text:
Q: Tableau Desktop refresh, connect to SQL Server I'm making some semi-live dashboards for my team, with pulled-data updated daily. This question got me about 70% of the way: Can Tableau Desktop be automatically refreshed when the database is updated
Specs are: Running windows 8, I have Tableau Desktop 10.1, data from SQL Server 2005, but extracted into a .tde
I need that final 30%, which is a bunch of some basic questions:

*

*In task scheduler, can I just run the command options as an argument (eg. tableau refreshextract), or do I have to create a separate .bat file?

*our database uses windows authentication, do I still need to state the username & password in parameters?

*In task scheduler, can I set to refresh multiple workbooks at one time, or is it better to execute separate instances?

*the .tde - I noticed it's stored locally. If the workbook is stored on a network folder, will it need to reference my tde, or do I have to move it somehow?

Thanks for any help!


text:
Q: Why PHP script execution gets serialized? I am using CakePHP3 -  Nginx + PHP7 on Windows8.
I have spawned multiple php-cgi processes for parralel execution. However what I have noticed, that in case of multiple concurrent ajax request from single host, request gets serialized.
I can confirm that there are some CPU usage spikes on multiple php-cgi instances, so it looks like requests are handled in parallel, but still they are serialized somehow. Any ideas what is serializing the calls?
Script does a simple repeatable and fast select from the DB that returns single row each.
Here is request timeline:

A: It's because Google Chrome limits 6 connections per host at the same time.
Ref: https://bugs.chromium.org/p/chromium/issues/detail?id=12066

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't take configuration value in view at 2.5.3 version? @play.Play.application.configuration.getString("application.host")
how can I take configuration value in view at 2.5.3 version?
Note that the view is used everywere. So I'm searching solution without setting parameters in all controllers.

A: import play.api.Configuration

val config = Configuration.load()
val mode = config.getString("application.host", defaultValueString)

the document is https://www.playframework.com/documentation/2.5.3/api/scala/index.html#play.api.Configuration
Good luck with you


text:
Q: Variance of $Y = a \cdot e^X$ if $X$ is Gussian random variable I have the following function
$$Y = a e^X$$
where $X$ is a normally distributed random variable. I would like to compute the variance of $Y$. So far I did the following
\begin{eqnarray}
\text{Var}(Y)
&= \text{Var}(ae^X)\\
&= a^2 \text{Var}(e^X)\\
&\approx a^2 e^{2E(X)} \text{Var}(X)
\end{eqnarray}
Where I used information I have found on this site on variance propagation. I would like to know if this calculation is correct and if there are better and more correct ways to compute $\text{Var}(Y)$? So far, this is only an approximation, if what I did is right.

A: If $X\sim N(\mu;\sigma^2)$ then $Y=e^X\sim\text{LogNormal}$ thus you can calculate $\mathbb{V}[Y]$ exactly
Lognormal distribution
$$\mathbb{V}[Y]=a^2\cdot e^{2\mu+\sigma^2}(e^{\sigma^2}-1)$$


text:
Q: Audio element default controls sliders I'm trying to use an element Audio into my app.
When i put my audio element like that:
<audio controls>
      <source src="http://dl.dropbox.com/u/1538714/article_resources/song.m4a" type="audio/mpeg">
</audio>

Audio element works fine, but when i try to use sliders for control volume/select a time song i can't drag the silders of default control, i only can click in the slider.
i want the default behaviour:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all
What i am doing wrong?

A: This code will help your access the sliders,

    Slide 3
    <audio preload="none" data-image="jsImgSlider/images/image-slider-5.jpg"
        data-alt="Lorem ipsum dolor sit amet" controls>
        <source data-src="prod/mcaudio.mp3" type="audio/mpeg">
        <source data-src="prod/mcaudio.ogg" type="audio/ogg">
    </audio>


text:
Q: Trying to hide specific div in jquery in php while loop I have this form being outputted from a PHP while loop :
echo '

      '.$ptitle.'

Posted on '.$pdate.'

'.$pdesc.'

    <form method="post" class="ibadForm">
        <input type="hidden" name="id" value="'.$pid.'">
        <input type="hidden" name="hiddenBad" value="yes">
        <input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
    </form>

';

I am trying to remove the individual .postCont when the ibadForm is clicked with jquery.
$(".ibadForm").submit(function(e) {
     var url = "add_form.php";
     var id = <?php echo $pid?>;
     $.ajax({
          type: "POST",
          url: url,
          data: $(this).serialize(),
          success: function(data)
         {
             $('.postCont' + id).hide();
         }
     });
     e.preventDefault();
 });

It submits the form to add_form.php fine but doesn't hide the postCont. If I remove the id from the class then it hides all post Cont's. Can anyone tell me where I am going wrong?

A: You could use closest() to get the parent div then hide it using hide() method like :
$(".ibadForm").submit(function(e) {
  var url = "add_form.php";
  var id = <?php echo $pid?>;
  var _this = $(this);

  $.ajax({
    type: "POST",
    url: url,
    data: $(this).serialize(),
    success: function(data)
    {
      _this.closest('.postCont').hide();
    }
  });
  e.preventDefault();
});

NOTE : You should store the $(this) object that refer to the clicked form in some variable (_this in my example) then use it inside the success callback since $(this) inside callback doesn't refer no more to the form, e.g :
_this.closest('.postCont').hide();

Hope this helps.


text:
Q: Python requests: How to PUT a string in body? I need to PUT data from a string (no dict) as the body of the call to a REST API.
When I call
r = requests.put(url, data = string)

then I can see in r.request.body after this call that it is None. Also, the server responds with a "411 Length Required" error.
However, when I try it with a dict instead of a string then it works, as the server responds with the correct JSON data. Moreover, in that case I can see in r.request.body the correct data.
Any ideas?
PS: I am using Python 2.7.3 and Python-requests 1.2.0

A: Even after three attempts to clarify the question, it still isn't clear what you're asking here, but I can try to throw out enough info that you can figure out the answer.
First, r = requests.put(url, data = string) returns a Response, which doesn't have a body, but it does have a request, and a history of 0 or more redirect requests, all of which are PreparedRequest objects, which do have body attributes.
On the other hand, if you did r.requests.Request(method='PUT', url=url, data=string), that would return a Request, which has to be prepare()d before it has a body.
Either way, if I do a simple test and look at the results, I find that the body is always correct:
>>> resp = requests.put('http://localhost/nosuchurl', data='abc')
>>> resp.request.body
'abc'
>>> resp = requests.put('http://localhost/redirect_to_https', data='abc')
>>> resp.history[-1].request.body
'abc'
>>> req = requests.Request(method='PUT', url='http://localhost/nosuchurl', data='abc')
>>> preq = req.prepare()
>>> preq.body
'abc'

My best guess is that you need to be looking at resp.history[0].request.body, but you're looking at resp.request.body, or something similar.
If Redirection and History in the quickstart tutorial doesn't help, read the detailed API docs, or just experiment with all of them until you figure it out.
Or do this:
resp = request.put('http://localhost/nosuchurl', data='abc', allow_redirects=False)

And then do the redirect-handling manually.


text:
Q: Python Pandas: combine 2 dataframes, one frame's column as the final result's index DataFrame df1:
+--------+------+--------+
| userId | isbn | rating |
+--------+------+--------+
|      1 | 0001 |      3 |
|      2 | 0002 |      4 |
|      2 | 0003 |      5 |
+--------+------+--------+

DataFrame df2:
+------+-------+
| isbn | title |
+------+-------+
| 0001 | aaa   |
| 0002 | bbb   |
| 0003 | ccc   |
+------+-------+

Can I merge them into:
+-----+-----+-----+
|     |  1  |  2  |
+-----+-----+-----+
| aaa | 3   | NAN |
| bbb | NAN | 4   |
| ccc | NAN | 5   |
+-----+-----+-----+

where the column is the userId, index is the title. isbn is dropped after the merge.
Thanks.

A: Once you merge these frames, you can use pivot_table:
In [11]: merged = df.merge(df2)

In [12]: merged
Out[12]:
   userId  isbn  rating title
0       1     1       3   aaa
1       2     2       4   bbb
2       2     3       5   ccc

In [13]: merged.pivot_table('rating', 'title', 'userId')
Out[13]:
userId   1   2
title
aaa      3 NaN
bbb    NaN   4
ccc    NaN   5


text:
Q: FullScreen picture from webcam I use openCV to take picture from the cam. Here is code:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glScalef( 1.0f, 1.0f, -1.0f);
glTranslatef(0,0,FOCAL_LENGTH);
glRasterPos2d(-width/2,height/2);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelZoom(1.0,-1.0);
glDrawPixels(bg->width, bg->height, GL_BGR_EXT, GL_UNSIGNED_BYTE, bg->imageData);

But when i maximized my window the picture size is only 640*480 - my webcam resolution. And it is only in top left corner of the window. What i must do to match picture size and window size.

A: You must resize the image using the cvResize function. Please note this may slow things down a bit depending upon your PC configuration.


text:
Q: How do I address a small /boot? I followed the common advice of making /boot on a different partition, and making it a nice and small partition, and all was find for a time.
Fast forward to now, and my partition that has /boot on it that is too small to receive any more updates. How can I safely address this?
Here is my layout according to the lsblk command:
NAME          MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda             8:0    0 931.5G  0 disk
├─sda1          8:1    0   256M  0 part  /boot
├─sda2          8:2    0   9.8G  0 part
│ └─cryptswap 253:0    0   9.8G  0 crypt [SWAP]
└─sda3          8:3    0 921.5G  0 part  /
sdb             8:16   0   3.7T  0 disk
├─sdb1          8:17   0   128M  0 part
└─sdb2          8:18   0   3.7T  0 part
sdc             8:32   0 465.8G  0 disk
├─sdc1          8:33   0   100M  0 part
├─sdc2          8:34   0   128M  0 part
└─sdc3          8:35   0 465.6G  0 part

OS is Pop_OS (an ubuntu derivative)
Contents of /boot:
config-4.18.0-18-generic      lost+found
config-4.18.0-25-generic      System.map-4.18.0-18-generic
config-5.0.0-21-generic       System.map-4.18.0-25-generic
grub                          System.map-5.0.0-21-generic
initrd.img-4.18.0-18-generic  vmlinuz-4.18.0-18-generic
initrd.img-4.18.0-25-generic  vmlinuz-4.18.0-25-generic
initrd.img-5.0.0-21-generic   vmlinuz-5.0.0-21-generic

