text:
Q: how to consume web services (own project) from html page i have a web service project called (WS_Service)
i have a html page thats trying to consume WS_Service.
i have web services sits on its own project (the reason i have created is because its independednt and can be called from .aspx or .html or mobile)
i dont have problem with .aspx and i have just add the reference and fire the services.
but i am not sure how i will be doing on .html page below is my code i am trying to POST to a web service:
 $.ajax({
      type: "POST",
      url: "http://myhostname/Delete.asmx/DeleteCustomer",  <<< is that right?
      data: "{CustID: " + parseInt(customer_id) + "}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
                     AjaxSucceeded(msg);
               },
      error: AjaxFailed
 });

any suggustions?

A: First off, you can't POST to a form that's on another domain using AJAX. So make sure that you aren't trying to POST to domain1.com when the Javascript is running on domain2.com.
Assuming they are on the same domain, you are pretty close, but if you're trying to post JSON to using jQuery I would just do something like this:
var data = {
    CustID: parseInt(customer_id)
};

$.post("http://myhostname/Delete.asmx/DeleteCustomer", {data: JSON.stringify(data)}, function(response) {
  //success
});

That will send through your JSONified object in a POST variable called data on the server side of things.
Don't try to mess with building the JSON yourself in a string, that will get very messy if you start sending complicated data. That's why they invented the JSON functions. $.post is just a shortcut to $.ajax with some default stuff already configured that should be fine for your use. If you really need to capture AJAX errors (like HTTP Status Codes), have a look at $.ajaxError as a supplement.
You can include a simple JSON compatibility script in your page if you are supporting legacy browsers that don't have the JSON.stringify and JSON.parse functions, like https://github.com/douglascrockford/JSON-js

A: I suspect strongly that this line:
  data: "{CustID: " + parseInt(customer_id) + "}",

should involve an object, not a string:
  data: { CustID: customer_id },

or possibly:
  data: { CustID: parseInt(customer_id, 10) },


text:
Q: Finding tight frustum around an AABB How do I build a tight-fitting view frustum around an AABB and a particular camera position?
Basically, I'm implementing frustum-traced shadows and reprojecting view samples to the point-light's view frustum. I want to optimize the light's projection by tightly bounding the view samples with a new frustum from light position. So basically, the new frustum will be a subset of the original one. I already have an AABB from the view samples (in light space), but I don't know how to turn it into a new frustum (= view/projection matrices).
Any help appreciated

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django User password only works after manually change in terminal I cant figure out why Django User password is not accepted. I've tried creating multiple users and each time I try to log in Django tells that the username or password didnt match. It must be a password issue because each time I change the password manually in terminal python manage.py changepassword username then the login is successful. I also checked that once the registration of the user is done then a user is added to the database and a hashed password is created as expected.
Any ideas what could be wrong here?
UPDATE
I also checked that the password works if I create a new user via django admin panel
models.py
class Company(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

views.py
def register(request):
    registered = False

    if request.method == 'POST':
        user_form = UserCreateForm(data=request.POST)
        profile_form = ProfileCreationForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():

            user = user_form.save()
            user.set_password(user.password)
            print(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'logo' in request.FILES:
                profile.logo = request.FILES['logo']

            profile.save()

            registered = True

        else:
            print(user_form.errors, profile_form.errors)

    else:
        user_form = UserCreateForm()
        profile_form = ProfileCreationForm()

    return render(request, 'companies/registration.html', {'user_form': user_form,
                                                           'profile_form': profile_form,
                                                           'registered': registered})

forms.py
class UserCreateForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].label = 'Lietotājvārds'

A: I deleted this line from views.py and it worked
user.set_password(user.password)

I cant figure out why it works now since I don't recall changing this line of code and I use it in my other projects since its also used in the tutorials from which I'm learning Django
UPDATE
Cause found. The code user.set_password(user.password) actually set a new password based on the hash value of the initial password that I entered during user creation. After filling the form the user.password didn't represent the raw password but rather the hashed version of it. So my code created two password


text:
Q: Failed to make a string raw for date (Elastticsearch) I want to search a date field without using range. So I decided to make a string raw to search into it as it is text:
 "myDate": {
                            "type": "date",
                            "format": " yyyy-MM-dd || yyyy-MM || Y ||date_hour_minute_second",
                            "fields": {
                                "raw": {
                                    "type": "string",
                                    "index": "not_analyzed",
                                    "null_value": "",
                                    "doc_values": true
                                }
                            }
                        }

But it shows up in kopf nothing for myDate.raw. Any idea?
Thanks


text:
Q: Make a music server with server and client side in nodeJs I want to do my first project in NodeJs. Basically I want to perform a music server on one side and a client to play music stored on the server. The whole will run only in a local private network.
I have only beginner skills as I just read one book about nodeJs, so I know how to initiate a site with Express, use a mongoDB database with mongoose and some other things.
My issue is that I don't know how to begin my project. As I see the things :

*

*my server will host the music files (mp3 and flac). In a first time this will done through real files, nothing will be stored in any database

*in a first time my clients will have to be able to list those files and play them.

But in a first time I'm just not able to find a library to play music files, it's just a mess as there are so many of them that I don't know what to choose.
So if you can help me to choose one and architecture my project, this would be a great help. thanks.


text:
Q: What's the standard config file name and extension in Python? I'm creating a config file to hold configuration/properties settings for my project that frequently change, such as file paths. What's the standard name/extension for such a file? (e.g. in Java I've used config.xml, in VB.NET I've used App.config...)

A: First, consider using ConfigParser (configparser in 3.0, so the documentation says).  That doesn't solve the naming problem, but it is a readable alternative to xml for most configuration needs.
Whatever name you use, make all the parts meaningful. I would probably use something like appName.cfg, where appName identifies your application, or the part of the application the configuration is for.

A: The docs seem to use .cfg
On Windows, many people (such as mercurial) use .ini

A: Ok, I've asked around where I work and researched a little, and this is what I've come up with as suggestions:

*

*settings.ini

*applicationName.config

*applicationName.cfg

If anyone has any other suggestions, feel free to add...


text:
Q: PyQGIS saving Raster from loop to file in QGIS3 I have a huge amount of Raster Layers and I only want to change the cell size using gdal warpreproject. This is my attempt:

import os.path, glob

inputpath = 'C:/Users/DGM1'
outputpath = 'C:/Users/output'

directory = os.fsencode(inputpath)
os.chdir(inputpath)

for file in glob.glob('*.txt'):
    print(file)
    filename = os.fsdecode(file)
    inputname = os.path.join(os.fsdecode(directory), filename)
    outputname = outputpath + "warped" + str(filename)
    processing.run("gdal:warpreproject",
        {'INPUT':inputname, 'SOURCE_CRS':None,
         'TARGET_CRS':QgsCoordinateReferenceSystem('EPSG:25832'),
         'RESAMPLING':0, 'NODATA':None, 'TARGET_RESOLUTION':5, 'OPTIONS':'',
         'DATA_TYPE':0, 'TARGET_EXTENT':None, 'TARGET_EXTENT_CRS':None,
         'MULTITHREADING':False, 'EXTRA':'', 'OUTPUT':outputname})

I don't get any mistake when running the code but there are no raster layers saved to the output.
Any idea what could be the mistake?

A: You need to change output file extension. I guess GDAL doesn't support .txt extension. Use for example .XYZ. You also miss / or \\ (path separator).
Change
outputname = outputpath + "warped" + str(filename)

to
outputname = os.path.join(outputpath, "warped" + str(filename)[:-3] + 'XYZ')


text:
Q: Compare values in Excel VBA I am trying to compare cell A1 with B1 and if it is true populate cell F1 with the A1 value. But irrespective of my input values the if condition becomes true.
Sub Macro3()
    Dim i As Integer
    i = 1
    For i = 1 To 10
        If (Range("A" & i).Select = Range("B" & i).Select) Then
            Range("A" & i).Select
            Selection.Copy
            Range("F" & i).Select
            ActiveSheet.Paste
        End If
    Next i
End Sub

A: Instead of selecting, copying, and pasting, you can compare the Value property of the cells, then set the F column Value accordingly:
Dim i As Integer
For i = 1 To 10
    If Range("A" & i).Value = Range("B" & i).Value Then
        Range("F" & i).Value = Range("A" & i).Value
    End If
Next

A: Consider this a compliment to Nick's answer (accept his if you find it to work, which you should). I wanted to help explain some of the things that are wrong in your code.
Before FIX:
Sub Macro3()
    Dim i As Integer
    i = 1
    For i = 1 To 10
        If (Range("A" & i).Select = Range("B" & i).Select) Then
            Range("A" & i).Select
            Selection.Copy
            Range("F" & i).Select
            ActiveSheet.Paste
        End If
    Next i
End Sub

AFTER FIX
Sub Macro4()
    Dim i As Long
    For i = 1 To 10
        If Range("A" & i).Value = Range("B" & i).Value Then
            Range("F" & i).Value = Range("A" & i).Value
        End If
    Next
End Sub

POINTS:

*

*Use Long instead of Integer (small optimization since VBA will convert the int to a long anyway)

*No need to declare i = 1 twice in a row

*You should be comparing values, not simply selecting cells. There is rarely, if ever, a need to use the .Select keyword. You can access all object's properties directly.

*Copy and paste is a heavy operation. Since you are in VBA, may as well just assign the value that is in A to the cell in column B. It's faster, and more effecient.

I hope this helps. BTW, you can simple enter:
=IF(A1=B1,A1,"")

in F1 and drag the formula down to get a similar result.

A: You can use a variant array to address your performance issue that you raise above. This code will run the same as Nicks except it will skip blanks cell, ie it will

*

*update the F value if A and B are the same

*skip updates if the A cell is blank

*leave the existing F values in place if A<>B

It wasn't clear to me how you are comparing rows accross two sheets, can you expand on this?
    Sub MyArray()
    Dim X As Variant
    Dim Y As Variant
    Dim lngrow As Long
    X = Range([a1], Cells(Rows.Count, "B").End(xlUp))
    Y = Range([f1], [f1].Offset(UBound(X, 1) - 1, 0))
    For lngrow = 1 To UBound(X, 1)
       If Len(X(lngrow, 1)) > 0 Then
       If X(lngrow, 1) = X(lngrow, 2) Then Y(lngrow, 1) = X(lngrow, 1)
       End If
    Next
    Range([f1], [f1].Offset(UBound(X, 1) - 1, 0)) = Y
    End Sub


text:
Q: Search data based on timestamp with multiple joins and dependency between timestamp in Postgres I have two tables prod_replay_in and prod_replay_outas below.
For msg_type as CDST010 in prod_replay_in table has it's confirmation in prod_replay_out table as CDST01C. Same for msg_type as CDST100 has it's confirmation message in prod_replay_out table as CDST10C. In below tables, cdsx_time matters. For example, second CDST100 message will have second CDST10C message based on cdsx_time.
Note: JOIN between 2 tables is based on cdsx_id as it is common between two tables. CDST010 and CDST01C will have only one entry for same cdsx_id in prod_replay_in and prod_replay_out table respectively. Also, number of CDST100 and CDST10C messages varies based on cdsx_id.
What I want to search?
I want to search number of CDST100 messages in prod_replay_in table as per following criteria:

*

*Get 1st CDST100 if fourth character in bancs_msg for CDST100 is matched with fourth character in msg_body for CDST01C

*Get 2nd CDST100 if fourth character in bancs_msg for CDST100 is matched with fourth
character in msg_body for 1st CDST10C

*Get 3rd CDST100 if fourth character in bancs_msg for CDST100 is matched with fourth character
in msg_body for 2nd CDST10C

The above pattern is like checking 2nd CDST100 with first CDST10C, 3rd CDST100 with 2nd CDST10C, etc.
prod_replay_in
id(serial) | msg_type(varchar) | cdsx_time(timestamp)  | cdsx_id(varchar)    | bancs_msg(text)
------------------------------------------------------------------------------------------
8334698    | CDST010           | 2020-02-24 14:23:01.0 | T202005518525        | ABCD
8341809    | CDST100           | 2020-02-24 14:47:38.0 | T202005518525        | ANOC
8342732    | CDST100           | 2020-02-24 14:51:53.0 | T202005518525        | PHLM
8344890    | CDST100           | 2020-02-24 15:15:14.0 | T202005518525        | JKQO

prod_replay_out
    id(serial) | msg_type(varchar) | cdsx_time(timestamp)    | cdsx_id(varchar)     | msg_body(text)
    ------------------------------------------------------------------------------------------
    42164527   | CDST01C           | 2020-02-24 14:23:08.016 | T202005518525        | AQRS
    42176068   | CDST10C           | 2020-02-24 14:47:47.056 | T202005518525        | STUM
    42177522   | CDST10C           | 2020-02-24 14:52:00.031 | T202005518525        | XYZK
    42245814   | CDST10C           | 2020-02-24 15:30:00.045 | T202005518525        | ASQO

What I have tried?
I have tried creating sql query for matching 1st CDST100 and CDST01C but not sure how can I compare with subsequent CDST100 with CDST10C?
SELECT count(T.id) FROM prod_replay_in T JOIN prod_replay_out O ON T.CDSX_ID = O.CDSX_ID
  JOIN prod_replay_out K ON K.CDSX_ID = O.CDSX_ID
  WHERE T.MSG_TYPE = 'CDST100'
  and O.msg_type = 'CDST01C'
  and K.msg_type = 'CDST10C'
  and ( (
        min(T.cdsx_time) > O.cdsx_time
        and substr(T.bancs_msg,4,1) = substr(O.msg_body,4,1)
        )
      );

A: I have tried following code. It should work as per my knowledge. Please feel free to suggest if any scenarios are missing.
Select count(T.*) from PROD_REPLAY_IN T, PROD_REPLAY_OUT O
Where T.msg_type = 'CDST100'
AND O.msg_type IN ('CDST01C', 'CDST10C')
AND T.cdsx_id = O.cdsx_id
AND substr(T.bancs_msg,4,1) = substr(O.msg_body,4,1)
AND (O.cdsx_id, O.cdsx_time) IN (Select Y.cdsx_id, Max(Y.cdsx_time) from PROD_REPLAY_OUT Y
        Where Y.msg_type IN ('CDST01C', 'CDST10C')
        AND O.cdsx_id = Y.cdsx_id
        AND T.cdsx_time > Y.cdsx_time
        GROUP BY Y.cdsx_id
        )

A: So long as you know that there will be a corresponding prod_replay_out row for every prod_replay_in row by timestamps, you can set this up to use window functions to sidestep the different message types at the beginning of a replay:
with interleave as (
  select msg_type, cdsx_time, cdsx_id, bancs_msg as msg, 'in' as direction
    from prod_replay_in
  union all
  select msg_type, cdsx_time, cdsx_id, msg_body as msg, 'out' as direction
    from prod_replay_out
), match_cdst100 as (
  select cdsx_id, msg,
         lag(msg) over (partition by cdsx_id
                            order by cdsx_time) as last_msg
    from interleave
   where msg_type = 'CDST100'
)
select cdsx_id, count(*)
  from match_cdst100
 where substr(msg, 4, 1) = substr(last_msg, 4, 1)
 group by cdsx_id;


text:
Q: What does setDefaultMaxPerRoute and setMaxTotal mean in HttpClient? I am using Apache HttpClient in one of my project. I am also using PoolingHttpClientConnectionManager along with my HttpClient as well.
I am confuse what are these properties mean. I tried going through documentation in the code but I don't see any  documentation around these variables so was not able to understand.

*

*setMaxTotal

*setDefaultMaxPerRoute

*setConnectTimeout

*setSocketTimeout

*setConnectionRequestTimeout

*setStaleConnectionCheckEnabled

Below is how I am using in my code:
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).setSocketTimeout(5 * 1000)
        .setStaleConnectionCheckEnabled(false).build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(200);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(20);

CloseableHttpClient httpClientBuilder = HttpClientBuilder.create()
        .setConnectionManager(poolingHttpClientConnectionManager).setDefaultRequestConfig(requestConfig)
        .build();

Can anyone explain me these properties so that I can understand and decide what values I should put in there. Also, are there any other properties that I should use apart from as shown above to get better performance?
I am using http-client 4.3.1

A: Some parameters are explained at http://hc.apache.org/httpclient-3.x/preference-api.html
Others must be gleaned from the source.

*

*setMaxTotal
The maximum number of connections allowed across all routes.

*

*setDefaultMaxPerRoute
The maximum number of connections allowed for a route that has not been specified otherwise by a call to setMaxPerRoute.  Use setMaxPerRoute when you know the route ahead of time and setDefaultMaxPerRoute when you do not.

*

*setConnectTimeout
How long to wait for a connection to be established with the remote server before throwing a timeout exception.

*

*setSocketTimeout
How long to wait for the server to respond to various calls before throwing a timeout exception.  See http://docs.oracle.com/javase/1.5.0/docs/api/java/net/SocketOptions.html#SO_TIMEOUT for details.

*

*setConnectionRequestTimeout
How long to wait when trying to checkout a connection from the connection pool before throwing an exception (the connection pool won't return immediately if, for example, all the connections are checked out).

*

*setStaleConnectionCheckEnabled
Can be disabled for a slight performance improvement at the cost of potential IOExceptions.  See http://hc.apache.org/httpclient-3.x/performance.html#Stale_connection_check


text:
Q: QR Code Detection from UIImage failed while converting UIImage to CIImage I am trying to decode a QR code to get its contents. Following is the code for it :
func detectQRCode(_ recImage: UIImage?) -> [CIFeature]?
{
    if let img = recImage,
    let ciImage = CIImage.init(image: img)
    {
        var options: [String: Any]
        let context = CIContext()
        options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
        let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options)
        if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String))
        {
            options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1]
        }
        else
        {
            options = [CIDetectorImageOrientation: 1]
        }
        let features = qrDetector?.features(in: ciImage, options: options)
        return features
    }
    return nil
}

if let statement fails at let ciImage = CIImage.init(image: img). Please suggest.

A: Please try to get ciImage from property of UIImage like -
if let ciImage = recImage?.ciImage

Updated Code should look like this -
func detectQRCode(_ recImage: UIImage?) -> [CIFeature]?
{
    if let ciImage = recImage?.ciImage
    {
        var options: [String: Any]
        let context = CIContext()
        options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
        let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options)
        if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String))
        {
            options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1]
        }
        else
        {
            options = [CIDetectorImageOrientation: 1]
        }
        let features = qrDetector?.features(in: ciImage, options: options)
        return features
    }
    return nil
}


text:
Q: Download from Laravel storage without loading whole file in memory I am using Laravel Storage and I want to serve users some (larger than memory limit) files. My code was inspired from a post in SO and it goes like this:
$fs = Storage::getDriver();
$stream = $fs->readStream($file->path);