A: It appears your /boot partition has enough space for three kernels, so you cannot add a newer kernel now until you delete the oldest.
Your oldest OS install would include the four files with names ending 4.18.0-18-generic, but rather than just delete them, you should remove them using whatever package tool you use to install them, e.g.
apt remove linux-image-4.18.0-18-generic


text:
Q: Rearrange python list to avoid any position matches I have 2 lists list1 and list2. How would I rearrange list1 (without rearranging list2) so that there are no matches on any positions eg:
UNDESIRED: list1 = ['A', 'B', 'C']  list2 = ['X', 'B', 'Z'] as you can see the B is on the same position, 1, in both lists…so I would then like to rearrange list1 to list1 = ['B', 'A', 'C'] or any other order where there are no positional matches with list2 WITHOUT rearranging list2

A: You could do this with the help of the itertools module. There may be better / more efficient mechanisms. Note that the process() function will return None when there is no possible solution.
import itertools

def process(L1, L2):
    for s in set(itertools.permutations(L1, len(L1))):
        if all([a != b for a, b in zip(s, L2)]):
            return s
    return None

list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']

print(process(list1, list2))

A: from itertools import permutations

def diff(list1, list2):
    for item in permutations(list1, len(list1)):
        if all(map(lambda a, b: a!=b, item, list2)):
            return list(item)
    return None

list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']

result = diff(list1, list2)
if result:
    print(result, 'vs', list2)

['A', 'C', 'B'] vs ['X', 'B', 'Z']

A: I solved it using this piece of code - however, as noted above, there are many possible cases where this very solution may not work. In this very case, you can try this:
import random
list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']
for i in list1:
    for j in list2:
        if i == j in list2:
            while list1.index(i) == list2.index(j):
                list1.remove(i)
                z = len(list1)
                rand = random.choice(range(z))
                list1.insert(rand, i)
print(list1, list2)

Also, note that you use quite weird apostrophes inside the list: ' instead of ' or ". AFAIK, Python won't be able to comprehend them correctly.


text:
Q: Applying jquery to first element of the list Hi i followed this link but i cannot get the output:
jQuery selector to find the first child in each of a set of elements.
I want to select first element of the list and make the fadein animation when i click the button having id "#add". I wrote code as follow but cant get the output. Please help.
HTML

                <input type="text" class="form-control" id="list_entry">

                    <button class="btn btn-default" type="button" id="add"></button>

something

something1

something2

something3

Jquery
 $("#add").live('click',function(){
 var li = $(this).parent().parent().next().find("li:eq(0)"); //how can i select first li
  li.animate(something);
 });

A: On your jQuery:
$(document).ready(function(){
    $('#add').click(function(){
        $('#inlist li:first').fadeOut('slow').fadeIn('slow');
    });
});

See fiddle here

A: move the eq outside of the selector, its a jquery function:
$("#add").live('click',function(){
    var li = $(this).parent().parent().next().find("li").eq(0); //how can i select first li
    li.animate(something);
});


text:
Q: How to divide dictionary values? I have a dictionary comprising of keys and values as integers in a lists, e.g.,
input: {
    'example_key1': [358, 57, 18602, 18388],
    'example_key2': [415, 12, 4800, 2013],
    'example_key3': [450, 10, 4500, 4500],
}

I wish to divide the last value with the second to last value in the list for every key, multiply the answer by 100 and enter the answer into a similar dictionary with with ndigit = 1 point round.
output: {
    'example_key1': [98.8],   # [round((((18388 / 18602)) * 100), 1)]
    'example_key2': [41.9],   # [round((((2103 / 4800)) * 100), 1)]
    'example_key3': [100.0],  # [round((((4500 / 4500)) * 100), 1)]
}

A: You can use dict-comprehension:
d = {
'example_key1': [358, 57, 18602, 18388],
'example_key2': [415, 12, 4800, 2013],
'example_key3': [450, 10, 4500, 4500]
}

out = {
    k: [round((j / i) * 100, 1)]
    for k, (*_, i, j) in d.items()
}

print(out)

Prints:
{'example_key1': [98.8], 'example_key2': [41.9], 'example_key3': [100.0]}

A: Try this (d is your input dict):
res={i:round(d[i][-1]/d[i][-2]*100, 1) if d[i][-2]!=0 else 0.0 for i in d}

print(res)

{'example_key1': 98.8, 'example_key2': 41.9, 'example_key3': 100.0}

A: Try this,
input = {
    'example_key1': [358, 57, 18602, 18388],
    'example_key2': [415, 12, 4800, 2013],
    'example_key3': [450, 10, 4500, 4500]
}

rounded_values = list(map(lambda item: round((item[3] / item[2]) * 100, 1), input.values()))
output_dict = dict()

for key, value in zip(input.keys(), rounded_values):
    output_dict[key] = value

print(output_dict)


text:
Q: AVCam memory low warning This is less a question and more a record of what I've found around the AVCam sample code provided by Apple for iOS4 and 5 camera manipulation. The symptoms of the problem for me were that my app would crash on launching the AVCamViewController after taking around 5-10 photos.
I ran the app through the memory leak profiler and there were no apparent leaks but on inspection with the Activity Monitor I discovered that something called mediaserverd was increasing by 17Mb every time the camera was launched and when it reached ~100Mb the app crashed with multiple low memory warnings.

A: Apple revised the sample code on Oct 17 2013, fixing the retain cycle. The issue is due to a improper usage of self within the blocks defined in the init.
Here's the revision description

Fixed retain cycles in AVCaptureManager that result in leaks. NOTE - if you've adapted AVCam code in your app, you should adopt the fixes made here in AVCaptureManager.m's init method. Without these fixes, you may be leaking AVCaptureManager instances and leaving the camera running constantly while your app is in the foreground.

However, the fix they introduced only works in case of Manual Retain Count. If you are using ARC on the project, apart from getting rid of release/retain calls and other obvious things, the storage qualifier for weakSelf has to be changed from __block to __weak, like follows.
__weak AVCamCaptureManager *weakSelf = self;

In fact the semantic of __block changed with ARC. In MRC it caused the variable to be weakly referenced, wheres in ARC it does not and __weak must be used for this purpose.
More information about this topic can be found here: How do I avoid capturing self in blocks when implementing an API?
Using the new init implementation from the last revision and using __weak instead of __block, finally caused the dealloc method to be properly called.

Finally, for those who hate to carry around old legacy code, here's a modernized version of the AVCam project: https://github.com/Gabro/AVCam
Features:

*

*memory leaks free

*uses ARC

*modern Objective-C syntax

*minor UI fixes for iOS 7

A: Ran into this problem recently. I found that the real root problem was that deviceConnectedBlock and deviceDisconnectedBlock were implicitly referring to self, leading to retain cycles. To fix it, change all the ivar references in those blocks to use weakSelf.
This way, you won't need to remember to call a teardown method explicitly.
Hope this helps someone else.
REF: View controller dealloc not called when using NSNotificationCenter code block method with ARC

A: First thing I did was put logging into the dealloc methods of all the AVCam files. I quickly discovered that the AVCamCaptureManager and AVCamRecorder weren't being deallocated when the AVCamViewController was. I checked out the retain and release calls and they appeared to balance so I put a breakpoint on the [captureManager release] and discovered that it had a retainCount of 2 AFTER the release (and hence the AVCamCaptureManager dealloc wasn't being called).
Next I stepped through the creation process for the capture manager and discovered that it had a retain count of 3 immediately after the init method was called.
Stepping through the init method and checking the retain count on every line I discovered the following two lines were both incrementing the retain count:
[self setDeviceConnectedObserver=[notificationCenter addObserverForName:AVCaptureDeviceWasConnectedNotification object:nil queue:nil usingBlock:deviceConnectedBlock]];
[self setDeviceDisconnectedObserver=[notificationCenter addObserverForName:AVCaptureDeviceWasDisconnectedNotification object:nil queue:nil usingBlock:deviceDisconnectedBlock]];