return response()->stream(
    function() use($stream) {
        fpassthru($stream);
    },
    200,
    [
        'Content-Type' => $file->mime,
        'Content-disposition' => 'attachment; filename="'.$file->original_name.'"',
    ]);

Unfourtunately, I run into an error for large files:
[2016-04-21 13:37:13] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Allowed memory size of 134217728 bytes exhausted (tried to allocate 201740288 bytes)' in /path/app/Http/Controllers/FileController.php:131
Stack trace:
#0 /path/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(133): Symfony\Component\Debug\Exception\FatalErrorException->__construct()
#1 /path/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(118): Illuminate\Foundation\Bootstrap\HandleExceptions->fatalExceptionFromError()
#2 /path/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(0): Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#3 /path/app/Http/Controllers/FileController.php(131): fpassthru()
#4 /path/vendor/symfony/http-foundation/StreamedResponse.php(95): App\Http\Controllers\FileController->App\Http\Controllers\{closure}()
#5 /path/vendor/symfony/http-foundation/StreamedResponse.php(95): call_user_func:{/path/vendor/symfony/http-foundation/StreamedResponse.php:95}()
#6 /path/vendor/symfony/http-foundation/Response.php(370): Symfony\Component\HttpFoundation\StreamedResponse->sendContent()
#7 /path/public/index.php(56): Symfony\Component\HttpFoundation\Response->send()
#8 /path/public/index.php(0): {main}()
#9 {main}

It seems that it tries to load all of the file into memory. I was expecting that usage of stream and passthru would not do this... Is there something missing in my code? Do I have to somehow specify chunk size or what?
The versions I am using are Laravel 5.1 and PHP 5.6.

A: X-Send-File.
X-Send-File is an internal directive that has variants for Apache, nginx, and lighthttpd. It allows you to completely skip distributing a file through PHP and is an instruction that tells the webserver what to send as a response instead of the actual response from the FastCGI.
I've dealt with this before on a personal project and if you want to see the sum of my work, you can access it here:
https://github.com/infinity-next/infinity-next/blob/master/app/Http/Controllers/Content/ImageController.php#L250-L450
This deals not only with distributing files, but handling streaming media seeking. You are free to use that code.
Here is the official nginx documentation on X-Send-File.
https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/
You do have to edit your webserver and mark specific directories as internal for nginx to comply with X-Send-File directives.
I have example configuration for both Apache and nginx for my above code here.
https://github.com/infinity-next/infinity-next/wiki/Installation
This has been tested on high-traffic websites. Do not buffer media through a PHP Daemon unless your site has next to no traffic or you're bleeding resources.

A: You could try using the StreamedResponse component directly, instead of the Laravel wrapper for it. StreamedResponse

A: It seems that output buffering is still building up a lot in memory.
Try disabling ob before doing the fpassthru:
function() use($stream) {
    while(ob_get_level() > 0) ob_end_flush();
    fpassthru($stream);
},

It could be that there are multiple output buffers active that is why the while is needed.

A: Instead of loading the whole file into memory at once, try to use fread to read and send it chunk by chunk.
Here is a very good article: http://zinoui.com/blog/download-large-files-with-php
<?php

//disable execution time limit when downloading a big file.
set_time_limit(0);

/** @var \League\Flysystem\Filesystem $fs */
$fs = Storage::disk('local')->getDriver();

$fileName = 'bigfile';

$metaData = $fs->getMetadata($fileName);
$handle = $fs->readStream($fileName);

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' . $metaData['path'] . '";');
header('Content-Type: ' . $metaData['type']);

/*
    I've commented the following line out.
    Because \League\Flysystem\Filesystem uses int for file size
    For file size larger than PHP_INT_MAX (2147483647) bytes
    It may return 0, which results in:

        Content-Length: 0

    and it stops the browser from downloading the file.

    Try to figure out a way to get the file size represented by a string.
    (e.g. using shell command/3rd party plugin?)
*/

//header('Content-Length: ' . $metaData['size']);

$chunkSize = 1024 * 1024;

while (!feof($handle)) {
    $buffer = fread($handle, $chunkSize);
    echo $buffer;
    ob_flush();
    flush();
}

fclose($handle);
exit;
?>

Update
A simpler way to do this: just call
if (ob_get_level()) ob_end_clean();

before returning a response.
Credit to @Christiaan
//disable execution time limit when downloading a big file.
set_time_limit(0);

/** @var \League\Flysystem\Filesystem $fs */
$fs = Storage::disk('local')->getDriver();

$fileName = 'bigfile';

$metaData = $fs->getMetadata($fileName);
$stream = $fs->readStream($fileName);

if (ob_get_level()) ob_end_clean();

return response()->stream(
    function () use ($stream) {
        fpassthru($stream);
    },
    200,
    [
        'Content-Type' => $metaData['type'],
        'Content-disposition' => 'attachment; filename="' . $metaData['path'] . '"',
    ]);

A: https://www.php.net/readfile
<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>


text:
Q: SprayJson: Object is missing required member 'User$u0020ID Here is my Json
{"preview":false,"offset":0,"result":{"User ID":"ab192013","IP
   Address":"101.2.0.11"}}

I have two case classes
   case class Sample(result: Result)
   case class Result(`User ID` : String , `IP Address`: String)

   object MyResultJsonProtocol extends DefaultJsonProtocol {
   implicit val ResultFormat = jsonFormat2(Result.apply)

   implicit def sampleFormat[jsonformat] = jsonFormat1(Sample.apply)
   }

I cannot get user ID value
Please help, I get the exception below
MalformedContent(Object is missing required member 'User$u0020ID',Some(spray.json.DeserializationException: Object is missing required member 'User$u0020ID'))


text:
Q: Angular2 Detect id and class Let say I have the following in angular:
<div class="dwiws" id="som" (click)="someFunction()">
      some content
</div>

Then in .ts, I have the following:
  someFunction(){
       //Want to detect the class and id of the div i clicked.
  };

I want to detect the id and class of the div that the click function lies.
How do I do it?

A: You can use srcElement property and get that info.
<button (click)="someFunction($event)" id="myid"
     class="myclass">Click</button>

  someFunction(event) {
      console.log(event);
      console.log(event.srcElement.attributes.id);
      console.log(event.srcElement.attributes.class);
  }


text:
Q: Export CSV with values enclosed with double quotes How do I export a CSV file where the values and fields are both enclosed in double quotes (") from Excel 2004 (Mac)?
E.g.
"Name","Telephone"
"John Doe","555-5009"

A: EDIT:
It only took me close to two years to come back and edit this. Here's a workaround that will hopefully wrap all your data in quotation marks and save as CSV. You will need to add the Microsoft Scripting Runtime reference to your VBA project (Under Tools > References...).
Sub addquotes()
Dim s As Worksheet
Dim tmpR As Range
Dim tmpArray() As Variant, out As String
Dim fso As FileSystemObject, ts As TextStream

Application.DisplayAlerts = False
Set s = ActiveSheet
Set tmpR = s.UsedRange

'Set format of all cells as Text.
tmpR.NumberFormat = "@"
tmpArray = tmpR.Value

For i = LBound(tmpArray, 1) To UBound(tmpArray, 1)
    For j = LBound(tmpArray, 2) To UBound(tmpArray, 2)
        If j = LBound(tmpArray, 2) Then out = out & Chr(34)
        out = out & tmpArray(i, j) & Chr(34)
        If j <> UBound(tmpArray, 2) Then
            out = out & "," & Chr(34)
        Else
            out = out & vbLf
        End If
    Next j
Next i
Set fso = New FileSystemObject
Set ts = fso.OpenTextFile("C:\Users\Editor 3\Desktop\yourcsv.csv", ForWriting, True)
ts.Write out
ts.Close
Application.DisplayAlerts = True
End Sub

Previous failed attempt (left only for reference; please don't use this):
Here's a macro that will open a new workbook and enter all the data from your sheet with each value enclosed in quotation marks.  You can then save this new workbook as a .CSV without disturbing your original workbook.  This will work even if your original data included formulas.
Sub addquotes()

Dim s As Worksheet, newS As Worksheet
Dim tmpR As Range
Dim tmpArray() As Variant

Set s = ActiveSheet
Set tmpR = s.UsedRange

'Loads all data from sheet into array.
tmpArray = tmpR.Value

'Adds quotes around members of array if not blank.
For i = 1 To UBound(tmpArray, 1)
    For j = 1 To UBound(tmpArray, 2)
        If tmpArray(i, j) <> "" Then
            tmpArray(i, j) = """" & tmpArray(i, j) & """"
        End If
    Next j
Next i

'Open new workbook and enter transformed data.
Set NewBook = Workbooks.Add
Set newS = NewBook.Sheets(1)
newS.Range("A1").Resize(UBound(tmpArray, 1), UBound(tmpArray, 2)) = tmpArray

End Sub


text:
Q: Connection from Spring Boot to artemis AMQP via SSL We are running on a Spring Boot project on Tomcat 9 where we need to connect to ActiveMQ Artemis via SSL. We need to have SSL in both sides. For this purpose we have created the truststores & keystores for both client server as described in the documentation.
In the broker.xml we have the acceptor like below:
<acceptor name="netty">tcp://0.0.0.0:61617?sslEnabled=true;keyStorePath=server-side-keystore.jks;keyStorePassword=secureexample;trustStorePath=server-side-truststore;trustStorePassword=secureexample;needClientAuth=true;enabledProtocols=TLSv1.2;useEpoll=true;amqpCredits=1000;amqpLowCredits=300;amqpDuplicateDetection=true</acceptor>

In the Spring configuration we have added :
      public ConnectionFactory jmsFactory( @Value("${spring.activemq.ssl.trustStorePath}") String trustStorePath,
             @Value("${spring.activemq.ssl.trustStorePass}") String trustStorePass,
              @Value("${spring.activemq.ssl.keyStorePath}") String keyStorePath,
              @Value("${spring.activemq.ssl.keyStorePass}") String keyStorePass) {

            Map<String, Object> connectionParams = new HashMap<String, Object>();

            connectionParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.HOST_PROP_NAME, "0.0.0.0"); // <-- PUT THE NATTED IP HERE!
            connectionParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, "61617");
            connectionParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.SSL_ENABLED_PROP_NAME, true);
            connectionParams.put(org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.SSL_PROVIDER, org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants.OPENSSL_PROVIDER);

            connectionParams.put("sslEnabled", true);
            connectionParams.put("keyStorePath", keyStorePath);
            connectionParams.put("keyStorePassword",keyStorePass);
            connectionParams.put("trustStorePath",trustStorePath);
            connectionParams.put("trustStorePassword", trustStorePass);
            connectionParams.put("enabledProtocols", "TLSv1.2");

            TransportConfiguration transportConfiguration = new org.apache.activemq.artemis.api.core.TransportConfiguration("org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory", connectionParams,  "nettySSL");

            ConnectionFactory connectionFactory = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);

As I am trying to deploy the project in the local Tomcat 9, this error occurs:
    11:50:32.989 [main] ERROR o.a.activemq.artemis.core.client - AMQ214016: Failed to create netty connection
    io.netty.channel.StacklessClosedChannelException: null
        at io.netty.channel.AbstractChannel$AbstractUnsafe.ensureOpen(ChannelPromise)(Unknown Source)
    javax.jms.JMSException: Failed to create session factory
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:886)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:299)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:294)
        at com.intrasoft.arpa.facade.config.FacadeConfiguration.jmsFactory(FacadeConfiguration.java:125)
        at com.intrasoft.arpa.facade.config.FacadeConfiguration$$EnhancerBySpringCGLIB$$b016d84a.CGLIB$jmsFactory$1(<generated>)
        at com.intrasoft.arpa.facade.config.FacadeConfiguration$$EnhancerBySpringCGLIB$$b016d84a$$FastClassBySpringCGLIB$$fd925062.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)
        at com.intrasoft.arpa.facade.config.FacadeConfiguration$$EnhancerBySpringCGLIB$$b016d84a.jmsFactory(<generated>)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:769)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:326)
        at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:173)
        at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:153)
        at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:95)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5166)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
        at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:843)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
        at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:434)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:342)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:473)
    Caused by: ActiveMQNotConnectedException[errorType=NOT_CONNECTED message=AMQ219007: Cannot connect to server(s). Tried with all available servers.]
        at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:703)
        at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.createConnectionInternal(ActiveMQConnectionFactory.java:884)
        ... 120 more
    11:50:34.732 [main] ERROR o.a.activemq.artemis.core.client - AMQ214016: Failed to create netty connection
    io.netty.channel.StacklessClosedChannelException: null
        at io.netty.channel.AbstractChannel$AbstractUnsafe.ensureOpen(ChannelPromise)(Unknown Source)
    11:50:34.738 [main] ERROR o.a.activemq.artemis.core.client - AMQ214016: Failed to create netty connection

Any ideas? Does Tomcat need configuration also?


text:
Q: Weird permissions issue with WD MyBook? I run Win 7 Pro 64 bit on desktop. I have several external drives, which I use for data backups and Acronis system image backups.
One of these drives is a WD MyBook (3 TB). Recently I ran the backup program I have been using for years (Cobian) to back up files from an internal data drive.
The backup completed successfully, but when I checked the data folder it was empty. When I tried to delete the folder, I was denied due to a permissions issue.
I am the only user and have admin rights.
I decided to reformat the drive in Acronis True Image. It would not complete.
I subsequently reformatted (GPT) in Windows, then ran the same backup (600 GB). It completed the backup, the files were there (I did a spot check of several folders) and WinDirStat also showed the correct numbers for used and available space.
Upon reboot Windows Explorer and WinDirStat showed the used and available space as if the back up had not been run. Sure enough files were gone and the folders were empty. What's really odd is that the folder structure (including subfolders) is intact, but when you get to the last nested folder (where the files would be) it's empty.
Any ideas as to what could be causing these files to disappear? I am not worried about losing files because this is a redundant backup. But I can't figure out whether it's a problem with the backup drive. I have run other backups and those files have not "disappeared."
FWIW, this drive also takes much longer for Windows to access than any of my other drives. The 2-year warranty ran out last month.

A: Start by checking the USB cable and the power cord by trying different ones and see if there's any difference.
Try other backup tools to exclude the backup software as the potential cause.
Try the same software on a different computer to exclude OS or specific hardware issues on yours.
Test the drive with WD Data Lifeguard Diagnostic (quick and extended tests) to check the health of the device itself. Checking the raw values of the S.M.A.R.T. status is also a good thing to do here.
Mind that the WD My Book features hardware encryption and some specific software applications may have issues with that for one reason or another.
Check if you have all your latest BIOS, OS and driver updates installed on your system.


text:
Q: Parameterize POST body in JMeter HTTP POST I am using Apache JMeter to run a few performance tests against RESTFUL API for an application that we have developed. I have an end point "api/create/empListJob", which basically adds one or more employee records in the MongoDB. The payload for the POST call looks like this:
{
        "employeeList": [
            {
                "first_name": "josh",
                "last_name": "don",
                "age": "25",
                "address": {
                    "street1": "xyz",
                    "street2": "apt-10",
                    "city" : "def",
                    "state" : "CA",
                    "zip" : "95055"
                },
                "deptType": {
                    "deptID": "1",
                    "deptName": "R&D"
                }
            },
            {
                "first_name": "mary",
                "last_name": "jane",
                "age": "22",
                "address": {
                    "street1": "zzz",
                    "street2": "apt-15",
                    "city" : "yyy",
                    "state" : "CA",
                    "zip" : "95054"
                },
                "deptType": {
                    "deptID": "2",
                    "deptName": "HR"
                }
            }
        ]
    }

As you can see, the payload takes a list of employee data, and it should have atleast one employee record. I have a requirement in which i want JMeter thread group to have 10 threads and each of these threads should make a concurrent POST to "api/create/empListJob" such that the body has 10 unique employee records, thus creating a total of 100 records. What is the best way that i could parameterize the payload?

A: Take a look at JMeter Functions, like:

*

*__threadNum() - returns the number of current thread (virtual user)

*__Random() - returns a random number in a given range

*__RandomString() - returns a random string from specified input characters

*__UUID() - returns random GUID structure
So for example if you change your JSON payload to look like:
"employeeList": [
  {
      "first_name": "josh-${__threadNum}",
      "last_name": "don-${__threadNum}",
      "age": "25",
      "address": {
          "street1": "xyz",
          "street2": "apt-10",
          "city" : "def",
          "state" : "CA",
          "zip" : "95055"
      },
      "deptType": {
          "deptID": "1",
          "deptName": "R&D"
      }
  },
  {
      "first_name": "mary-${__threadNum}",
      "last_name": "jane-${__threadNum}",
      "age": "22",
      "address": {
          "street1": "zzz",
          "street2": "apt-15",
          "city" : "yyy",
          "state" : "CA",
          "zip" : "95054"
      },
      "deptType": {
          "deptID": "2",
          "deptName": "HR"
      }
  }
]
}

JMeter will create:
- `josh-1` for 1st virtual user
- `josh-2` for 2nd virtual usre
- etc.

See Apache JMeter Functions - An Introduction to get familiarized with JMeter Functions concept.


text:
Q: Calculate values of letters in string - Java I have been trying to calculate the value of each letter within a string input by the user (firstname which is then transferred to firstname1 after conversion to lowercases) in order to then add the total to the sum of an int and a double (ageWeight).
I am facing issues with the for loop which does not seem to work (without it I get a final result which does not include the value of the string, but the code at least runs to the end) as I get an error in the console (Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8).
Eclipse does not give me any error that prevents me from running the codes, so I'm a bit confused as to where in the for loop (or its structure) am I wrong. I've been looking at all sorts of things online and can't get anywhere.
Here is my entire code (before you give a low score which may block me from asking questions, please note that I do not expect anyone to do my work for me, we just don't all have the same level of understanding):

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter your firstname: ");
        String firstname = input.next();
        firstname.toLowerCase();
        String firstname1 = firstname.toLowerCase();

        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        int nameValue = alphabet.indexOf(firstname1);
        int name = 0;
            for (int i=0; i <= firstname1.length(); i++)
            {
                name = firstname1.charAt(i);
            }

        System.out.println("Please enter your age: ");
        int int1 = input.nextInt();

        System.out.println("Please enter your weight: ");
        double db = input.nextDouble();

        double ageWeight = (int1 + db);
        double total = ((ageWeight + name) +1);
        System.out.println(total);

    }