Looking through I found that the removeObserver counterparts were INSIDE the dealloc method of the AVCamCaptureManager (which wasn't being called) and so the retain count never dropped to 0.
To fix it I created a new public removeObservers method:
 -(void)removeObservers {
     NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
     [notificationCenter removeObserver:[self deviceConnectedObserver]];
     [notificationCenter removeObserver:[self deviceConnectedObserver]];
 }

and taking the same lines OUT of the AVCamCaptureManager dealloc method.
Calling [captureManager removeObservers]; and THEN calling [captureManager release]; in the AVCamViewController dealloc method successfully drops the retain count to 0.
Testing with the Activity Monitor now has the mediaserverd process humming at only 5-17Mb and the crashing stops!
Hope this helps anyone else having this problem!


text:
Q: How to use phones camera as a background? I am trying to create the camera as my background in xamarin forms where I plan to add things on top of the cameraview in my shared code.
Right now I am doing it for iOS-devices. I get a crash on this line of code right now: Frame = liveCameraStream.Bounds with the error: Object reference not set to an instance of an object.
So my question is how can I adjust my current code to get a camera as a background in xamarin forms?
This is my renderer in iOS:
[assembly: ExportRenderer(typeof(ICameraBackground), typeof(CameraBackground_iOS))]
namespace project.iOS
{
public class CameraBackground_iOS : ViewRenderer
{
    AVCaptureSession captureSession;
    AVCaptureDeviceInput captureDeviceInput;
    AVCaptureStillImageOutput stillImageOutput;
    UIView liveCameraStream;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);
        SetupLiveCameraStream();
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        SetupLiveCameraStream();
    }

    public async void SetupLiveCameraStream()
    {
        await AuthorizeCameraUse();
        captureSession = new AVCaptureSession();

        var videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
        {
            Frame = liveCameraStream.Bounds
        };
        liveCameraStream.Layer.AddSublayer(videoPreviewLayer);

        var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
        ConfigureCameraForDevice(captureDevice);
        captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);

        var dictionary = new NSMutableDictionary();
        dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
        stillImageOutput = new AVCaptureStillImageOutput()
        {
            OutputSettings = new NSDictionary()
        };

        captureSession.AddOutput(stillImageOutput);
        captureSession.AddInput(captureDeviceInput);
        captureSession.StartRunning();
    }

    public void ConfigureCameraForDevice(AVCaptureDevice device)
    {
        var error = new NSError();
        if (device.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
        {
            device.LockForConfiguration(out error);
            device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
            device.UnlockForConfiguration();
        }
        else if (device.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
        {
            device.LockForConfiguration(out error);
            device.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
            device.UnlockForConfiguration();
        }
        else if (device.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
        {
            device.LockForConfiguration(out error);
            device.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
            device.UnlockForConfiguration();
        }
    }

    public async Task AuthorizeCameraUse()
    {
        var authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
        if (authorizationStatus != AVAuthorizationStatus.Authorized)
        {
            await AVCaptureDevice.RequestAccessForMediaTypeAsync(AVMediaType.Video);
        }
    }

A: Xamarin.Forms.Labs, a MVVM framework for Xamarin.Forms, has a CameraView that you can use. It has been implemented for both platforms as well. If you don't want to install the entire package, you can simply grab the source. But don't forget to add the appropriate license to your project if you decide to do so.
The CameraView can be consumed quite easily in a Xamarin.Forms project like so:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="XLabs.Samples.Pages.Controls.CameraViewPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms">
<StackLayout>
    <controls:CameraView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
</StackLayout>


text:
Q: How to stop a script within a script I'm looking to control a script via Zigbee/XBee using X-CTU. I've created a script named zb_control.py. Now I'm trying to start and stop another script within this script. A script adxl345test.py is used to collect data from an attached accelerometer on my Raspberry Pi.
The idea behind the zb_control.py script is that I run it and then if I type "run" in X-CTU the script will start running adxl345test.py and collect data.
I'm trying to create a script within a script that can also be stopped again and then still have the zb_control.py running ready to recieve new input from X-CTU.
As you can tell I've tried different things:
import serial, time, sys, os, subprocess
from subprocess import check_call
from subprocess import call

while True:

    ser=serial.Serial('/dev/ttyUSB0',9600,timeout=2)
    inc=ser.readline().strip()

    if inc=='run':
        print("---------------")
        print("Collecting data")
        print("---------------")
        p = subprocess.Popen("/home/pi/adxl345test.py", stdout=subprocess.PIPE, shell=True)

    elif inc=='stop':
        # check_call(["pkill", "-9", "-f", adxl345test.py])
        # serial.write('\x03')
        # os.system("pkill –f adxl345test.py")
        # call(["killall", "adxl345test.py"])
        p.kill()
        print("-----------------------")
        print("Script has been stopped")
        print("-----------------------")

I got it to run and it's now collecting data properly. However now the problem is stopping the adxl345test.py again. As you can tell from the script from above I'm using p.kill() but the script doesn't stop collecting data. When I type "stop" in XCTU my zb_control.py does print the print-commands but the p.kill() isn't being executed. Any suggestions?
I've tried using p.terminate() alone and together with p.kill() aswell as the commands by themselves however it doesn't stop the adxl345test.py script. I can tell that the .csv-file is still increasing in size and therefore the script must still be collecting data.

A: Here is the adxl345test.py script for those interested:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Example on how to read the ADXL345 accelerometer.
# Kim H. Rasmussen, 2014
import sys, math, os, spidev, datetime, ftplib

# Setup SPI
spi = spidev.SpiDev()
#spi.mode = 3    <-- Important: Do not do this! Or SPI won't work as intended, or even at all.
spi.open(0,0)
spi.mode = 3

# Read the Device ID (should be xe5)
id = spi.xfer2([128,0])
print 'Device ID (Should be 0xe5):\n'+str(hex(id[1])) + '\n'

# Read the offsets
xoffset = spi.xfer2([30 | 128,0])
yoffset = spi.xfer2([31 | 128,0])
zoffset = spi.xfer2([32 | 128,0])
accres = 2
accrate = 13
print 'Offsets: '
print xoffset[1]
print yoffset[1]
# print str(zoffset[1]) + "\n\nRead the ADXL345 every half second:"

# Initialize the ADXL345
def initadxl345():
    # Enter power saving state
    spi.xfer2([45, 0])
    # Set data rate to 100 Hz. 15=3200, 14=1600, 13=800, 12=400, 11=200, 10=100 etc.
    spi.xfer2([44, accrate])

    # Enable full range (10 bits resolution) and +/- 16g 4 LSB
    spi.xfer2([49, accres])

    # Enable measurement
    spi.xfer2([45, 8])

# Read the ADXL x-y-z axia
def readadxl345():
    rx = spi.xfer2([242,0,0,0,0,0,0])

    #
    out = [rx[1] | (rx[2] << 8),rx[3] | (rx[4] << 8),rx[5] | (rx[6] << 8)]
    # Format x-axis
    if (out[0] & (1<<16 - 1 )):
        out[0] = out[0] - (1<<16)
#   out[0] = out[0] * 0.004 * 9.82
    # Format y-axis
    if (out[1] & (1<<16 - 1 )):
        out[1] = out[1] - (1<<16)
#   out[1] = out[1] * 0.004 * 9.82
    # Format z-axis
    if (out[2] & (1<<16 - 1 )):
        out[2] = out[2] - (1<<16)
#   out[2] = out[2] * 0.004 * 9.82

    return out

# Initialize the ADXL345 accelerometer
initadxl345()

# Read the ADXL345 every half second
timetosend = 60
while(1):
    with open('/proc/uptime','r') as f: # get uptime
        uptime_start = float(f.readline().split()[0])
    uptime_last = uptime_start
    active_file_first = "S3-" + str(pow(2,accrate)*25/256) + "hz10bit" + str(accres) + 'g' + str(datetime.datetime.utcnow().strftime('%y%m%d%H%M')) $
    active_file = active_file_first.replace(":", ".")
    wStream = open('/var/log/sensor/' + active_file,'wb')
    finalcount = 0
    print "Creating " + active_file
    while uptime_last < uptime_start + timetosend:
        finalcount += 1
        time1 = str(datetime.datetime.now().strftime('%S.%f'))
        time2 = str(datetime.datetime.now().strftime('%M'))
        time3 = str(datetime.datetime.now().strftime('%H'))
        time4 = str(datetime.datetime.now().strftime('%d'))
        time5 = str(datetime.datetime.now().strftime('%m'))
        time6 = str(datetime.datetime.now().strftime('%Y'))
        axia = readadxl345()
        wStream.write(str(round(float(axia[0])/1024,3))+','+str(round(float(axia[1])/1024,3))+','+str(round(float(axia[2])/1024,3))+','+time1+','+ti$
    # Print the reading
    # print axia[0]
    # print axia[1]
    # print str(axia[2]) + '\n'
    # elapsed = time.clock()
    # current = 0
    # while(current < timeout):
    #   current = time.clock() - elapsed
        with open('/proc/uptime', 'r') as f:
                uptime_last = float(f.readline().split()[0])
    wStream.close()

def doftp(the_active_file):
    session = ftplib.FTP('192.0.3.6','sensor3','L!ghtSp33d')
    session.cwd("//datalogger//")
    file = open('/var/log/sensor/' + active_file, 'rb')   # file to send
    session.storbinary('STOR' + active_file, file)        # send the file
    file.close()
    session.quit

A: My suggestions:

*

*If you're doing something at a specified interval, you're probably better off using threading.Timer rather than checking the time yourself.

*As I said in the comment, you can check for an exit condition instead of brutally killing the process. This also allows to properly clean up what you need.

*Those time1...time6 really don't look nice, how about a list? Also, time2, time3, time4, time5, time6 are not used.

*You don't actually need strftime to get hour, day, month, year, etc. They're already there as attributes.

You can do something like:
cur_time = datetime.datetime.now()
cur_hour = cur_time.hour
cur_minute = cur_time.minute

...And so on, which is a bit better. In this specific case it won't matter, but if you start measuring milliseconds, the time will be slightly different after a few lines of code, so you should store it and use it from the variable.
As for the rest, if you want an example, here I check that a file exists to determine whether to stop or not. It's very crude but it should give you a starting point:
from threading import *
from os.path import exists

def hello():
    print('TEST') # Instead of this, do what you need
    if (exists('stop_file.txt')):
        return
    t = Timer(0.5, hello)
    t.start()

hello()

Then in the other create you create the stop file when you want it to stop (don't forget to add a line to remove it before starting it again).


text:
Q: Copy the content of an appxmainfest file to another using Pre-build command I've been trying to get this re-build command working for a Windows 8 Project in Visual Studio 2012.
if "$(ConfigurationName)"==ReleaseOEM copy "$(ProjectDir)PackageOEM.appxmainfest" "$(ProjectDir)Package.appxmainfest" copy "$(ProjectDir)StoreManifestOEM.xml" "$(ProjectDir)StoreManifest.xml"

The xml file StoreManifest.xml is copied every time I do a rebuild; however the Package.appxmainfest is never changed.
What have I done wrong?

A: This worked in a test project ...
if "$(ConfigurationName)"=="Debug" copy "$(ProjectDir)Package.appxmanifest" "$(ProjectDir)Package2.appxmainfest"

The only real difference is I added quotes around Debug.  It does not copy the file without the quotes. According to MSDN, you need to separate commands by line breaks.  Yours should probably look something like ...
if "$(ConfigurationName)"=="ReleaseOEM" copy "$(ProjectDir)PackageOEM.appxmainfest" "$(ProjectDir)Package.appxmainfest"
if "$(ConfigurationName)"=="ReleaseOEM" copy "$(ProjectDir)StoreManifestOEM.xml" "$(ProjectDir)StoreManifest.xml"


text:
Q: Number of data files in tempdb in Availability Group We have configured AlwaysOn Availability Group with 3 node in Sync mode. The primary server got 16 core while the replicas have 10 core each. We have tempdb contention issue, just wondering if we can have different number of tempdb data files on nodes in Availability Group or do we have to have same number on each node. It is SQL Server 2016 Enterprise Edition.
Thanks in advance for help.

A: There is not a problem with having different numbers of tempdb files on each machine,  you just need to be aware that should you failover to one of the machines with fewer files that you will run into the contention problem that you worked to alleviate on the new server.


text:
Q: ASP.NET MVC in a virtual directory I have the following in my Global.asax.cs
routes.MapRoute(
    "Arrival",
    "{partnerID}",
    new { controller = "Search", action = "Index", partnerID="1000" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

My SearchController looks like this
public class SearchController : Controller
{
    // Display search results
    public ActionResult Index(int partnerID)
    {
        ViewData["partnerID"] = partnerID;
        return View();
    }
}

and Index.aspx simply shows ViewData["partnerID"] at the moment.
I have a virtual directory set up in IIS on Windows XP called Test.
If I point my browser at http://localhost/Test/ then I get 1000 displayed as expected. However, if I try http://localhost/Test/1000 I get a page not found error. Any ideas?
Are there any special considerations for running MVC in a virtual directory?

A: IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so?

This happens because IIS 6 only
  invokes ASP.NET when it sees a
  "filename extension" in the URL that's
  mapped to aspnet_isapi.dll (which is a
  C/C++ ISAPI filter responsible for
  invoking ASP.NET). Since routing is a
  .NET IHttpModule called
  UrlRoutingModule, it doesn't get
  invoked unless ASP.NET itself gets
  invoked, which only happens when
  aspnet_isapi.dll gets invoked, which
  only happens when there's a .aspx in
  the URL. So, no .aspx, no
  UrlRoutingModule, hence the 404.

Easiest solution is:

If you don't mind having .aspx in your
  URLs, just go through your routing
  config, adding .aspx before a
  forward-slash in each pattern. For
  example, use
  {controller}.aspx/{action}/{id} or
  myapp.aspx/{controller}/{action}/{id}.
  Don't put .aspx inside the
  curly-bracket parameter names, or into
  the 'default' values, because it isn't
  really part of the controller name -
  it's just in the URL to satisfy IIS.

Source: http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/

A: If you are doing this on Windows XP, then you're using IIS 5.1.  You need to get ASP.Net to handle your request.  You need to either add an extension to your routes ({controller}.mvc/{action}/{id}) and map that extension to ASP.Net or map all requests to ASP.Net.  The http://localhost/Test works because it goes to Default.aspx which is handled specially in MVC projects.
Additionally, you need to specify http://localhost/Test/Search/Index/1000.  The controller and action pieces are not optional if you want to specify an ID.

A: There are a number of considerations when using virtual directories in your application.
One is particular is that most browsers will not submit cookies that came from one virtual directory to another, even if the apps reside on the same server.

A: Try set virtual path: right click on mvc project, properties, web tab, there enter appropriate location.


text:
Q: Pythonic way to handle vat number validation I have a case where I want to validate an entered vat number. Each European country has a pre-defined format and I can create a regex pattern to validate an entered number.
My question is what would be the most "pythonic" way to handle this for 20 countries. Should I create a dictionary with each of the country and its pattern
Example
VAT_PATTERNS = {
   'ES': '([A-Z0-9][0-9]{7}[A-Z0-9]$)',
   'DE': '([0-9]{9}$)',
}

or is there a more pythonic way?
There are cases where several countries have the same pattern. Some countries might also have more complex patterns.
I could create a VAT base class from where each country's class inherits and handle it that way but that seems a bit out of place.

A: Part of the "Zen of Python" (type import this into an interpreter!) is that "Explicit is better than implicit" and "Simple is better than complex".
What you've described looks both simple and explicit, and so I would consider it pretty pythonic.

A: (I'm not sure there is a real answer to questions like this one --
what's "pythonic" and what is not is still much influenced by personal
taste, IMHO.  But since you ask for it, here's my take.)
The Zen of Python says:

Explicit is better than implicit.
  Simple is better than complex.

So, in your case, I'd say that a mapping country to VAT pattern, as
you propose, is the simplest and most explicit solution, and therefore
the most "pythonic" one.

A: The only place for improvement could be storing the shared patterns in variables named with a descriptive name (like for example VAT_PATTERN_WESTERN_EUROPE) and then use it in the map values.
But as this is unlikely to ever change, and if it does it will probably not change in all the countries at the same time, it seems a better option to just leave it as a constant expression in the values.

A: I think your solution is great; simple and explicit.  You could reduce duplication by doing something like this, assuming Spain, Italy, and the UK all use the same VAT (sorry, I'm Canadian; not factually accurate):
VAT_PATTERNS = {
   'ES': '([A-Z0-9][0-9]{7}[A-Z0-9]$)',
   'DE': '([0-9]{9}$)',
}
VAT_PATTERNS['IT'] = VAT_PATTERNS['UK'] = VAT_PATTERNS['ES']

Or even shorter:
VAT_PATTERNS = {
   'ES': '([A-Z0-9][0-9]{7}[A-Z0-9]$)',
   'DE': '([0-9]{9}$)',
}
V = VAT_PATTERNS # I like to use a short alias for speed
V['IT'] = V['UK'] = V['ES']
del V


text:
Q: Trying to remember title of a book about people on an asteroid/comet I'm trying to remember the title of a book.  The plot was a group of people are stranded on a comet or asteroid.  They establish kind of a colony inside it, and rig up rockets on the surface to move it.  Some of the people discover some sort of algae type life form inside it, which bonds with and mutates people helping them to survive.  They set the asteroid to head for Earth but have to change the course when authorities on Earth threaten to blow the asteroid up because of the mutations.

A: Indeed this is Heart of the Comet, a 1987 book by David Brin and Gregory Benford.  I've read this book so many times and it never loses its appeal...

A group of spacers and scientists land on Halleys Comet, and set about harvesting it for the materials and metals that comets are made of.   They install mass launchers in order to change the orbit of the comet, to bring it into the inner solar system and make the harvesting easier.
Unexpectedly they encounter life within Halley, life that lives deep within the comet, life that is inimical to start with but the spacers and scientists gradually adjust and come to terms with the Halley-life (as they call it).  Earth attempts to blow up the comet to stop any of the extra-terrestrial life reaching earth, so the comet crew change trajectory to move out of the solar system.
This is a really good hard sf story, totally recommended...


text:
Q: Unzip files using ZipArchive- iOS I have an iPhone app in which I have to download a zip file and unzip the components. I've been suggested to use ZipArchive to do this job for me and so far i ve found it very useful.
My question is does the open source library - ZipArchive automatically do the checksum(CRC check) while extracting/unzipping files?
Or do I need to perform this separately to ensure that the files are not corrupted by any means?
What do you guys think? What's the way forward for me?

A: Looking into the code, ZipArchive (http://code.google.com/p/ziparchive/) checks CRC when the extracted file stream is being closed (unzCloseCurrentFile), so the answer is yes.


text:
Q: "Einstein must have been wrong" I have a memory of a brief throw-away passage in a book by a well-known sci-fi author which talks about a FTL drive invented by "O'Malley" (or an equally stereotypical Irish name). When asked how he got around Einstein's laws, O'Malley says something like "To be sure, Einstein must have been wrong".
Not much to go on, I know. Any identifications?
This was probably at least a twenty year old book.

A: Maybe the Skylark Series?

Crane: Three hundred and fifty million miles [in twenty minutes]. Half-way out of the solar system. That means a constant acceleration of about one light.
Seaton: Nothing can go that fast, Mart. E Equals M C square.
Crane: Einstein's Theory is still a theory. This distance is an observed fact.
Seaton: And theories are modified to fit facts. Hokay.

A: Sounds to me like something that would be said by the title character of Callahan's Crosstime Saloon, by Spider Robinson.

A: The books: "The Stone Canal" and "The Cassini Division" by Ken MacLeod feature a wormhole attached to some sort of near C (or actually much greater than C I think) probe. The wormhole is known as the Malley Mile in honour of the work of a Physicist called I. K. Malley who features in the second of those two books. I don't remember that particular quote but it could quite conceivably be in there.
The books mentioned are the 2nd and 3rd books of the Fall Revolution sequence.

A: This is a long shot, but you might be thinking of the bolded passage below:

Arcot and Wade were laughing, but not Robert Morey. With a sorrowful expression, he walked to the window and looked out at the hundreds of slim, graceful aircars that floated above the city.
"My friends," said Morey, almost tearfully, "I give you the great Dr. Arcot. These countless machines we see have come from one idea of his. Just an idea, mind you! And who worked it into mathematical form and made it calculable, and therefore useful? I did!
"And who worked out the math for the interplanetary ships? I did! Without me they would never have been built!" He turned dramatically, as though he were playing King Lear. "And what do I get for it?" He pointed an accusing finger at Arcot. "What do I get? He is called 'Earth's most brilliant physicist', and I, who did all the hard work, am referred to as 'his mathematical assistant'." He shook his head solemnly. "It's a hard world."
At the table, Wade frowned, then looked at the ceiling. "If you'd make your quotations more accurate, they'd be more trustworthy. The news said that Arcot was the 'System's most brilliant physicist', and that you were the 'brilliant mathematical assistant who showed great genius in developing the mathematics of Dr. Arcot's new theory'." Having delivered his speech, Wade began stoking his pipe.
Fuller tapped his fingers on the table. "Come on, you clowns, knock it off and tell me why you called a hard-working man away from his drafting table to come up to this play room of yours. What have you got up your sleeve this time?"
"Oh, that's too bad," said Arcot, leaning back comfortably in his chair. "We're sorry you're so busy. We were thinking of going out to see what Antares, Betelguese, or Polaris looked like at close range. And, if we don't get too bored, we might run over to the giant model nebula in Andromeda, or one of the others. Tough about your being busy; you might have helped us by designing the ship and earned your board and passage. Tough." Arcot looked at Fuller sadly.
Fuller's eyes narrowed. He knew Arcot was kidding, but he also knew how far Arcot would go when he was kidding—and this sounded like he meant it. Fuller said: "Look, teacher, a man named Einstein said that the velocity of light was tops over two hundred years ago, and nobody's come up with any counter evidence yet. Has the Lord instituted a new speed law?"
"Oh, no," said Wade, waving his pipe in a grand gesture of importance. "Arcot just decided he didn't like that law and made a new one himself."
"Now wait a minute!" said Fuller. "The velocity of light is a property of space!"
Arcot's bantering smile was gone. "Now you've got it, Fuller. The velocity of light, just as Einstein said, is a property of space. What happens if we change space?"

That's from the Project Gutenberg etext of the Ace Books edition of John W. Campbell's novel Islands of Space in his Arcot, Morey and Wade series.  I suppose Morey could be your "O'Malley" although Arcot was the main inventor of the FTL drive and Morey merely his "mathematical assistant". But they are not exactly saying "Einstein was wrong" so this is not a very good match to the question. Like I said, a long shot. (My first guess was The Skylark of Space but that's already taken.)


text:
Q: What's wrong in this caching function in Django? I've created the model for counting the number of views of my page:
class RequestCounter(models.Model):
    count = models.IntegerField(default=0)
    def __unicode__(self):
        return str(self.count)

For incrementing the counter I use:
def inc_counter():
    counter = RequestCounter.objects.get_or_create(id =1)[0]
    counter.count = F('count') + 1
    counter.save()

Then I show the number of the page views on my page and it works fine.
But now I need to cache my counter for some time. I use:
def get_view_count():
    view_count = cache.get('v_count')
    if view_count==None:
        cache.set('v_count',RequestCounter.objects.filter(id = 1)[0],15)
    view_count = cache.get('v_count')
    return view_count

After this I'm passing the result of get_view_count to my template.
So I expect, that my counter would now stand still for 15 sec and then change to a new value. But, actually, it isn't quite so: when I'm testing this from my virtual ubuntu it jumps, for example, from 55 to 56, after 15 secs it changes and now jumps from 87 to 88.
The values are always alternating and they don't differ much from each other.
If I'm trying this locally from windows, the counter seems to be fine, until I try to open more than browser.
Got no idea what to do with it. Do you see what can be the problem?

p.s. i tried using caching in the templates  - and received the same result.

A: What CACHE_BACKEND are you using? If it's locmem:// and you're running Apache, you'll have a different cache active for each Apache child, which would explain the differing results. I had this a while ago and it was a subtle one to work out. I'd recommend switching to memcache if you're not already on it, as this won't give you the multiple-caches problem


text:
Q: Custom URL Scheme RubyMotion I am needing to go to a specified ViewController in my app. I can get to the rootViewController just fine when entering scheme:// in Safari as I've edited my Info.plist. I even came across this:
https://stackoverflow.com/a/10925872/1327809
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
[self.viewController presentModalViewController:controller animated:YES];
[controller release];

return YES;
}

which is exactly what I want to do with just one problem. I'm having to use RubyMotion (which I'm new to) and therefore don't even have a nib file.
def application( application, handleOpenURL:url )
// desired code

end

Thank you for any possible help and let me know if you need more info.
Updated 6/14/12
I found out that the handOpenURL method is deprecated so now I'm using its replacement.
I've included my code because I cannot for the life of me figure out why I'm getting the black screen. I even removed the if/else from controller.rb and just had it run the   initial view controller no matter if through Safari or by directly clicking app and if through Safari, it still was black. If this should be in a new question, please let me know and I will start a new question.
Both didFinishLaunchingWithOptions and openURL have to pass through the workFlowController method which then sends us to controller.rb and runs the method viewWillAppear. It is there that having a URL determines which view controller runs.
I think it's something in app_delegate.rb that isn't coded right. I don't know how the new openURL method code should be different other than what I've commented below. Is there a way to see my logs (I use log and puts within the methods in question) in my console when I run rake device? I would need it to still log when I completely exit the app and try to go back in via Safari because according to the Apple Docs, "If an application is launched as a result of another application requesting it to open a URL resource, UIApplication first sends the application a application:didFinishLaunchingWithOptions: message and then it invokes this method." I'd like to see if this happens in my app when the app isn't running but I open it via URL.
Any feedback would be greatly appreciated. Again, I thank you for your help up to this point. I will keep looking as well.
app_delegate.rb
class AppDelegate
...
  def application( application, didFinishLaunchingWithOptions: launchOptions )
  ...
     @window.rootViewController = self.workFlowController
  ...
  true
  end

  def application( application, openURL: url, sourceApplication: sourceApplication, annotation: annotation )

     if sourceApplication !=nil
       #should I now be using this instead of from_open_url?
     end
     ...
     @window.rootViewController = self.WorkFlowController

     @window.rootViewController.from_open_url = true
     ...
     true
  end

  def workFlowController

     @_workFlowController ||= begin

     wfController = Auth::Controller.alloc.init

     wfController.delegate = self

     # return wf controller
     wfController

     end
  end
  ...
end

controller.rb
module Auth

  class Controller < BaseController
  ...
     attr_accessor :delegate, :from_open_url
  ...
     def viewWillAppear( animated )

        super

        # app loads from URL, password reset controller loads first
        if (@from_open_url)

           self.presentViewController(
             self.urlController,
             animated: false
           )

        else

           self.presentViewController(
             self.otherController,
             animated: false
           )

        end

     end
     ...
  end
end

A: I don't know your exact app setup, but you should just be able to use MyViewController.alloc.init instead. Here's a full working example. This loads a default image (foo.png), but if the app is opened via the URL, it presents a modal view with a different image (bar.png).
class AppDelegate
  def application(application, didFinishLaunchingWithOptions:launchOptions)
    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    @viewController = Foo.alloc.init
    @window.rootViewController = @viewController
    @window.rootViewController.wantsFullScreenLayout = true
    @window.makeKeyAndVisible
    true
  end

  def application(application, openURL:url, sourceApplication:sourceApp, annotation:annotation)
    # Here's where you might parse the url and decide which view controller to use
    controller = Bar.alloc.init
    @viewController.presentModalViewController(controller, animated:true)
    true
  end
end

class Foo < UIViewController
  def viewDidLoad
    self.view = UIImageView.alloc.initWithImage(UIImage.imageNamed('foo.png'))
  end
end

class Bar < UIViewController
  def viewDidLoad
    self.view = UIImageView.alloc.initWithImage(UIImage.imageNamed('bar.png'))
  end
end


text:
Q: Редирект в Code Igniter Здравствуйте.
Мне нужно осуществить редирект в фреймворке Code Igniter (редирект на класс, вида: www.site.ru -> www.site.ru/myclass/ ), при этом не задавая класс по умолчанию и не используя редирект htaccess (из-за специфичности фреймворка он создает бесконечный цикл). Как это можно сделать?


text:
Q: App for managing my app? I'm releasing my first large app soon, and I've been thinking of writing a small app to manage the databases for my own app with master privileges, to clean up data and the like. This will just be a dev project shared with a few people within the company.
Is this something that people do?
Has anyone had any experience with this?
It feels like a good idea, but I'd also really love feedback.

A: I'm assuming when you say database you are not referring to coredata specifically but rather some remote database. There is certainly nothing wrong with you creating tools to help you do your job.
I think really this answer is going to come down to time management. If your database has complicated relationships,etc that a simple database editor is not going to be able to maintain or will be highly prone to human error mistakes, I'd say go for it. But, if you are just making trivial changes it might be a more efficient use of time to use a existing solution.


text:
Q: Animated Node does not exist with tag 1 We recently updated to Expo SDK 40 and now have run into a issue with "React Native: Animated Node with tag 1 does not exist".
This is only an error on Android that is occurring.
We've changed all instances of useNativeDriver to false.
We've also tried commenting out all instances of Animated in our code and the error still persists.
Any ideas on what is going on here?

A: This isn't a full answer because I'm sure there was a fix for SDK 40 but Expo SDK 41 came out today and figured I'd see if that fixed the issue and it did.
For anyone that is stuck.  SDK 41 using expo upgrade might be your solution.


text:
Q: Doxygen does not generate automatic links in markdown code blocks Using doxygen 1.8.13, how can I get automatic links to be generated in markdown code?  For example, I have the following two file:
test.h
/**
 * Function foo.
 * This is a code snippet in markdown format:
 *
 *          foo("Hello World!!!");
 *
 *  This is a regular code snippet:
 *  \code
 *  foo("Hello World!!!");
 *  \endcode
 **/
 void foo(const char *hello);

And the following companion file:
test.md
# Markdown Test

This is a code snippet in markdown format:

    foo("Hello World!!!");

This is a regular code snippet:
\code
foo("Hello World!!!");
\endcode

The output that I have when running doxygen on these files look like this:
test.h

Notice how the second snippet has generated a link for the foo, but the first hasn't.
test.md

Notice how none of the snippets has generated a link for the foo function - also, the formatting is quite different.
So the question: is there a way to configure doxygen such that automatic links are generated in the code sections of markdown documents?

A: Answering my own question.

*

*From what I see, doxygen will not properly highlight indented code blocks. It will format them as code, but will not attempt to guess the language of the code; This can be resolved in by using a fenced code block - which will be assumed to be in the same language of the file it is found in. This works as expected:

foo.h
/**
 * Function foo.
 * This does not work properly:
 *
 *          foo("Hello World!!!");
 *
 *  But this does:
 *  ```
 *  foo("Hello World!!!");
 *  ```
 **/
 void foo(const char *hello);

*

*When writing code samples in markdown files (.md), doxygen will not automatically guess the code language. The solution when hosting code examples in .md files was simply to specify the language. Thereafter, automatic links are properly generated:

foo.md
# Markdown Test

This does not work properly:

    foo("Hello World!!!");

But this does
```{cpp}
foo("Hello World!!!");
```


text:
Q: How To Optimize JSF applications I'm rewriting the questions to expand to broader context.
I would like to optimize my JSF web application by minifying CSS and JS, optimizing AJAX requests and basically learning the rules of efficient JSF web apps.
Emphasis on JSF since much of the page is built by the JSF framework although there are client side Javascript files that need optimization as well..

A: If you're using richfaces:

<context-param>
    <param-name>org.ajax4jsf.COMPRESS_SCRIPT</param-name>
    <param-value>true</param-value>
</context-param>

<context-param>
    <param-name>org.richfaces.LoadStyleStrategy</param-name>
    <param-value>all</param-value>
</context-param>

<context-param>
    <param-name>org.richfaces.LoadScriptStrategy</param-name>
    <param-value>all</param-value>
</context-param>

More info on this blog
Optimizing the ajax call is a too much generic question, it depends much on the widget library you are using. Try to be specific, otherwise this question may be closed.


text:
Q: NumPy fancy indexing with provided output array I have a two-dimensional array and index it with a pair of arrays (in fact my arrays are much larger, millions of elements):
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a[[0, 0, 0, 1], [0, 1, 2, 0]]

Indexing will allocate a new array. Is there a way to do this indexing with an output array provided?
I looked at np.take and np.choose, but it seems that they don't work with a pair of arrays. I managed to use np.take(..., out=buf) if I ravel the array and manually construct the 1-d instance, but it causes more memory accesses, and almost kills the improvement over eliminating allocation for the indexing result.

A: This was asked a long time ago, but just in case:
If your large array (a in your question) is C-contiguous, then you could use np.lib.stride_tricks.as_strided() instead of np.ravel() as in your question. That returns a view of the large array, without copying, and is very fast. You can then use np.take() with an existing out=... destination.
Note however that, in your question, the index pair itself is large (twice as many elements as the output you seek). If we convert it to a 1-d index (with np.ravel_multi_index(ix, a.shape) as below), that is also a new array of the same size as the output you want, so in the end you might not save much time not memory.
In any case, here is one use of np.lib.stride_tricks.as_strided:
n = np.prod(a.shape)
as1d_view = np.lib.stride_tricks.as_strided(a, (n, ), writeable=False)

# then, to index and copy into buf:
np.take(as1d_view, np.ravel_multi_index(ix, a.shape), out=buf)

Example 1: single large array, multiple indices
# setup
a = np.array([[1, 2, 3], [4, 5, 6]])
indices = [
    (np.array([0, 0, 0, 1]), np.array([0, 1, 2, 0])),
    (np.array([0, 1, 0, 1, 0, 1]), np.array([2, 1, 1, 2, 0, 0])),
    (np.array([0, 0, 1]), np.array([0, 1, 2])),
]

# init
n = np.prod(a.shape)
as1d_view = np.lib.stride_tricks.as_strided(a, (n, ), writeable=False)
m = max(len(ix[0]) for ix in indices)
buf = np.empty(m, dtype=a.dtype)

# loop
for i, ix in enumerate(indices):
    m = len(ix[0])
    np.take(as1d_view, np.ravel_multi_index(ix, a.shape), out=buf[:m])
    print(f'for index {i}, buf={buf[:m]!r}')

# gives:
# for index 0, buf=array([1, 2, 3, 4])
# for index 1, buf=array([3, 5, 2, 6, 1, 4])
# for index 2, buf=array([1, 2, 6])

Example 2: single index, multiple large arrays
# setup (presumably the large arrays are obtained one at a time instead...)
a_list = [
    np.array([[1, 2, 3], [4, 5, 6]]),
    np.arange(15).reshape(3, 5),
    np.random.randint(0, 20, (4,4)),
]
ix = np.array([0, 0, 0, 1]), np.array([0, 1, 2, 0])

# init
m = len(ix[0])
buf = np.empty(m, dtype=a.dtype)

# loop
for i, a in enumerate(a_list):
    ix1d = np.ravel_multi_index(ix, a.shape)
    as1d_view = np.lib.stride_tricks.as_strided(a, (n, ), writeable=False)
    np.take(as1d_view, ix1d, out=buf)
    print(f'for array {i}, buf={buf!r}')

# gives:
# for array 0, buf=array([1, 2, 3, 4])
# for array 1, buf=array([0, 1, 2, 5])
# for array 2, buf=array([ 5, 19,  1,  3])


text:
Q: Why is the body of a GeometryReader evaluated twice? Also first time with dimensions of zero? I have a GeometryReader nested inside of a NavigationView. Inside the GeometryReader I am using the dimensions supplied by the GeometryProxy with an if-statement. In my project I stumbled over the fact, that the content inside the GeometryReader is evaluated twice and the provided dimensions are width 0 and height 0 the first time. Also the onAppear() method of the content inside of the if case is called twice which lead to more problems.
Could someone explain that behavior so I can improve my code?
I made a minimal example to showcase the problem:
import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView() {
            NavigationLink(destination: SecondView()) {
                Text("Click me!")
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct SecondView: View {
    private func showHorizontal(_ w: CGFloat, _ h: CGFloat) -> Bool {
        print("Dimensions \(w), \(h)")
        return (w > h)
    }

    var body: some View {
        GeometryReader { proxy in
            if self.showHorizontal(proxy.size.width, proxy.size.height) {
                Text("Landscape")
                .onAppear() {
                    print("Landscape appeared")
                }
            } else {
                Text("Portrait")
                .onAppear() {
                    print("Portrait appeared")
                }
            }
        }
        .onAppear() {
            print("GeometryReader appeared")
        }
    }
}

On my iPad in landscape orientation I get the following console output:
Dimensions 0.0, 0.0
Dimensions 1194.0, 688.0
GeometryReader appeared
Landscape appeared
Landscape appeared

A: GeometryReader is updating on changes in its geometry, which makes sense.  In your if-clause, you are creating a new Text view on each evaluation.  What you're seeing is the onAppear of each of these.
if self.showHorizontal(proxy.size.width, proxy.size.height) {
         Text("Landscape")
         .onAppear() {
             print("Landscape appeared")
     }
}

If you needed the Text to be constant for some reason, you can assign it an id using the id modifier, like so:
if self.showHorizontal(proxy.size.width, proxy.size.height) {
         Text("Landscape")
         .id("fixed id")
         .onAppear() {
             print("Landscape appeared")
     }
}

A: I tried running OP's example code in 12.4 (12D4e) but did not get the double evaluation behavior.  On launch I get:
Dimensions 1024.0, 1366.0
Dimensions 1024.0, 1220.0
GeometryReader appeared
Portrait appeared

and rotating 4 times (full circle):
Dimensions 1366.0, 878.0
Landscape appeared
Dimensions 1366.0, 898.0
Dimensions 1024.0, 1220.0
Portrait appeared
Dimensions 1366.0, 878.0
Landscape appeared
Dimensions 1366.0, 898.0
Dimensions 1024.0, 1220.0
Portrait appeared

Hard-coding an ID, like .id("landscape"), didn't affect the behavior and yielded the same print statements from above.
To get around having "Portrait/Landscape appeared" print with every rotation, I factored Text() out of the if-statement:
GeometryReader { proxy in
    let text = self.showHorizontal(proxy.size.width, proxy.size.height) ? "Lanscape" : "Portrait"
    Text("\(text)")
        // .id(text)  // un-comment if you do want to see "Orientation appeared" w/every rotation
        .onAppear() {
            print("\(text) appeared")
        }
}
.onAppear() {
    print("GeometryReader appeared")
}

Now launch and a full circle of rotations yields:
Dimensions 1024.0, 1220.0
Portrait appeared
GeometryReader appeared
Dimensions 1366.0, 878.0
Dimensions 1366.0, 898.0
Dimensions 1024.0, 1220.0
Dimensions 1366.0, 878.0
Dimensions 1366.0, 898.0
Dimensions 1024.0, 1220.0


text:
Q: How can I achieve one single form, pre-populated with data from two different Profile instances? I have a model, Pair, and another model Profile.
An instance of the model Pair will be made with a form that draws from two different Profile instances. So, how do I pre-populate a single form with bits of information from two Profiles?
Two models: Profile & Pair:
class Profile(models.Model):
    ...
    favorites = models.CharField(max_length=150)

class Pair(models.Model):
    requester = models.ForeignKey(Profile)
    accepter = models.ForeignKey(Profile)
    requester_favorite = models.CharField(max_length=50)
    accepter_favorite = models.CharField(max_length=50)

The form so far:
class PairRequestForm(forms.Form):
    your_favorites = forms.CharField(max_length=50)
    partners_favorites = forms.CharField(max_length=50)

Code Explanation:  The way it works is, a user(requester) will request the initiation of a pair with the PairRequestForm to the potential accepter.
The form should be pre-populated with the "favorite" of each individual user.
I'm not sure how to wire up the views.py since I need to obtain two objects.
class PairRequestView(FormView):
    form_class = PairRequestForm
    template_name = 'profile/pair_request.html'
    success_url = "/"

    def is_valid(self, form):
        return

note: The pair form must be pre-populated with current information from the Profile. However, the form will not update any old information(will not save() any Profiles)--it will simply create a new Pair instance.

A: Assuming that the accepters page is visited at something like /profiles/2, you can capture the id of the accepter from the url, as you normally would.
Couple of things - you don't need to save the favourites into the Pair model, since for any use of the Pair model, you can just access them by doing
`p = Pair.objects.get(id=1) #or whatever query
 p.requester.favourites
 > Some of my favourites
 p.accepter.favourites
 > Some of your favourites.

If you, the proposer, are id=1, and visiting mine, the accepter's page (id=2), then you can populate the form - (I've done this in a very long manner for clarity)
accepterobj = Profile.objects.get(id=id_from_url_for_page)
proposerobj = Profile.objects.get(id=request.user.id)

form = PairRequestForm(accepter=accepterobj,
                       proposer=proposerobj,
                       accepter_favourites=accepterobj.favourites,
                       proposerobj_favourites=proposerobj.favourites)

in your CBV, you can do the queries above by overriding the get_initial method on your PairRequestView.
def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super(PairRequestView, self).get_initial()

    initial['proposer'] = self.request.user
    ...etc
    return initial


text:
Q: Is there a way to use a grammar with the HTML 5 speech input API? I'm working with the HTML 5 speech input API and I want to let the server know which answers it can expect to be returned from the speech input. Is there a way to set a list of possible inputs?

A: I assume your a talking about the Speech Input API Specification as defined by the W3C.
According to this specification grammars are supported, which is the method used by speech recognition systems to restrict possible inputs.  Look for the section titled "Speech recognition grammars".  The problem will be how well it is supported in the particular browser that is being used, which is the case for an HTML 5 specific function since it is not a completed standard yet.  Chrome seems to be the most up to date with the standard.  Checkout this blog post from the Chrome team on implementing the Speech Input API.

A: In Google Chrome you can not use grammars yet, overall they decided to use free-form recognition only. Relevant question is Grammar in Google speech API.
Grammars are supported in Firefox Web Speech API, but the feature is experimental.
If your browser supports HTML5 audio, you might want to try to recognize words from your grammar using Pocketsphinx.js library, it provides javascript-based recognizer which should be very good for grammars.


text:
Q: scraper is unable to switch inputs I'm trying to login to a website using a selenium script i wrote. The problem im having is when it is logging in, its unable to locate the passwords input.
search = driver.find_element_by_id("clareity")
search.send_keys("user")
search.find_element_by_xpath('//div[@class="form-control lock"]')
search.send_keys("pass")

when it looks for the xpath it sends the keys into the username input, so when both keys get sent, in the user input on the site it show, "userPass" instead of putting the pass in the password input.
username input form:

password input form:

A: You created a variable for user, so you need to do the same for password
search = driver.find_element_by_id("clareity")
search.send_keys("user")
password = driver.find_element_by_id("security")
password.send_keys("pass")

Or don't use variables at all
driver.find_element_by_id("clareity").send_keys("user")
driver.find_element_by_id("security").send_keys("pass")


text:
Q: Understanding value to reference and reference to value in Java refactoring I was going through refactoring book and couldn't understand these two techniques.
https://refactoring.com/catalog/changeValueToReference.html
And
https://refactoring.com/catalog/changeReferenceToValue.html
Can you please help me understand with an example in Java?

A: In it's very simplest form it just means switching between the following two options:
class Order
{
    // constructor etc...
    private String customerName;
    public String getCustomerName() {return customerName;}
}

or
class Customer
{
    // constructor etc...
    private String name;
    public String getName() {return name;}
    public String setName(String name) {this.name = name;}
}

class Order
{
    // constructor etc...
    private Customer customer;
    public String getCustomerName() {return customer.getName();}
}

Now when a customer's name can change, the 2nd solution is prefered, because you don't need to update the customerName member in every order.
However if a customer's name never changes, the 1st solution might be prefered, because you don't need to manage Customer objects somewhere.
Which version you want to chose and if you need to refactor depends on your actual application.

A: Assume you have two Customer objects/instances, customer1 and customer2. They are actually the same customer, with same ID and name. However they were read at different moments from the database or such. A new Customer() was called twice.
Customer customer1 = new Customer(13L);

Customer customer2 = new Customer(13L);

The refactoring would involve a factory method:
Customer customer1 = customerRepository.findById(13L);

Customer customer2 = customerRepository.findById(13L);

Examples of the latter is for instance JPA, an O/R mapping.

A: Strictly speaking, I'm not sure whether this conversion is possible in Java, since you don't have both references and values of objects in Java - all objects are references (which are passed by value).
However, one can consider this similar to the following example:
"Value":
class Order
{
   private int orderNum;
   private Customer customer;
   Order(int orderNum, String customerString)
   {
      this.orderNum = orderNum;
      this.customer = new Customer(customerString);
   }
}

// elsewhere:
Order order1 = new Order(1, "I am a customer");
Order order2 = new Order(2, "I am a customer");
Order order3 = new Order(3, "I am a customer");
Order order4 = new Order(4, "I am a customer");

Here each Order has it's own Customer object, even when all or most of those Customer objects are the same.
The above is, of course, just an example. Passing all parameters of another object into a constructor is not good design.
Reference:
class Order
{
   private int orderNum;
   private Customer customer;
   Order(int orderNum, Customer customer)
   {
      this.orderNum = orderNum;
      this.customer = customer;
   }
}

Customer customer = new Customer("I am a customer");
Order order1 = new Order(1, customer);
Order order2 = new Order(2, customer);
Order order3 = new Order(3, customer);
Order order4 = new Order(4, customer);

Here we can have a single Customer for many Orders (if we want).


text:
Q: Error while installing pyHWM2014 with pip:
  pip install pyHWM2014
    Collecting pyHWM2014
      Using cached pyhwm2014-1.1.tar.gz (18 kB)
      Preparing metadata (setup.py): started
      Preparing metadata (setup.py): finished with status 'done'
    Requirement already satisfied: timeutil in c:\users\naci_\anaconda3\lib\site-packages (from pyHWM2014) (2.1.0)
    Requirement already satisfied: numpy in c:\users\naci_\anaconda3\lib\site-packages (from timeutil->pyHWM2014) (1.19.2)
    Note: you may need to restart the kernel to use updated packages.Requirement already satisfied: nose in c:\users\naci_\anaconda3\lib\site-packages (from timeutil->pyHWM2014) (1.3.7)
    Building wheels for collected packages: pyHWM2014
      Building wheel for pyHWM2014 (setup.py): started

      error: subprocess-exited-with-error

      python setup.py bdist_wheel did not run successfully.
      exit code: 1

      [73 lines of output]

      CommandNotFoundError: No command 'conda nose'.

      WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
      Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
      To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      Requirement already satisfied: timeutil in c:\users\naci_\anaconda3\lib\site-packages (2.1.0)
      Requirement already satisfied: nose in c:\users\naci_\anaconda3\lib\site-packages (from timeutil) (1.3.7)
      Requirement already satisfied: numpy in c:\users\naci_\anaconda3\lib\site-packages (from timeutil) (1.19.2)
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running bdist_wheel
      running build
      running config_cc
      unifing config_cc, config, build_clib, build_ext, build commands --compiler options
      running config_fc
      unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
      running build_src
      build_src  Building wheel for pyHWM2014 (setup.py): finished with status 'error'
      Running setup.py clean for pyHWM2014
    Failed to build pyHWM2014
    Installing collected packages: pyHWM2014
      Running setup.py install for pyHWM2014: started
      Running setup.py install for pyHWM2014: finished with status 'error'
    ```
      building extension "hwm14" sources
      f2py options: ['--quiet']
        adding 'build\src.win-amd64-3.8\build\src.win-amd64-3.8\fortranobject.c' to sources.
        adding 'build\src.win-amd64-3.8\build\src.win-amd64-3.8' to include_dirs.
        adding 'build\src.win-amd64-3.8\hwm14-f2pywrappers.f' to sources.
        adding 'build\src.win-amd64-3.8\hwm14-f2pywrappers2.f90' to sources.
      building data_files sources
      build_src: building npy-pkg config files
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build_py
      creating build\lib.win-amd64-cpython-38
      creating build\lib.win-amd64-cpython-38\pyhwm2014
      copying pyhwm2014\__init__.py -> build\lib.win-amd64-cpython-38\pyhwm2014
      running build_ext
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      customize MSVCCompiler using build_ext
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      Could not locate executable g77
      Could not locate executable f77
      customize IntelVisualFCompiler
      Could not locate executable ifort
      Could not locate executable ifl
      customize AbsoftFCompiler
      Could not locate executable f90
      customize CompaqVisualFCompiler
      Could not locate executable DF
      customize IntelItaniumVisualFCompiler
      Could not locate executable efl
      customize Gnu95FCompiler
      Could not locate executable gfortran
      Could not locate executable f95
      customize G95FCompiler
      Could not locate executable g95
      customize IntelEM64VisualFCompiler
      customize IntelEM64TFCompiler
      Could not locate executable efort
      Could not locate executable efc
      customize PGroupFlangCompiler
      Could not locate executable flang
      don't know how to compile Fortran code on platform 'nt'
      warning: build_ext: f77_compiler=None is not available.

      building 'hwm14' extension
      error: extension 'hwm14' has Fortran sources but no Fortran compiler found
      Error in atexit._run_exitfuncs:
      Traceback (most recent call last):
        File "C:\Users\naci_\anaconda3\lib\site-packages\colorama\ansitowin32.py", line 59, in closed
          return stream.closed
      ValueError: underlying buffer has been detached
      [end of output]

      note: This error originates from a subprocess, and is likely not a problem with pip.
      ERROR: Failed building wheel for pyHWM2014
      error: subprocess-exited-with-error

      Running setup.py install for pyHWM2014 did not run successfully.
      exit code: 1

      [73 lines of output]

      CommandNotFoundError: No command 'conda nose'.

      WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
      Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
      To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      Requirement already satisfied: timeutil in c:\users\naci_\anaconda3\lib\site-packages (2.1.0)
      Requirement already satisfied: numpy in c:\users\naci_\anaconda3\lib\site-packages (from timeutil) (1.19.2)
      Requirement already satisfied: nose in c:\users\naci_\anaconda3\lib\site-packages (from timeutil) (1.3.7)
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running install
      C:\Users\naci_\anaconda3\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running config_cc
      unifing config_cc, config, build_clib, build_ext, build commands --compiler options
      running config_fc
      unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
      running build_src
      build_src
      building extension "hwm14" sources
      f2py options: ['--quiet']
        adding 'build\src.win-amd64-3.8\build\src.win-amd64-3.8\fortranobject.c' to sources.
        adding 'build\src.win-amd64-3.8\build\src.win-amd64-3.8' to include_dirs.
        adding 'build\src.win-amd64-3.8\hwm14-f2pywrappers.f' to sources.
        adding 'build\src.win-amd64-3.8\hwm14-f2pywrappers2.f90' to sources.
      building data_files sources
      build_src: building npy-pkg config files
      running build_py
      creating build\lib.win-amd64-cpython-38
      creating build\lib.win-amd64-cpython-38\pyhwm2014
      copying pyhwm2014\__init__.py -> build\lib.win-amd64-cpython-38\pyhwm2014
      running build_ext
      No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
      customize MSVCCompiler
      customize MSVCCompiler using build_ext
      get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
      customize GnuFCompiler
      Could not locate executable g77
      Could not locate executable f77
      customize IntelVisualFCompiler
      Could not locate executable ifort
      Could not locate executable ifl
      customize AbsoftFCompiler
      Could not locate executable f90
      customize CompaqVisualFCompiler
      Could not locate executable DF
      customize IntelItaniumVisualFCompiler
      Could not locate executable efl
      customize Gnu95FCompiler
      Could not locate executable gfortran
      Could not locate executable f95
      customize G95FCompiler
      Could not locate executable g95
      customize IntelEM64VisualFCompiler
      customize IntelEM64TFCompiler
      Could not locate executable efort
      Could not locate executable efc
      customize PGroupFlangCompiler
      Could not locate executable flang
      don't know how to compile Fortran code on platform 'nt'
      warning: build_ext: f77_compiler=None is not available.

      building 'hwm14' extension
      error: extension 'hwm14' has Fortran sources but no Fortran compiler found
      Error in atexit._run_exitfuncs:
      Traceback (most recent call last):
      File "C:\Users\naci_\anaconda3\lib\site-packages\colorama\ansitowin32.py", line 59, in closed
          return stream.closed
      ValueError: underlying buffer has been detached
      [end of output]

      note: This error originates from a subprocess, and is likely not a problem with pip.
    error: legacy-install-failure

    Encountered error while trying to install package.

    pyHWM2014

    note: This is an issue with the package mentioned above, not pip.
    hint: See above for output from the failure.

A:
don't know how to compile Fortran code on platform 'nt'
warning: build_ext: f77_compiler=None is not available.

Means you don't have a fortran compiler installed. Try to install gfortran.
Step 1
Install MSYSY2
Step 2
Invoke Msys2 window. The program runs automatically for the first time. After that, search for "msys2" in the search menu. Choose MSYS2 MinGW 64-bit
Step 3
Msys2 consists of many dependent programs. Each program is prepared as a package. If the package is modified, you can download it through the internet. This process is automated by a command pacman.
For the first time, you have to date the built-in packages through the internet. In the Msys2 windows, type the following command.
pacman -Syu
Step 4
GFortran is also provided as a package. Type the following command in the window to install GFortran.
pacman -Su gcc-fortran
As above, it will ask you if you want to install the package. Type y, and wait for a while to finish the installation. After this step, you can use GFortran in this window.
Step 5
To be able to use gfortran in your normal command prompt you need to add the following directories to your PATH environment variable.
C:\msys64\mingw64\bin, C:\msys64\usr\bin
To add anything to your PATH in Windows 10:

*

*Search "Advanced System Settings" in the search bar

*Open the "environment variables" window, click on the PATH variable and click on "Edit"

*Click on the "New" button and add the 2 directories to your PATH

*Click on OK on all the windows and open a new Command Window and you will be able to use gfortran into your windows command prompt!

You can confirm the successful installation with the following command in your normal command prompt.
gfortran --version
You may also have to install or update conda to make it work.
Download and install here
If you have it installed already try updating it.
If you have it added to PATH already just run conda update conda. Else open "Anaconda Prompt" from your search menu and run the same command.
Restart all command prompt windows and try
pip install pyHWM2014
again it may work now.


text:
Q: Alternative to navigator.permissions.query({name:'geolocation'}) I want to query the status of the gelocation permission without prompting the user directly. Since then I have done this via:
navigator.permissions.query({name:'geolocation'})

however I realized that this does not work via iOS. Does anyone know an alternative way that works system and browser independent?


text:
Q: How can I play the data frame get from streaming by Live555? My iOS App is a player to streaming video from monitor camera. There are two streaming mode: HTTP and RTP/RTSP.

HTTP:
 Media Container : MPEG-2 TS
 Video Codec     : H.264 (MPEG-4 AVC)
 Audio Codec     : AAC
RTP/RTSP:
 Media Container : MPEG4
 Video Codec     : H.264 (MPEG-4 AVC)
 Audio Codec     : AAC

In HTTP mode, I can play successfully with MPMoviePlayerViewController.
In RTP/RTSP mode, I used Live555 to implement the protocol RTP/RTSP. We just got the data from streaming and stored to a temperature file such as DATA.MP4. We don't use ffmpeg to decode the data because the license.
I used MPMoviePlayerViewController to play DATA.MP4 file but it can't. As above information, HTTP and RTP/RTSP have the same video profile H.264, so I wonder that why the MPMoviePlayerViewController can't play DATA.MP4?
By the way, I'm trying to use OpenH264(Cisco) to decode the DATA.MP4, but I don't know how to use this library. Because it isn't more document about it. Anyone who have experience about it, can you share me some samples?
Thank you!

A: You can save a RTSP steam to an mp4 using openRTSP, which also provides a source code example of how it do it. http://www.live555.com/openRTSP/
I have managed to decode an RTSP stream using openh264 but there are a few things to be aware of. See http://www.live555.com/liveMedia/faq.html#testRTSPClient-how-to-decode-data for an overview.

*

*Derive a new class from MediaSink

*For an overview of the openh264 decoder API, see https://github.com/cisco/openh264/wiki/UsageExampleForDecoder

*Before you initialize the h264 decoder, you need to get some parameters from the subsession: string spropParams = subsession->fmtp_spropparametersets(); and pass that into your sink object.

*During decode, the sink's AfterGettingFrame method gets repeated called. Each time, a H264 "NAL frame" is passed in, which is either a H264 frame fragment or a group of H264 parameters.

*Each frame needs a start code 0x00000001 prepended to the buffer before it is sent to the decoder. See H264or5VideoFileSink.cpp (in the live555 source) for an example of how this is done. https://github.com/xanview/live555/blob/master/liveMedia/H264or5VideoFileSink.cpp

*The sprop parameters should be transmitted to the decoder before any other data is sent. See H264or5VideoFileSink.cpp for this too.

*Use the DecodeFrameNoDelay (for immediate display of multi-slice data) or DecodeFrame2 (for display of only complete frames) function in openh264 for decoding https://github.com/cisco/openh264/wiki/ISVCDecoder#decodeframenodelay

*A frame is only ready when sDstBufInfo.iBufferStatus is true

*The frame is often encoded in some non-RGB colour space such as I420. One way to deal with this is opencv's cvtColor and the COLOR_YUV2BGR_I420 option.

*I had some difficulty with frames failing to decode when RTSP was working over UDP (I was getting dsRefLost errors). This may be due to some frames being larger than the MTU for the network, resulting in packet loss. A work around is to use TCP for RTSP instead or simply increase the network MTU. https://ffmpeg.org/pipermail/libav-user/2011-November/000901.html
I hope that helps!


text:
Q: Sorting and Setting Default in CoreData List My iOS application uses CoreData to store many things, and NSUserDefaults to store other things that CoreData would be overkill for.
I'm going to simplify this so bear with me (Note: for the sake of this example let's use credit cards). When my application loads it displays a list of saved credit cards. Now, when each card is added it is assigned a number 1-10 (let's call it cardNum) that stays with the card for the life of it.
So we add one card and assign it #1. We add another card and assign it #2. Another... #3. We can set a default card that will be highlighted on launch by tapping it. What it does is saves the cardNum as the cDefault to NSUserDefaults to keep track of it (effectively setting card X as the default card).
(crude drawing of a table view)
//cDefault is 2
------------
1 - Card1
------------
2 - Card2 (cDefault)
------------
3 - Card3
------------
4 - Card4
------------

So let's say we assign cDefault to 2 and then next week we delete that card. On deletion, I need to automatically assign one of the other cards to be a default card.
(crude drawing of table view AFTER card 2 is deleted - note how cDefault is still set...)
//cDefault is still 2
------------
1 - Card1
------------
3 - Card3
------------
4 - Card4
------------

So my question is how, upon deletion, to set another card as cDefault (i.e if it was an array I would probably set the new default to the cDefault value of whatever card is at  indexPath.row==0 but I'm not sure if I can do that using CoreData)
Please ask as many questions as you need to. I tried to explain this to the best of my abilities but if I was unclear on anything please ask me.
Thank you so much in advance.
James

A: First, I don't understand why you have to separate certain informations from your managed objects... I would define a BOOL property like "highlighted" in the Card class and handle all your stuff in core data... it sounds more OOP to me :P
Second, I didn't try it before, but you can subscribe to the NSNotificationCenter and listen to NSManagedObjectContextDidSaveNotification, that notification contains an userInfo dictionary with a key named NSDeletedObjectsKey that should contains a set of deleted objects (cards), in your selector you can write the piece of logic to update the objects in the store (that is, set the "highlighted" property to YES for the first card for example)... this approach is cool because can be placed anywhere in your code, anyway the simplest and obvious place to handle the update is where you are deleting the card.


text:
Q: Firebase function does not return the right data update
The vehicleDocument, employeeDocument and routeDocument are document references in my firestore. I have also updated my code according to Renaud(added a query for employee_ID), but still the same result.
The data model is:
--- collection: assignments
------ someDocument
--------- string: employee_ID
--------- reference: employee_Document
--------- reference: route_Document
--------- reference: vehicle_Document
--- collection: employees
------ someEmployee
--------- string: employee_ID
I do not get the desired results from my Firebase function, I always get this result:
{result: tour-found, tourStartTime: null, licensePlate: null, vin: null, waypoints: null, tourcode: null}

from this code:
exports.getTourDataFromAssignment = functions.runWith({timeoutSeconds: 15}).region(REGION_ID).https.onCall(async (data, context) => {
    //retrieve uid and get assignmentCollection
    const uid = data.uid.toString();
    var assignmentDocument;
    // eslint-disable-next-line promise/always-return
    const snapshot = await admin.firestore().collection('assignments').where('employee_ID', '==', uid).get();
    if(snapshot.docs.length !== 0) {
        assignmentDocument = snapshot.docs[0];
    }else{
        return {
            'result': 'no-tour-found',
        };
    }

    //loop over assignment, find employeeDocument, get check for identical employeeID
    async function getDocumentsFromAssignment() {
        const vehicleDocument = await assignmentDocument.data()['vehicle_Document'].get();
        const routeDocument = await assignmentDocument.data()['route_Document'].get();
        return [routeDocument, vehicleDocument];
    }

    const result = await getDocumentsFromAssignment();
    const routeDocument = result[0];
    const vehicleDocument = result[1];
    return {
            'result': 'tour-found',
            'waypoints': routeDocument["waypoints"],
            'licensePlate': vehicleDocument["licensePlate"],
            'vin': vehicleDocument["vin"],
            'tourcode': routeDocument["tourcode"],
            'tourStartTime': routeDocument["tour_start_time"],
    };

I can assure that the uid from the request is equal to the uid from my firestore. That means that I am able to get 'inside' the if-statement, but somehow it still returns null whatsoever.

A: This is related with getting the documents in getDocumentsFromAssignment function. When you get this reference it returns DocumentSnapshot on which you had to still call data() again (reference). I think that there be many possible correction of that, however the easiest for me will be to add the .data() methods in return like:
async function getDocumentsFromAssignment() {
        const vehicleDocument = await assignmentDocument.data()['vehicle_Document'].get();
        const routeDocument = await assignmentDocument.data()['route_Document'].get();
        return [routeDocument.data(), vehicleDocument.data()];
    }

I tested it locally on node12, so it should work in Cloud Function as well.


text:
Q: google map Version 2 not displaying -- android I am using google map version2. I got the API key and place those in manifest. I can able to view the map in some devices, but when I compile the same app in different device, I get the blank screen instead to display the map. Can anyone guide me on this
    FragmentManager myFragmentManager = getFragmentManager();
    MapFragment myMapFragment = (MapFragment)myFragmentManager.findFragmentById(R.id.map);
    myMap = myMapFragment.getMap();

     if (myMap == null) {
         myMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                                .getMap();
     }
    myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    myMap.setMyLocationEnabled(true);
    myMap.setOnMyLocationChangeListener(this);

A: activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

MapActivity.java
public class MapActivity extends Activity {

private GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();

    //modify below according to your requirement
    map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    map.setMyLocationEnabled(true);
    ..
    ..
    ..

Add following in your manifest file:
<permission
    android:name="com.yourpackage.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

  <uses-permission android:name="com.yourpackage.permission.MAPS_RECEIVE" />

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

   <application
       ........ >
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_api_key" />

Of course, you have to other manifest parameter like activity name and other.
Then you have to reference google play service library into your project.
Follow with this link to install google play service sdk Install the Google Play Services SDK
And then
Your Project--->Right Click-->Properites-->Android-->Add

Select google-play-services sdk that you import into your workspace using that i mention in above method
Finally, select your android sdk target to

Google API Version 8

or other Google API version according to your requirement.
Further if you have any confusion, you can follow with this android official link:Google Maps Android API v2
UPDATED CODE:
To make it work in lower version:
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      class="com.google.android.gms.maps.SupportMapFragment"/>

MyMapActivity.java
FragmentManager fragmentManager = getSupportFragmentManager();
SupportMapFragment mapFragment =  (SupportMapFragment)
fragmentManager.findFragmentById(R.id.map);
map = mapFragment.getMap();

Thanks !!