A: Note that array indices in Java (any most other languages) start at 0, not 1. This means that in your array of say n elements, indices range from 0 to n - 1.
However, with your current loop condition, i <= firstname1.length(), you will be trying to access firstname1[n] (in the loop's final iteration), which does not exist, hence the IndexOutOfBounds exception.
To fix, simply replace your loop condition with i < firstname1.length() (< instead of <=) and this should do the trick.


text:
Q: karate html report in Jenkins shows everything expanded I am using karate version 0.9.6 and I'm very happy with it. I have just a minor issue:
When running tests locally, the generated html report has many steps collapsed (like POST steps etc.) which is pretty convenient because I can expand only the steps I am interested in.
When running the same tests in Jenkins however, the same html report has all steps expanded and it can be pretty confusing to zoom in to the part you want.
I am using Firefox to display the report in both cases. Actually, I have tried also with Chrome and it didn't make any difference.
Do you know anything that could affect this behavior?
I hope I expressed the issue clearly enough, otherwise I can try and provide a screenshot.
Thank you in advance!
EDIT: I realize now that this is probably due to Jenkins security policy not allowing Javascript... is there any workaround in case someone is not allowed to change the security policy?


text:
Q: How to avoid Duplication of CSS Classes while compile LESS to CSS I am using less files for developing css but when I am compiling as css base.less get compile multiple times for eg:
style.less
   @import 'base.less'
   @import 'variable.less'
   @import '../../dashboard/my-dashboard.less'

my-dashboard.less
   @import 'base.less'
   .my-dashboard-css{
     all css goes here
}

when compiling style.less to style.css want to skip base.less from "my-dashboard.less" but i want to import base.less for reference for developer .Pls suggest me how to avoid me. Also Ihv tried @import(once) but its not working.

A: You can import only references using keyword reference: @import (reference) "foo.less";.
http://lesscss.org/features/#import-options

A: I agree to @3rdthemagical answer. So for your answer follow the link as your guideline.
Here's probably your output in the end.
style.less
   @import (reference) 'base.less'
   @import (reference) 'variable.less'
   @import (less) '../../dashboard/my-dashboard.less'

my-dashboard.less
   @import (reference) 'base.less'
   .my-dashboard-css{
     all css goes here
}

and here's my actual LESS CSS
// CodeKit Framework Libraries [Bootstrap]
@import (reference) "utilities";
@import (reference) "variables";
@import (reference) "mixins";

// Internal Libraries
@import (less) "_fonts";
@import (less) "_mixins";
@import (less) "components/default";
@import (less) "components/menu";
@import (less) "components/header";
@import (less) "components/footer";

@import (less) "components/core";

Note: All under reference will be my variables and mixins. And if you declare your import as less it will read and import the file as less content.


text:
Q: Docker LEMP stack with WordPress, what needs to connect to memcached? I'm trying to wrap my head around Docker and containerisation.
To help myself I've whipped up a little relation diagram for all the separate programs (containers).
One question that keeps cropping up is which of the programs needs to interface with Memcached? In my head I'm thinking that WordPress, nginx, postgresql and php-fpm all need to interface with Memcached.
Is this correct or do only nginx and/or php-fpm and/or postgresql need to interface with memcached?
Container relations digram


text:
Q: Location service disabled message default not showing in iPhone In my app the CLLocationManager is used to get the current user location. If the GPS is disabled by the user, then I'm expecting the default alert from apple asking to turn on the GPS services and giving an option to navigate to the settings page.
I'm not getting this alert even for the for the first time I launch the app.

A: Once the default GPS unavailable alert is shown then it will be showed for that app only after a certain period of time. I'm not sure about that time interval.


text:
Q: Disaggregate monthly forecasts into daily data I would like to disaggregate monthly forecasts of sales into daily data.
I have historical data about daily sales over the past two years (which mainly depends on deterministic effects like day-of-the-week, holiday, end-of-month effect,..).
Which technique can I use to predict future daily sales starting from available monthly forecasts according to the historical distribution of sales by day and ensuring that the daily forecasts sum up to the monthly forecasts?

A: Ideally, you want to forecast at the level you need forecasts for. One alternative is using Temporal Hierarchical forecasting via: http://robjhyndman.com/papers/temporalhierarchies.pdf - (implented in the R thief package). This uses multiple aggregation levels (daily, weekly, biweekly, etc.), forecasts out each and reconciles the forecasts. Alternatively, you could try multiple seasonal TBATS or double seasonal Holt-Winters.
Lastly, you could also try moving averages of the Day of Week pattern, index day of month, or seasonal index day of month (i.e. Jan. 2016 index 1 received 2% of total monthly volume, index day 2 received 1.4%, etc.). With all of these methods, it would be wise to use test sets to see which have the best predictive accuracy so you can select the one that is best for your data.


text:
Q: How to scroll Notebooks list at the left to the currently opened page in OneNote? I have many notebooks and many pages inside them in OneNote. They are always expanded in my work. When I find some page by search, I am unable to locate appropriate section at left. I need to scroll long list manually and catch selected item by eye. Can I scroll to current page automatically?
There were no such ability in OneNote 2013 and it is apparently no one in OneNote 2016. What are they doing there?
UPDATE
Apparently question was not set clear. I mean I already found my page, I see it on screen. Now I wish to find it's tab or know at left, to see neighboring pages or parent page.
How to do that?

A: 1.On the ribbon, click the History tab.
2.In the Authors group, click Recent Edits.
3.On the menu that appears, click a timeframe.
4.Click a page name to view its contents.
This seems like the only way to do it. You can view your edits by the time you did it


text:
Q: How to Connect Python, Oracle 11g with cx_Oracle in linux server? My oracle install folder in linux server is "/lib/oracle/11.2/client64/lib"

setting variables in ~/.bash_profile are
ORACLE_HOME=/usr/lib/oracle/11.2/client64
LD_LIBRARY_PATH=$ORACLE_HOME/lib

export ORACLE_HOME
export LD_LIBRARY_PATH

Also, link in folder "/usr/lib/oracle/11.2/client64/lib"
ls -al|grep libclntsh.so

## Results are:
libclntsh.so -> libclntsh.so.11.1
libclntsh.so.10.1 -> /oracle/app/pracle/product/11.2.0/lib/libclntsh.so
libclntsh.so.11.1

And in python
os.environ['ORACLE_HOME']
os.environ['LD_LIBRARY_PATH']

## Results are:
'/usr/lib/oracle/11.2/client64'
'/usr/lib/oracle/11.2/client64/lib'

import cx_Oracle ## This Part is ok

But, This code are Error
cx_Oracle.clientversion()
## or
dsn = cx_Oracle.makedsn('ip',port,'SID')
conn = cx_Oracle.connect(user='uid',password='pwd',dsn=dsn)

## Above Code Results:
DatabaseError:Error while trying to retrieve text for error ORA-01804

I doubt that my folder "/etc/ld.conf.d" has not "oracle-instantclient.conf" file. This folder only has "mariadb-x86x64.conf"
ip, port, SID and userid, password all correct!
What's wrong my oracle connect setting in linux server?

A: Sorry. It's my fault.
I just change the ORACLE_HOME & LD_LIBRARY_PATH and It's running.
os.environ["ORACLE_HOME"] = 'oracle/app/oracle/product/11.2.0'
os.environ["LD_LIBRARY_PATH"] = 'oracle/app/oracle/product/11.2.0/lib'
conn = oci.connect('ID/pw@localhost:port/SID')

Solved it.


text:
Q: I'm fetching dynamic data from my nodejs to reactjs but I get an error saying "POST IS NOT DEFINED" I have made entries in my mongodb database using node now I'm trying to fetch that data from backend to react front-end the 3rd party app used for cross-platform in node are cors and for react is axios(in script I have added "proxy":"http://localhost:5000"(5000 is my backend port)
Here  is my code for NovelCard.js
import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
import Card from 'react-bootstrap/Card';

import axios from 'axios';

const createSet = (post) => {
  <Card style={{ width: '18rem' }}>
    <Card.Img variant="top" src="holder.js/100px180" />
    <Card.Body>
      <Card.Title>{post.name}</Card.Title>
      <Card.Subtitle className="mb-2 text-muted">{post.author}</Card.Subtitle>
      <Card.Text>{post.synopsis}</Card.Text>
    </Card.Body>
  </Card>;
};

class Latest extends Component {
  state = {
    name: '',
    author: '',
    synopsis: '',
    post: [],
  };

  componentDidMount = () => {
    this.getData();
  };

  getData = () => {
    axios
      .get('http://localhost:5000/novels/')
      .then((res) => {
        const data = res.data;
        this.setState({ post: data });
        console.log('data recived');
      })
      .catch(() => {
        alert('error');
      });
  };

  render() {
    console.log('state', this.state);
    return <Container>{post.map(createSet)}</Container>;
  }
}
export default Latest;

I'm getting error saying ***

src\components\home\Latest\NovelCard.js   Line 45:24:  'post' is not
defined  no-undef

A: Your post variable is available within you state. You need to do something like this within your render function.
render() {
  console.log('state', this.state);
  return <Container>{this.state.post.map(createSet)}</Container>;
}

Or you can do like this as well.
render() {
  const { post } = this.state;
  console.log('state', this.state);
  return <Container>{post.map(createSet)}</Container>;
}


text:
Q: Cross-Origin Request Blocked between Angular frontend and webapi .NET core 5.0 I have .NET core 5.0 webapi that I need to use from an Angular application, they are both running on the same machine.
The error that I get is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed).

What have I done/tryed

*Read and try to apply other answers from SO

*Enabled CORS on the backend .NET core 5.0

*Included httpOptions on the frontend Angular

*Disabled windows firewall (is not the reason)

In the ConfigureServices I have tried :
/* attempt 1
services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    //builder.WithOrigins("http://example.com", "http://www.contoso.com");
                    //This is done this way to facilitate connecting frontend and backend
                    //but this should be changed to enforce certain origins or methods
                    builder.AllowAnyOrigin(). ;
                });
        });
*/

/* attempt 2
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
    builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
*/

services.AddCors(c =>
{
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});

services.AddControllers();

In the Configure method
        app.UseRouting();
        //app.UseCors("ApiCorsPolicy");
        app.UseCors(options => options.AllowAnyOrigin());

In the Angular fronted this how I try to call a GET on the API
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class BackendService {
  private readonly getMovesURL = 'http://localhost:5000/api/Game/GetPossibleMoves';

  private httpOptions: any;

  constructor(private http: HttpClient) {
    this.httpOptions = {
      observe: 'body',
      responseType: 'json',
      /*
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin':'*'
      })
      */
      headers:{'Access-Control-Allow-Origin':'*'}
    };
  }

  getGameMoves(): Observable<any> {
    console.log('calling: GetPossibleMoves');

    return this.http.get<string[]>(this.getMovesURL, this.httpOptions);
  }
}

I have also tried withou any headers, No matter which combination I try, including answer to very similar issues here in SO. Always return these errors
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed).

A: Order of the pipeline matters put app.UseCors(); at the top of your Configure().
Remove headers:{'Access-Control-Allow-Origin':'*'} on the angular side to resolve:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: header 'access-control-allow-origin' is not allowed according to header 'Access-Control-Allow-Headers' from CORS preflight response).


text:
Q: Transfer learning with small shapes? I want to create a model which can classify these images

X_train shape is (7230, 21, 21) having arrays of 21x21 as input.
I thought of using pre-trained model (transfer-learning), but these image arrays are of size 21x21 and in every model in transfer-learning there is requirement for bigger image (around 224x224).
I tried to classify it using this sequential model
model = Sequential([
    layers.Conv2D(32,(3,3), activation='relu',input_shape = (21,21,1)),
    layers.MaxPooling2D((2,2)),
    layers.Conv2D(64,(3,3),activation= 'relu'),
    layers.MaxPooling2D((2,2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(9,activation='softmax')
])

But this model is not working. Any solutions?


text:
Q: Get result from query in DO satement How to run SQL statement within an IF condition in plpgsql? I don't want to create or replace a function. This is what I tried:
DO LANGUAGE plpgsql $$
BEGIN
IF 'Khosla' = 'Khosla' THEN
SELECT * FROM test_log limit 10;
ELSE
RAISE NOTICE 'not worked';
END IF;
END;
$$;

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function "inline_code_block" line 3 at SQL statement

I also tried this but was unable to get data:
DO LANGUAGE plpgsql $$
BEGIN
if 'a' = 'a' THEN
PERFORM * FROM test_log limit 10;
else
raise notice 'not worked';
end if;
end;
$$;

Output: Query returned successfully with no result in 13 ms.

After reading document properly I came to know that PERFORM executes SQL and discards result set.
Can you help in running the SQL Statement and getting the result set?

A: You cannot return values from a DO statement. Create a plpgsql function instead.
There are several ways to define the return type with the RETURNING clause or with OUT parameters. Read the manual about CREATE FUNCTION.
There are several ways to return values from the function. Read the chapter Returning From a Function in the manual.
In particular, since you are trying to return whole rows from a table, you can use the registered type of the table for the function declaration:
CREATE FUNCTION foo ()
  RETURNING SETOF test_log
$func$
BEGIN

IF 'a' = 'a' THEN
  RETURN QUERY
  SELECT * FROM test_log LIMIT 10;
ELSE
   RAISE WARNING $$Didn't work!$$;
END IF;

END
$func$ LANGUAGE plpgsql;

Call:
SELECT * FROM foo ();

Or try a search here on SO. I posted many related code examples.
Workaround for DO statement
If you cannot use a function, the only halfway sensible workaround with a DO statement is to use a temporary table:
CREATE TEMP TABLE tbl_tmp AS
SELECT * FROM test_log LIMIT 0;

$do$
BEGIN

IF 'a' = 'a' THEN
  INSERT INTO tbl_tmp
  SELECT * FROM test_log LIMIT 10;
ELSE
   RAISE WARNING $$Didn't work!$$;
END IF;

END
$do$ LANGUAGE plpgsql;

SELECT * FROM tbl_tmp;

Temporary tables are dropped automatically at the end of the session.

A: Finally I Did IT - Passing Parameter in plpgsql function.
CREATE OR REPLACE FUNCTION param_test_1(text)
RETURNS TABLE (comp_id int, comp_name text, comp_sort text) AS $$
BEGIN
IF 'company' = $1 THEN
RETURN QUERY SELECT id::int as comp_id, ltrim(company.compname)::text as compname, ltrim(company.compname)::text as sort FROM company where deleteflag = '0' and active = '1' and id in (270,394,376,396,403);
ELSEIF 'jobs' = $1 THEN
RAISE NOTICE 'Not Working';
END IF;
RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM param_test_1('company');

This is working perfectly. Any suggestions for better approach on my work will be highly appreciated. Thanks


text:
Q: How to draw route on map with using crumb path? I have used the classes provided by apple CrumbPath.o and CrumbPathView.o, but it supports only iphone 5.0,when I try the same code with iphone 4.0 ,it does not update the route.
Code :
 if (newLocation)
    {

    if (oldLocation.coordinate.latitude == 0.0) {
        initialLocation = [[[CLLocation alloc]initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude]retain];
    }
    // make sure the old and new coordinates are different
    if((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
      (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {
    if (!crumbs)
    {
        // This is the first time we're getting a location update, so create
        // the CrumbPath and add it to the map.
        //
        crumbs = [[CrumbPath alloc] initWithCenterCoordinate:newLocation.coordinate];
        [mapView addOverlay:crumbs];

        // On the first location update only, zoom map to user location
        MKCoordinateRegion region =
        MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 2000, 2000);
        [mapView setRegion:region animated:YES];
    }
    else
    {
        // This is a subsequent location update.
        // If the crumbs MKOverlay model object determines that the current location has moved
        // far enough from the previous location, use the returned updateRect to redraw just
        // the changed area.
        //
        // note: iPhone 3G will locate you using the triangulation of the cell towers.
        // so you may experience spikes in location data (in small time intervals)
        // due to 3G tower triangulation.
        //
        Count++;
        double latitude = 0.000500 * Count;
        double longitude = 0.000020 * Count;
        _bean = [[TempBean alloc]init];
        _bean.lat = newLocation.coordinate.latitude + latitude;
        _bean.lon = newLocation.coordinate.longitude - longitude;

        CLLocation *locationToDraw = [[CLLocation alloc]initWithLatitude:_bean.lat longitude:_bean.lon];
        //                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Update_Loc" message:[NSString stringWithFormat:@"Lat:%f , Lon:%f",locationToDraw.coordinate.latitude,locationToDraw.coordinate.longitude] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"Cancel",nil];
        //                [alert show];
        //                [alert release];

        MKMapRect updateRect = [crumbs addCoordinate:locationToDraw.coordinate];

        if (!MKMapRectIsNull(updateRect))
        {
            // There is a non null update rect.
            // Compute the currently visible map zoom scale
            MKZoomScale currentZoomScale = (CGFloat)(mapView.bounds.size.width / mapView.visibleMapRect.size.width);
            // Find out the line width at this zoom scale and outset the updateRect by that amount
            CGFloat lineWidth = MKRoadWidthAtZoomScale(currentZoomScale);
            updateRect = MKMapRectInset(updateRect, -lineWidth, -lineWidth);
            // Ask the overlay view to update just the changed area.
            [crumbView setNeedsDisplayInMapRect:updateRect];
        }
        [self calDistance:initialLocation SecondCor:locationToDraw];
        [locationToDraw release];
        locationToDraw =nil;
        [_bean release];
        _bean = nil;

}}

A: If that the case then, you should try looking into your CrumbPathView.m see if the render function works correctly or not from what i see here you copied & pasted the code from Apple Docs right? In the file you should find this in method drawMapRect:zoomScale:inContext:
if (path != nil)
{
    CGContextAddPath(context, path);
    CGContextSetRGBStrokeColor(context, 0.0f, 0.0f, 1.0f, 0.6f);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, lineWidth);
    CGContextStrokePath(context);
    CGPathRelease(path);
}

See if the path is nil or not if it's nil-ed nothing gets rendered. Have you debug into this view? The rendering happens in CrumbPathView so, you should see what happen in it.
If the path is nil then you should check the method which is called to assign its value, located above the if (path != nil)


text:
Q: Necessary condition for orbits to be separated by invariant polynomials. Suppose we have an algebraic subgroup $G \subset GL(V)$, where $V$ is a finite dimensional vector space over the field of complex numbers $\mathbb{C}$. I'm trying to prove the following:

If $G$-orbits in $V$ can be separated by $G$-invariant polynomials, then $G$ is finite.

I've found out that it's important that the field is $\mathbb{C}$ (I think because $\mathbb{C}$ is closed). Over $\mathbb{R}$ we have a counterexample $SO_1 \subset GL(\mathbb{R}^3)$. But the requirement for subgroup to be algebraic prevented me to construct something of this kind for $\mathbb{C}$. So this condition is also crucial.
I have a feeling it's an easy question, but I didn't succeed in making all those conditions work together. Any hint would be appreciated.

A: We can take homogeneous generators $f_1, \dots, f_n$ of $\mathbb{C}[V]^G$ and consider a map $f : V \to \mathbb{C}^n$, $f(x) = (f_1(x), \dots, f_n(x))$. Since invariant polynomials separate $0$ from other orbits, $f^{-1}(0) = 0$. This condition together with homogeneity implies that $f$ has finite fibers (it is actually finite, When does a homogeneous morphism have only finite fibers?). Hence all orbits are finite. Hence $G$ is finite.


text:
Q: Rails & Nginx Delete request - 405 Not Allowed I'm only getting this error on my production server. It will only return a '405 Not Allowed' when I do a 'Delete' request method and it should return with some UJS. It works fine on my development machine.
Below is the code I'm using within my view. This will then return some JS.
link_to("Delete", image, method: :delete, remote: true, data: {confirm: "Are you Sure?"})

The link at the bottom is where I've got my nginx configuration as I'm using there capistrano tasks. I've googled around to see what could fix the issue but a lot I've found are over 3 years old and don't seem to do anything. For example: http://andre.arko.net/2011/06/30/rails-page-caching-nginx-and-restful-apis/
Any ideas would be great as I'm currently lost. My server configuration is: Ubuntu 12.04, Unicorn, Nginx, Rails 4, Ruby 2.
https://github.com/kalys/capistrano-nginx-unicorn/blob/master/lib/generators/capistrano/nginx_unicorn/templates/nginx_conf.erb

A: i recommend cleaning up the NGINX file by removing the IF statements and doing 301 redirects instead.  After that take care of the error page logic in your application, if you want to keep the error page logic, move it in to your server block.  Here is my working nginx.conf as an example.
https://gist.github.com/Austio/6399964


text:
Q: What is causing this strange Mathematica result? I've run into what seems like a bug in Mathematica 8. I can't find anything related to it online, but I admit I'm not exactly sure what to search for.
If I run this statement:
0.05 + .10 /. {0.15 -> "pass"}
1.04 + .10 /. {1.14 -> "pass"}
1.05 + .10 /. {1.15 -> "pass"}
1.15 /. {1.15 -> "pass"}

I get this output:
pass

pass

1.15

pass

Am I just overlooking something?
Edit: After reading the helpful discussion below, I changed my dispatch table to use a Which statement instead:
f[x_] := Which[x == 1.05, -1.709847, x == 1.10, -1.373823,
  x == 1.15, -1.119214, x == 1.20, -0.9160143, x == 1.25, -0.7470223, x == 1.30, -0.6015966]

This seems to do the trick.

A: In addition to incurring small errors when using MachinePrecision, the same floating-point calculation can produce slightly different results at different times of the day. This is not a bug, but rather a by-product of how modern hardware floating-point architectures work
This means you should not use operations like ReplaceAll that depend on knowing exact value of MachinePrecision numbers. Using == (and ===) might be OK because they ignore last 7 (respectively 1) binary digit of MachinePrecision numbers.
Using Mathematica arithmetic should give exact results regardless of time of day, you could use it for your example as follows (10 significant digits)
0.05`10 + .10`10 /. {0.15`10 -> "pass"}
1.04`10 + .10`10 /. {1.14`10 -> "pass"}
1.05`10 + .10`10 /. {1.15`10 -> "pass"}
1.15`10 /. {1.15`10 -> "pass"}

Update: What Every Computer Scientist Should Know About Floating-Point Arithmetic gives some more caveats about floating point arithmetic. For instance, page 80 gives examples of how different implementations of IEEE 754 give slightly different results, even despite being standard compliant

A: Your replacements only work on exact matches, whereas your While statement uses Equal.  You can make the rule based approach work by using Equal as well.
0.05 + .10 /. {x_ /; x == 0.15 -> "pass"}
1.04 + .10 /. {x_ /; x == 1.14 -> "pass"}
1.05 + .10 /. {x_ /; x == 1.15 -> "pass"}
1.15 /. {x_ /; x == 1.15 -> "pass"}

A: Welcome to the world of machine precision. If you examine 1.05 +.10 and 1.15 more closely, you'll see that they're not quite the same:
1.05 + .10 // FullForm

==> 1.1500000000000001`

1.15 // FullForm

==> 1.15`


text:
Q: Seleccionar el hijo del pariente de un div seleccionado estoy tratando de hacer una pestaña desplegable de una tabla de divs y quisiera cambiarle el valor de un div, específicamente el hijo de un padre que conozco su id, algo así:

Inactivo

Selector

function toggle_visibility(id) {
        var e = document.getElementById(id);
        e.style.display = ((e.style.display!='none') ? 'none' : 'block');
}

Un dato adicional es, que el id=Pariente es un módulo de varios repetidos, y hay más selector-1. Necesito qué al hacer click en el selector en otro div poder accesar al div=Hijo y modificarle el "Inactivo" por "Activo". Muchas gracias, espero con ansias sus respuestas. Saludos

A: No deberías tener varios id=pariente pero si no puedes diferenciar ese div de otros se puede seleccionar el elemento anterior y luego su hijo, algo así:

window.onload = function() {
  document.getElementById("selector-1").addEventListener("click", function() {
    this.previousElementSibling.firstElementChild.innerHTML = "activo";
  });
};
#selector-1 {
  cursor: pointer;
}
#selector-1:hover {
  color: red;
}

inactivo

selector

A: Podría ser document.querySelector("pariente").children[0].innerHTML = "Inactivo"#
Claro obviamente con la programación de el valor intercambiable para poder poner activo e Inactivo


text:
Q: How read specific positions strings and if they match, then print all the line in python? I'm learning python. I want to do this:
I have a text file with a lot of lines like this (each line have 26 strings, some strings can be whitespaces or not, followed the number of line):
      BBBTHTHTTTTCCCHHHHHH       1
CCCTTTTHHHHHHHHHHHTTTTTTTT       2
TTTTTTTTTTHHHHHHHHCCCCCC         3
CTCTTTTTTTTTTTTTTHHHHHHHHH       4

I want to read the string from 22 to 26 position, and if all these positions are H,  then print the complete line. For example:
      BBBTHTHTTTTCCCHHHHHH       1
CTCTTTTTTTTTTTTTTHHHHHHHHH       4

My script is this
f = open("file.txt", "r")
lines = [line for line in f.readlines() if line[22:26]=="H"]
print lines

anybody can help me to fix it? Thanks for your support and tips.

A: Try this:
with open('file.txt') as f:
    for i in f:
        if i[21:26]=='HHHHH':
            print(i)

A: You can use split() and endswith()
res = [line for line in f if line.split()[0].endswith('H' * (26 - 21))]
print(res)

Output:
[' BBBTHTHTTTTCCCHHHHHH       1', 'CTCTTTTTTTTTTTTTTHHHHHHHHH       4']

A: It can be :
with open('file.txt') as f:
    lines = '\n'.join([l for l in f.read().splitlines() if l[22:26] == 'HHHH'])
print(lines)


text:
Q: Multi-table optimal database design I'm a bit new to the database design. Thus this question to people who may have more experience.
I need to design a database that needs to store statistical data for many systems. The data is collected every day. There may be a couple hundred statistical counters. The number of systems can also grow.
Which database design is more efficient? From long term maintenance standpoint, from performance standpoint, etc.

*

*Design 1: one giant table with columns for counters. Then each system on each date will add its number of entries.

*Design 2: every system gets its own table dynamically created. It will contain a line for every day of statistics collection. There will also be one more table of tables that will contain the list of all system tables.

A: Of the two options mentioned, without any doubt, the first is better.  MySQL is fine at handling large tables.  There is no reason whatsoever to break the data into separate "equivalent" tables.  In fact, having multiple tables with the same layout is usually an indication of a poor database design.
For performance, you can then add indexes on the system and date (or both in one index).  You can also learn about performance.
There are some reasons why you would split the data into separate tables per system.  Here are two:

*

*If the statistics maintained for each system were very different from other systems, then it would be more efficient to store only the appropriate columns.

*If system requirements mandated data separation or permissioning.  The latter is easier to do on the table level.

You might also consider an entity-attribute-value (EAV) approach.  This would be a table where you basically have four columns:

*

*date

*system name

*statistic name

*value

You then repeat rows for each statistic.  This is usually less efficient than the single-table approach.  But it can be beneficial, particularly when you have lots of statistics, and most systems have different sets of statistics.

A: You say 100 measurements once a day. I'd have two tables as follows:
CREATE TABLE Measurement
(
  Measurement_ID INTEGER PRIMARY KEY,
  System_ID INTEGER,  -- FK into the System table
  Measurement_Date DATE (or DATETIME depending),
  Measurement_1 M1_Datatype,
  ..
  .. 100 lines
  Measurement_100 M100_Datatype
);

CREATE TABLE System
(
  System_ID INTEGER PRIMARY KEY,
  System_Location VARCHAR(3) -- maybe a code, if that suits? Zip?
  System_Description VARCHAR(50)
);

@GordonLindoff is right about it being feasible to put all this data in a single table - one system's measurements are like anothers - they're the same thing - objects which have similar attributes belong in the same table (unless your storage requirements become truly massive). Plus with a 64 bit integer as a key, you'll effectively never run out of potential PRIMARY KEYs.
See my accepted answer here for good reasons to never consider an EAV system.

A: since your date will grow rapidly. I would suggest to separate all the 'character field' into dimension and link with numeric values in the fact table which will only contain numeric data. This approach will be extremely fast and save you tone of space. also, depending on the partitioning configuration you can make it more efficient for retrial
    create table dim_system (
        system_id int PK
        system_name char
    )

    create table dim_counters (
        counter_id int PK
        counter_name char
    )

    create table fact_measurements (
        id int
        datetime datetime
        system_id FK( dim_system.system_id )
        counter_id FK( dim_counters.counter_id)
    )


text:
Q: How to add to slave's PATH using Slave SetupPlugin? I have 2 RHEL machines setup in a Master/Slave configuration using Jenkins ver. 1.609.2
The slave is being launched via SSH Slaves Plugin 1.10.
I'm trying to use the Slave Setup Plugin v 1.9 to install the tools that will be necessary for my slave machine to run builds. In particular I am installing sqlplus.
Here is the script that I am running in order to try installing sqlplus:
if command -v sqlplus >/dev/null; then
    echo "sqlplus already setup. Nothing to do."
else
    #Create directory for sqlplus and unzip it there.
    mkdir /jenkins/tools/sqlplus
    tar -xvf sqlplussetup/instantclient-basiclite-linux.x64-12.1.0.2.0.tar.gz -C /jenkins/tools/sqlplus  || { echo 'unzip failed' ; exit 1; }
    tar -xvf sqlplussetup/instantclient-sqlplus-linux.x64-12.1.0.2.0.tar.gz -C /jenkins/tools/sqlplus  || { echo 'unzip failed' ; exit 1; }

    cd /jenkins/tools/sqlplus/instantclient_12_1

    #Create links for the Oracle libs
    ln -s libclntsh.so.12.1 libclntsh.so || { echo 'Could not create link' ; exit 1; }
    ln -s libocci.so.12.1 libocci.so || { echo 'Could not create link' ; exit 1; }

    #Add two lines to .bashrc only if they don't already exist. Export LD_LIBRARY_PATH and add sqlplus to PATH.
    grep -q -F 'export LD_LIBRARY_PATH=/jenkins/tools/sqlplus/instantclient_12_1:$LD_LIBRARY_PATH' /home/jenkins/.bashrc || echo 'export LD_LIBRARY_PATH=/jenkins/tools/sqlplus/instantclient_12_1:$LD_LIBRARY_PATH' >> /home/jenkins/.bashrc
    grep -q -F 'export PATH=$PATH:/jenkins/tools/sqlplus/instantclient_12_1' /home/jenkins/.bashrc || echo 'export PATH=$PATH:/jenkins/tools/sqlplus/instantclient_12_1' >> /home/jenkins/.bashrc

    #Export variables so they can be used right away
    export LD_LIBRARY_PATH=/jenkins/tools/sqlplus/instantclient_12_1:$LD_LIBRARY_PATH
    export PATH=$PATH:/jenkins/tools/sqlplus/instantclient_12_1

    echo "sqlplus has been setup."
fi

This script runs successfully and everything appears to work until I try to run a build and execute the sqlplus command. The build fails because sqlplus is not a recognized command.
My main question is this:
What is the proper way to automatically add an environment variable when launching a slave?
Please note I am looking for an automated way of doing this. I don't want to go into the configuration screen for my slave, tick a checkbox and specify an environment variable. That is counter-productive to what I am trying to achieve which is a slave that is immediately usable for builds once connected.

I pretty much understand why my script doesn't work. When Jenkins is launching the slave it first makes an SSH connection and then it runs my setup script using the command
/bin/sh -xe /jenkins/tmp/hudson8035138410767957141.sh

Where the contents of hudson8035138410767957141.sh is my script from above. So obviously, the export isn't going to work. I was hoping adding the exports to the .bashrc file would get around this but it does not work. I think this is because this script is executed after the ssh connection is established and therefore the .bashrc has already been read.
Problem is I can't figure out any way to work around this limitation.

A: Bash does not read any of its startup files (.bashrc, .profile etc) for non-interative shells that don't have the --login option set explicitly -- that's why the exports don't work.
So, solution "A" is to keep the bashrc magic that you suggest above, and to add the --login option by changing the first line in your build step to
#!/bin/bash --login

<your script here>

The explicit shebang at on the first line will also prevent excessive debug output that you get from the default's -x option (see your console snippet above).
Alternative solution "B" uses the fact that bash will source any script whose name is given in $BASH_ENV (if that variable is defined and the file exists). Define that variable globally in your slave properties (e.g., set to /jenkins/tools/setup.sh) and add exports as needed during slave setup. Every bash shell build step will read the settings then.
With solution "B" you don't need to use the --login option and you don't have to mess up the .bashrc. However, the "BASH_ENV" feature is only active when bash runs in "bash mode". As Jenkins starts the shell via sh, bash tries to emulate historic sh, which does not have that feature. So, also for B, you need a shebang:
#!/bin/bash

<your script here>

But that you'd need anyway to get rid of the tracing output that's usually too much in production setups.


text:
Q: Finding growth bounds on Fibonacci Sequence I've been working on this following problem:

Find a constant $c< 1$ such that $F_n \leq 2^{cn}$ for all $n \geq 0$.

I honestly have no idea where to begin on this. I've done plenty of proofs the one function is Big-O another, but I'm not sure where to start looking for c in this case. Guidance appreciated. Thanks!

A: Binet's formula seems like overkill, given the (relatively weak) desired conclusion.
A more naive strategy is to pretend that $F_{n} = 2^{cn}$ and see what the recursion relation $F_{n+2} = F_{n} + F_{n+1}$ suggests. Here,
$$
2^{c(n+2)} = 2^{cn} + 2^{c(n+1)}, \quad\text{or}\quad
2^{2c} = 1 + 2^{c}.
$$
The latter is a quadratic in $2^{c}$, and by the quadratic formula has roots
$$
2^{c} = \frac{1 \pm \sqrt{5}}{2}.
$$
It's therefore natural to attempt to show $F_{n} \leq \bigl[(1 + \sqrt{5})/2\bigr]^{n}$ for $n \geq 0$; this is a straightforward induction.

A: Let $0\lt x=2^c\le 2$.
If $F_{n-2}\le x^{n-2}$ and $F_{n-1}\le x^{n-1}$ you have $F_n=F_{n-1}+F_{n-2}\le x^{n-1}+x^{n-2}$
So you will definitely succeed if you get the initial conditions (first values) to work and if  $x^{n-1}+x^{n-2}\le x^n$ which gives you $x^2-x-1\ge 0$ (dividing through by $x^{n-2}\gt 0$). For example, $x=\frac 53$ works for the inequality.
There has been some debate elsewhere about the initial values of $F_n$ - whether $F_0=0$ or $F_0=1$ - $F_0=0$ is the best choice, because then $F_n\mid F_{kn}$ for all positive integers $n$ and $k$. Then $x=\frac 53$ works for the initial values too.
Then you need to take logs to get the appropriate value of $c$. Note that $\varphi = \frac {1+\sqrt 5}2$ is the least value of $x$ which would satisfy the inequality.

A: By Binet's formula you may prove that:
$$0<F_n =\frac{1}{\sqrt{5}} \left(\frac{1+\sqrt{5}}2\right)^n-\frac{1}{\sqrt{5}} \left(\frac{1-\sqrt{5}}2\right)^n<\left(\frac{1+\sqrt{5}}2\right)^n$$ then choose $c$ such that
$$
2^c=\frac{1+\sqrt{5}}2,
$$ giving
$$
c=\frac{\ln \left(\frac{1+\sqrt{5}}2\right)}{\ln 2}=0.6942...<1.
$$

A: Hint:
$$\text{If }\phi = \frac{1 + \sqrt5}{2}, \ F(n) = \frac{\phi^n - (1-\phi)^n}{\sqrt 5}\text{ where } F(n)\text{ is the nth Fibonacci number}$$


text:
Q: Need Help on Page Object Model Implementation I am in a process of implementing Page object Model, I have one query regarding it, please see below:
I have created page files which is having locators and methods for the page, I have spec file in which I am doing the assertions by calling these methods. My question is that for one page I have over 100 test cases, now should I create single assertion file for single tests or should I create 100 assertion file for 100 test.
Please let me know what is the best way to manage it.
Regards,
Manan

A: I think it makes the most sense to group tests into files by functionality. It's hard to run only some tests from a file, so split out any groups of tests you think you might want to run independently. Are some of them suitable for a quick smoke test suite? Maybe those should be in a separate file.

A: You shouldn't need to create a new file for neither every assertion nor test case. I am confused by your question because in my understanding, the assertion is part of the test case, and test+assertion are part of the same function (assertion being the end goal of the test).
Regarding the Page Object Model: The important part of the pattern is ensuring the separation of page/DOM detail from test flow (i.e. tests should possess no knowledge of the DOM, but instead rely on page objects to act on actual pages).


text:
Q: Angular SPA can't refresh or direct navigate on nginx I have an Angular SPA that I am trying to serve on a private network via IP.
I have this configuration in nginx
server {
    listen 80 default_server;

    root /var/www/report;
    try_files $uri $uri/ index.html?$args

    server_name _;

    location /reportapi {
            rewrite                 /reportapi/(.*) /$1 break;
            proxy_pass              http://127.0.0.1:5000;
            proxy_http_version      1.1;
            proxy_set_header        Upgrade $http_upgrade;
            proxy_set_header        Connection keep-alive;
            proxy_set_header        Host $host;
            proxy_cache_bypass      $http_upgrade;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto $scheme;
}

When I navigate to the root URL say 192.168.10.10 the SPA is served correctly and navigation within it is fine. If I refresh a page or try to navigate directly to a specific URL say 192.168.10.10/scantests i get a 500 error.
The error log says
[error] 67305#67305: *2060 rewrite or internal redirection cycle while internally redirecting to "_", client: 192.168.10.77, server: , request: "GET /scantests HTTP/1.1", host: "192.168.10.10"

If I change the server_name to the IP address it has the same error but the IP address in the quotes not _. How do I setup the redirect to work correctly?