text:
Q: Have Vim remember previous line and column position How would I have Vim remember and position the cursor at the previous line position and column position when a specific file is reloaded? Right now I am able to have vim remember the line position, but vim starts at the beginning of the line instead of the previous column position.

A: You could use :mkview to save the cursor position (folds, etc.) when you close a file. Then use :loadview next time you use the file.
To make this automatic, add these lines in your vimrc:
autocmd BufWinLeave *.* mkview
autocmd BufWinEnter *.* silent loadview

You may also find the restore_view.vim plugin useful.


text:
Q: How to evaluate array formulae with the Evaluate method In VBA, the Evaluate() and [] methods can both be used to return arrays:
Dim i As Variant
i = Evaluate("{1,2;3,4}")
i = [{1,2;3,4}]

both lines set i to be a 2D array containing the numbers 1-4. An added functionality is that Evaluate(...)(1,2) returns the R1C2 indexed element of the array (i.e. 2 - [...](1,2) meanwhile errors)
I'm wondering whether there's any syntax for evaluating an array-returning worksheet function in the same way, e.g.
i = Evaluate("LEN(A1:A5)>3") 'or similar like [{LEN(A1:A5)>3}]

which should return the 1D array like {False,False,False,True,True} if I have text longer than 3 characters in A4 & A5, but it doesn't.
If not, is there another 1-liner way of evaluating an array-formula to return the full array? I'm looking for whatever approach gives the smallest character-count.

A: To return an array, you need to use a function that supports an array as a result.
The function usually used with VBA to evaluate an expression to an array is INDEX since it doesn't alter the values :
Dim data()
data = Evaluate("INDEX(LEN(A1:A5)>3,)")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Microsoft Remote Desktop cant wake W11 computer from sleep Ive got a Desktop PC which i need to connect to from time to time using Microsoft Remote Desktop Mac MRD.
Sometimes i connect via LAN sometimes i connect over Dial In VPN to the router (which places me on the LAN).
Both the LAN and VPN to LAN access work fine, but if the computer goes to sleep you can not access it via MRD, the only way to access it is by going to the computer and waking it by moving the mouse. This is fine if you are physically near it eg. on the LAN locally. But can not be done if you are remote using the VPN to LAN.
Originally the Desktop PC was connected to the network via Wifi, which i though might be the problem so ive now turned off the wifi and used a wired ethernet connection instead. But i still have the same issue when the computer sleeps MRD cant wake it.
Ive tried setting the Wake On Lan settings in the config (see screenshot attached) but again to no avail.
My only work around currently is to set the PC to never sleep, but this isnt a long term solution.
Im running W11 Pro on a system with an ASUS motherboard.
Please see link here to view screenshots of my current network card / WOL setup in device manager - https://imgur.com/a/1igi9wQ
Please see link to my current power settings here (note that these are reflective of the fact that i have set the computer to never sleep as a work around, but i do actually want it to sleep and just to be able to be woken) https://imgur.com/a/oRNQNXy

A: My friend you have allowed the computer to turn off the device to save power which means that when there is no traffic the card will be disabled and may lose the magic packet. Also take a look in your power scheme of windows and disable any power saving features for network cards and the like. My work PC had the same issues and disabling the power saving fixed it. Hope it helps

A: The Draytek Vigor2860 supports Wake-On-Lan.
From the
Draytek Vigor2860 Series User Manual page 233:

A PC client on LAN can be woken up by the router it connects. When a
user wants to wake up a specified PC through the router, he/she must
type correct MAC address of the specified PC on this web page of Wake
on LAN (WOL) of this router.
In addition, such PC must have installed
a network card supporting WOL function. By the way, WOL function must
be set as "Enable" on the BIOS setting.

To find the MAC address of the network adapter, enter in the
Command Prompt (cmd) the command ipconfig /all. The address
will be found on the line labelled "Physical Address".
It's unclear from the manual whether WOL from outside the local network
is supported, or whether you will need to login to the router in order
to send the WOL request.
Even if the later case is the right one, this method still beats
physically going to the computer in order to move the mouse.


text:
Q: Convert number in money format I have asked this question several times, but still can't find an accurate solution for it.
I have a value in string, now i want to convert it into money format. For example If a=1000 then the result will be 1,000 if a=10000 then it will become 10,000 and so on in vb.net, I tried this(below), but it did not work, It shows an error
dim no as integer =1200
dim a as string= no.ToString("C")

Error: Conversion from string "C" to type 'Integer' is not valid.

A: Could you please try this...
dim a as string= no.ToString("#,##0")

A: I am used to using string.Format
dim no as integer =1200
dim a as string = string.Format("{0:C}",no)

hope it will help


text:
Q: Google Cloud API: how to save json response when using gcloud command I am following the quickstart page on how to send an API request to Google Cloud Video API.
As such I am using the gcloud command:
gcloud ml video detect-labels gs://cloud-ml-sandbox/video/chicago.mp4

Which returns the json response as intended. However, the response is just a printout to my console.
Now I would like to know if there is any way to save/write the json response to a file?

A: If you are using linux, redirect the standard output to a file with >
With Windows, the same thing seems working. But I don't have a Windows OS for testing.
In addition, if you want to select only some parts in the response (only the business part and not the technical/protocol parts) you can use the --format param
https://cloud.google.com/sdk/gcloud/reference/topic/formats


text:
Q: Can I run Imagemagick on windows shared hosting I have shard hosting like GoDaddy with Windows. I am writing in ASP.NET c#. Can I use it from c# on the shared hosting?

A: If you can get them to install Imagemagick, then yes.


text:
Q: Regular expression which has @ because of that page is loaded I have a regular expression for checking email. This function is works in a .js file, but in a HTML file because of the @ in the expression the whole page shows? (Not Load). If I remove @ from the regular expression then the page loads properly but then the expression is not validating emails properly.
How can I make this regular expression work in a .cshtml file? The expression is:
var filter = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

Thank You.

A: Add an extra @ sign to escape the razor keyword.
var filter = /^[\w\-\.\+]+\@@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

As a side note, I'd recommend that you don't validate emails too much as this can prevent valid international addresses such as this Chinese example:

用户@例子.广告


text:
Q: Meaning of 'wasn't for nine days' The rain fell and his next appointment wasn't for nine days.
It means his appointment will start after nine days?

A: I've glanced at the source text,
google search "The End of the Day"
It does mean what you said, but it means a little more when expressed negatively. It means there were nine days that he must wait before his next appointment.
The focus of the statement is on the nine days, which is a frustrating delay because he is looking forward to the appointment.
If someone had an appointment that they feared, the nine days might be seen as a welcome delay, for example, "My next chemotherapy appointment isn't for nine days."


text:
Q: "get the boat" or "get a boat"? When talking about form of transport, we could say "take a bus", "get the subway".
In this context, should I use "get the boat" or "get a boat"?
Google Ngram gives this plot

A: You are confused on the role of "a" or "the", which have their usual meaning.
In one city there is only one subway system, so when speaking about underground trains, it is understood which system you are talking about.  Since it is determined by context you say "the subway"
On the other hand, there are many buses so you don't know which bus you will take. It is not determined; you say "a bus".  This is the normal use of "a" and "the".
It is possible that you do know which bus, or you want to say "bus" to mean "the network of buses in my city. In which case the bus is determined and you can say "I'll take the bus".
So the answer about boats has to be "Use the right word depending on what you want to say"  If you mean a particular boat, or you mean the system of boats serving a particular route then say "the boat"  if not then say "a boat".  In many cases both can be correct.  Also remember that the word "ferry" is often better for boats that you can "take".

I'd normally fly to France, but tomorrow I'm going to take [a/the] ferry. (both correct with different meaning)


text:
Q: Почему происходит замена только первого совпадения var str = "<img <img <img";
var res = str.replace("img", "img class='img-responsive'");
alert(res)

Почему здесь замещается только 1 <img

A: Потому что нет флага "g". Надо так
var res = str.replace(new RegExp("img", "g"), "img class='img-responsive'");

Или так - лучше читается, но в IE не работает:
var res = str.replace("img", "img class='img-responsive'", "g");

A: На вопрос почему может ответить спецификация, в которой приведен алгоритм работы функции String.prototype.replace

String.prototype.replace (searchValue, replaceValue )
Когда метода replace вызывается с аргументами searchValue и replaceValue выполняются следующие шаги:
Проверка, что this не null или undefined.

*

*Если searchValue не undefined и не null, тогда

*

*Пусть replacer будет методом @@replace в searchValue.

*Если replacer не undefined, тогда, параметр - регулярное выражение

*

*Вернуть результат применения replacer

*Пусть string будет this приведенный к строке.

*Пусть searchString будет searchValue приведенный к строке.

*Пусть functionalReplace - это IsCallable(replaceValue).

*Если functionalReplace равен false, тогда

*

*Пусть replaceValue - ToString(replaceValue).

*Поиск в string первого вхождения searchString и установка pos в индекс первого совпавшего символа из строки string и установка matched в значение searchString. Если ничего не найдено вернуть string.

*Если functionalReplace равен true, тогда

*

*Пусть replValue - Call(replaceValue, undefined,«matched, pos, and string»).

*Пусть replStr - ToString(replValue).

*Иначе,

*

*Пусть captures пустой список.

*Пусть replStr - GetSubstitution(matched, string, pos, captures, replaceValue).

*Пусть tailPos - pos + количество символов в совпадении.

*Пусть newString - строка сформированная объединением подстроки до pos,  replStr, и оставшейся подстроки начинающейся с индекса tailPos. Если pos равен 0, первый элемент объединения - пустая строка.

*Вернуть newString.

  Важно: Функция replace намеренно обобщена; Она не требует, чтобы this был только строкой. Таким образом, она может быть передана другим типам объектов для использования в качестве метода.


text:
Q: Ошибка "Unresolved reference: R" Скажу сразу: - я абсолютный ноль в андроид разработке.
Получил вот такую ошибку "Unresolved reference: R". Пробовал чистить, ребилдить, синхронизировать с Gradle, инвалидейтить кеш. Ничего не помогает. Я так понимаю, что мой проект не видит файл с ресурсами. Не знаю почему так произошло. Ведь до этого проект запускался без этой ошибки, а после выхода и входа в андроид студию появилась она. Как ее решить??
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "ru.temocenter.temocenter"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    } }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:27.1.1'

    // 3rd party libs
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0' }

A: Я решил этот вопрос. В общем, я просто удалил все те файлы на которые была ругань, сделал билд, посмотрел, что все работает, и добавил их снова - и все работает. Не знаю почему так происходит.

A: import android.R
Удалите эту строку. Она может быть лишней, не знаю откуда взялась

A: Так вам Android Studio подсказывает почему не может проект билднуть. В Android Issues показано в каких файлах есть ошибки. К примеру в вашей разметке activity_contact_detail.xml используется файл под названием shadow и т.д , но
 не может его найти из-за этого и происходит ошибка

A: Была похожая ситуация. Возникала при добавлении новой активити. Решалась следующим образом: File -> Invalidate Caches / Restart... -> Invalidate, затем Close Project, затем удаляем его из списка, затем открываем заново. Где-то на просторах StackOverflow это решение описывалась - не могу найти линк. В конечном итоге всё решилось тем, что я перешёл на бета версию AS и проблема исчезла. Однако при очередном обновлении всё повторилось вновь.


text:
Q: twitter return datetime to datetime format in python def _datetime(date_str):
    r=datetime.strftime(datetime.strptime(date_str,'%a %b %d %H:%M:%S +0000 %Y'),'%Y-%m-%d %H:%M:%S')
    return r

if __name__ == '__main__':

    fp = open( 'csk.csv', 'rb' )
    reader = csv.reader( fp, delimiter=',', quotechar='"', escapechar='\\' )

    c=''
    a=[]
    sent=[]
    dates=[]
    for row in reader:
        c=row[1] #twitter datetime in these format Wed Apr 22 14:29:00 +0000 2015
        b=_datetime(c)
        a.append(b)
    print a

It is giving format error when i tried these, even many previous questions supported the above striptime format, I want actually pass these parameter to plot graph.

A: def _datetime(date_str):
    r=datetime.strftime(datetime.strptime(date_str,'%a %b %d %H:%M:%S +0000 %Y'),'%Y-%m-%d %H:%M:%S')
    return r

if __name__ == '__main__':

    fp = open( 'csk.csv', 'rb' )
    reader = csv.reader( fp, delimiter=',', quotechar='"', escapechar='\\' )

    c=''
    a=[]
    sent=[]
    dates=[]
    for row in reader:
        c=row[1] #twitter datetime in these format Wed Apr 22 14:29:00 +0000 2015
        try:b=_datetime(c)
        except:pass
        a.append(b)
    print a

just adding try except block solved the issue


text:
Q: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it After hosting my Django application on Heroku while I try to download dynamic pdf my Django app's wkhtmltopdf causes this error.
In local machine(Ubuntu) I've applied
sudo apt-get install wkhtmltopdf

I've also added Aptfile with my project directory so that Heroku installs those dependency and requirements while building the application.
Aptfile:
wkhtmltopdf

But unfortunately Heroku don't even builds the app with the given dependency.
I've also tried to install it by running Heroku bash but Heroku prevents.
W: Not using locking for read only lock file /var/lib/dpkg/lock-frontend
W: Not using locking for read only lock file /var/lib/dpkg/lock
E: Unable to locate package wkhtmltopdf

My code for generating pdf is:
def pdf_generation(request, pk):
    ''' Will generate PDF file from the html template '''
    template = get_template('bankApp/print_view.html')
    withdraw_obj = get_object_or_404(Withdraw, id=pk)
    year_month_day = withdraw_obj.withdrawn_on.split('-')
    day = year_month_day[2]
    month = year_month_day[1]
    year = year_month_day[0]
    word_amount = f'{num2words(withdraw_obj.withdrawn_amount)} Only'
    date = f'{day}{month}{year}'

    html = template.render({
        'pay_to': withdraw_obj.paid_to,
        'date': date,
        'amount': withdraw_obj.withdrawn_amount,
        'amount_word': word_amount
    })
    options = {
        'page-size': 'A4',
        'margin-top': '0.0in',
        'margin-right': '0.0in',
        'margin-bottom': '0.0in',
        'margin-left': '0.0in',
        'encoding': 'UTF-8',
    }

    pdf = pdfkit.from_string(html, False, options=options)
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;\
       filename="print.pdf"'

    return response

Server Error:
OSError at /bank/pdf/print/2

No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

Request Method:     GET
Request URL:    https://issue-cheque.herokuapp.com/bank/pdf/print/2
Django Version:     3.1.7
Exception Type:     OSError
Exception Value:

No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

Exception Location:     /app/.heroku/python/lib/python3.6/site-packages/pdfkit/configuration.py, line 27, in __init__
Python Executable:  /app/.heroku/python/bin/python
Python Version:     3.6.13
Python Path:

['/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python36.zip',
 '/app/.heroku/python/lib/python3.6',
 '/app/.heroku/python/lib/python3.6/lib-dynload',
 '/app/.heroku/python/lib/python3.6/site-packages']

Server time:    Sat, 13 Mar 2021 10:51:55 +0000


text:
Q: how to mask password in bat I have this code snippet from a Stack Overflow question about masking input in a batch script.
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
echo %password%

And here is my script.
cls
@ECHO OFF
title Folder Locker
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Locker goto MDLOCKER
:CONFIRM
echo Are you sure u want to Lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Locker "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo Enter password to Unlock folder
set/p "pass=>"
if NOT %pass%==Your-Password-Here goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Locker
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Locker
echo Locker created successfully
goto End
:End

Now, I want to implement the code snippet I showed earlier into my own script, where should I put the snippet into the script? Should I remove some code or not?


text:
Q: python database search with html I have created a database with python and the results are kept in a text file.
I would like to create a simple html with a search button that looks through my database.
My database would be accessible only on my computer.
My database looks something like this:
Reference | Name | Dimension
XXX         AAA     45

So, for example, if I search for a specific reference I would like to obtain their name or dimension obviously.
Is this even possible with python and where do I start ?
I should mention I have basic skills in html and python.

A: There are multiple ways to solve this:

*

*Install a webserver on your local machine and write a full-fledged Python web application

*Write a simple webserver and application in Python using BaseHTTPServer

*Write an HTML/JavaScript application that doesn't use Python at all and parses the file for itself. Note that due to recently tightened restrictions, this may still require being served by a webserver.

*Write a Python application that writes the database to a JavaScript file. While this is inflexible (you need to run it every time you want to update the database), it's also very simple - just encode your data with JSON and write it in a JavaScript file or element, like this.

htmlfile = open('database.html', 'w')
htmlfile.write('<html>...')
htmlfile.write('<script>var db = ' + json.encode(database) + ';</script>');

Either way, you're going to have to write HTML and JavaScript.

A: You have a very simple use case and if you already have a web server installed, then probably the simplest and quickest way is to use a CGI script written in python. Check out the cgi module: http://docs.python.org/library/cgi.html.
Basically you have to handle GET request to show a HTML form for asking the query string and the POST request to process the query and show the results.


text:
Q: Android in app purchase does not returns products detail I am working on android in app purchase billing api.
I have created an app on api console and uploaded signed apk on play store under alpha testing.
I have added product in product list.
but when query product list it returns blank array.
Code for call product listing -
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {

mHelper.queryInventoryAsync(true,mList,mGotInventoryListener);
}

and code of inventory finish listener is -
  public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
        Log.d(TAG, "Query inventory finished.");

 }

this method always return product list blank.
any one can please help me i am facing problem is this topic from last 3 days.
Thanks in advance.

A: After westing alote of time i was found solution of my problem.
I was just forget to publish my App,i was thinking that it does not require to publish in Alpha testing but i was wrong.


text:
Q: NHibernate - one-to-one relationship I have a problem with one-to-one relationships in NHibernate. The structures of the my objects are as follows:
public partial class PersonDataContext
{
    protected int _personid;
    protected string _name;
    protected EmployeeDataContext _employee;
}

public partial class EmployeeDataContext
{
    protected int _personid;
    protected string _payrollno;
}

In my model, every PersonDataContext must contain exactly one EmployeeDataContext, and every EmployeeDataContext that exists is there to be part of an PersonDataContext . It's a common one-to-one relationship.
Now, to the mappings:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="PersonDataContext, DAL" table="`Person`" lazy="false">
        <id name="PersonId" column="`PersonId`" type="int">
            <generator class="native" />
        </id>
        <property type="string" name="name" column="`name`" />
        <one-to-one name="Employee" cascade="save-update" class="EmployeeDataContext,DAL" />
    </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="EmployeeDataContext, DAL" table="`Employee`" lazy="false">
        <id name="PersonId" column="`PersonId`">
            <generator class="foreign">
                <param name="property" >PersonId</param>
            </generator>
        </id>
        <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    </class>
</hibernate-mapping>

Then I create an PersonDataContext, that creates by itself an EmployeeDataContext. Then when I save it NHibernate throws an exception, "Unable to resolve property: PersonId".

A: The foreign property error, modify 'PersonId' to 'PersonDataContext' as follow:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
     <class name="EmployeeDataContext, DAL" table="`Employee`" lazy="false">
         <id name="PersonId" column="`PersonId`">
             <generator class="foreign">
                 <param name="property" >**PersonDataContext**</param>
             </generator>
         </id>
         <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
     </class>
</hibernate-mapping>

A: You don't have a PersonId property in EmployeeDataContext.
You should have a PersonDataContext property of type PersonDataContext, and that's what goes in the param.


text:
Q: How to add leading 0 to int variable I have a list which contains instanceNumber properties of type int I want to add leading 0 if its value is less than 10. i.e 01,02...09 after that 10,11,12 and goes on etc. I tried following code but it did not work
 var sidList = _sidRepository.GetAllList().Where(q=>q.IsDeleted==false).OrderByDescending(q=>q.Id).ToList();
            if (sidList.Count > 0)
            {
                sidList.Where(w => w.InstanceNumber<10).ToList().
                    ForEach(s => s.InstanceNumber = s.InstanceNumber.Value.ToString("D").Length + 2);
            }

A: Try this:
var sidList = _sidRepository.GetAllList()
    .Where(q => !q.IsDeleted)
    .OrderByDescending(q => q.Id)
    .ToList();

if (sidList.Any())
{
    sidList
        .Where(w => w.InstanceNumber < 10)
        .ToList()
        .ForEach(s => s.InstanceNumber = s.InstanceNumber.Value.ToString("00").Length + 2);
}

What I would suggest:
var sidList = _sidRepository.GetAllList()
    .Where(q => !q.IsDeleted)
    .OrderByDescending(q => q.Id);

if (sidList.Any())
    foreach (var item in sidList.Where(i => i.InstanceNumber < 10))
        item.InstanceNumber = item.InstanceNumber.Value.ToString("00").Length + 2;

My suggestion will return a IEnumerable<item> instead of a List<item>, but you can handle it afterwards with a .ToList() if you need it, but you'll benefit from performance, because you'll avoid ToList(ing) two times.


text:
Q: upload video to aws S3 I am trying to upload a video to an S3 bucket using the API interface, I followed the presigned URL procedure, here is my lambda function that returns the presigned URL (it returns the presigned url correctly - seemingly):
import json
import base64
import boto3
import uuid
BUCKET_NAME = 'redacted-bucket-instance'

def lambda_handler(event, context):
    actionId = uuid.uuid4()
    file_path = "video_uploads/" + str(actionId) + ".mp4"
    s3 = boto3.client('s3')
    s3Params = {
        "Bucket": BUCKET_NAME,
        "Key": file_path,
        "ContentType": 'video/mp4',
        "ACL": 'public-read'
    }
    try:
        s3_response = s3.generate_presigned_url('put_object', Params=s3Params, ExpiresIn=3600, HttpMethod="PUT")
    except Exception as e:
        raise IOError(e)
    return {
        'statusCode': 200,
        'body': {
            'file_path': file_path,
            'url': s3_response
        }
    }

when I try to upload an mp4 video with curl like this for ex:
curl -X PUT -F 'data=@ch01_00000100055009702.mp4' https://redacted-bucket-instance.s3.amazonaws.com//video_uploads/a845a97f-a218-4815-a836-376e498a4334.mp4?AWSAccessKeyId=ASIAWZPXMJR5V7GEHUJJ&Signature=zDsdfsdfqsdfD&content-type=video%2Fmp4&x-amz-acl=public-read&etc
or
curl -X PUT --data-binary '@ch01_00000100055009702.mp4' https://redacted-bucket-instance.s3.amazonaws.com//video_uploads/a845a97f-a218-4815-a836-376e498a4334.mp4?AWSAccessKeyId=ASIAWZPXMJR5V7GEHUJJ&Signature=zDsdfsdfqsdfD&content-type=video%2Fmp4&x-amz-acl=public-read&etc
in both cases, the terminal closes...whatcould I be doing wrong here?
(both url are not the ones received of course but just there for demonstration)
Edit
Adding quotes for the url prevented the terminal from closing and gave a reponse.(I'm guessing some characters needed to be escaped)
Now I'm getting this error:
<Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>ASIAWZPXMJR54PMEJVPQ</AWSAccessKeyId>

Should I add headers in the request for it to work?
(I renewed the presigned url to make sure it's valid during teseting)

A: The solution for me was to first add quotes for the url (as mentioned in the edit) and also add a Content-Type header
-H "Content-Type:video/mp4"

*

*no space between ':' and video or it will lead to an error as well (at least in my case)


text:
Q: Differential "Freshman's dream" for Laplacian operator. Today I encountered quite an interesting phenomenon. There is an exercise in multivariable calculus that asks students to prove the identity
$$
\frac{\partial^2 f}{\partial x^2} + \frac{\partial^2 f}{\partial y^2} = e^{-2\xi} \left( \frac{\partial^2 f}{\partial \xi^2} + \frac{\partial^2 f}{\partial \theta^2} \right),
$$
where the coordinates transformation is given by $(x,y) = F(\xi,\theta) = (e^\xi \cos(\theta), e^\xi \sin(\theta))$, assuming $f \in C^2$. I have seen a person misunderstood the question and proved
$$
\left(\frac{\partial f}{\partial x} \right)^2 + \left(\frac{\partial f}{\partial y} \right)^2 = e^{-2\xi} \left( \left(\frac{\partial f}{\partial \xi} \right)^2 + \left(\frac{\partial f}{\partial \theta} \right)^2 \right)
$$
instead. To my surprise, his proof contains no mistake and the misinterpreted equation is actually true!
This got me into thinking about the generalization of the above "Freshman's dream" for Laplacian operator:

Which coordinates transformation $(x,y) = F(\xi,\theta)$ (or, equivalently, $(\xi,\theta) = G(x,y)$ )has the property that for any $f\in C^2$, we have
$$\begin{align}
\frac{\partial^2 f}{\partial x^2} + \frac{\partial^2 f}{\partial y^2} &= h(\xi,\theta) \left( \frac{\partial^2 f}{\partial \xi^2} + \frac{\partial^2 f}{\partial \theta^2} \right) \\
&\text{if and only if} \\
\left(\frac{\partial f}{\partial x} \right)^2 + \left(\frac{\partial f}{\partial y} \right)^2 &= h(\xi,\theta) \left( \left(\frac{\partial f}{\partial \xi} \right)^2 + \left(\frac{\partial f}{\partial \theta} \right)^2 \right)
\end{align}$$
on an open domain $D\subset\Bbb R^2$ for some (sufficiently smooth) function $h>0$?

Here's my thought so far:
Suppose that our coordinates transformation is given by $(\xi,\theta) = G(x,y) = (G_1(x,y),G_2(x,y))$. By some calculation (that I shall skip), we can compute that the Laplacian $\Delta = \partial_x^2 + \partial_y^2$ in the coordinate $(\xi,\theta)$ can be written as
$$
\partial_x^2 + \partial_y^2 = (\Delta G_1)\partial_\xi + (\Delta G_2)\partial_\theta + |\nabla G_1|^2 \partial_\xi^2 + |\nabla G_2|^2 \partial_\theta^2 + 2(\nabla G_1 \cdot \nabla G_2)\partial_\xi \partial_\theta,
$$
hence $\partial_x^2 + \partial_y^2 = h(\partial_\xi^2 + \partial_\theta^2)$ if and only if
$$
|\nabla G_1|^2 = |\nabla G_2|^2 = h, \quad \Delta G_1 = \Delta G_2 = 0, \quad \text{and}\quad \nabla G_1 \cdot \nabla G_2 = 0.
$$
On the other hand, we have
$$
\begin{pmatrix}\partial_x f &\partial_y f \end{pmatrix} = \begin{pmatrix}\partial_\xi f &\partial_\theta f \end{pmatrix} \begin{pmatrix}\partial_x G_1 &\partial_y G_1 \\
\partial_x G_2 &\partial_y G_2 \end{pmatrix},
$$
hence in order that $(\partial_x f)^2 + (\partial_y f)^2 = h ((\partial_\xi f)^2 + (\partial_\theta f)^2 )$, we need the Jacobian matrix to be of the form
$$
\begin{pmatrix}\partial_x G_1 &\partial_y G_1 \\
\partial_x G_2 &\partial_y G_2 \end{pmatrix} = \sqrt{h}\ M,
$$
where $M$ is an orthogonal matrix at each point on $D$. In particular, this is equivalent to
$$
|\nabla G_1|^2 = |\nabla G_2|^2 = h \quad \text{and}\quad \nabla G_1 \cdot \nabla G_2 = 0.
$$
It seems like the "miracle" we have seen earlier is a little bit less surprising than expected!

From my calculation above (unless I made some mistakes), it seems like
$$\begin{align}
\partial_x^2 f + \partial_y^2 f &= h(\partial_\xi^2 f + \partial_\theta^2 f) \\
&\text{if and only if} \\
(\partial_x f)^2 + (\partial_y f)^2 &= h ((\partial_\xi f)^2 + (\partial_\theta f)^2 ) \ \ \text{and} \ \ \Delta G_1 = \Delta G_2 = 0,
\end{align}$$
i.e. $G$ is a harmonic function coordinate-wise. In particular, this is true for our original coordinate transformation function since we can rewrite $(x,y) = (e^\xi \cos(\theta), e^\xi \sin(\theta))$ as $(\xi,\theta) = G(x,y)$, where
$$
G(x,y) = (G_1(x,y) , G_2(x,y)) = \left( \frac12 \ln(x^2+y^2), \arctan\left( \frac{y}{x} \right) \right).
$$
Here $G_1$ and $G_2$ are indeed harmonic (on an appropriate domain). I want to know if we can find more interesting examples like this? I have a feeling that this should be related to holomorphic functions and harmonic conjugate but my knowledge of complex analysis is pretty limited.

Is there a general theory that would allow us to construct a coordinate transformation function $G$ satisfying the above properties?

A: Summary. The orthogonality of the matrix $M$ also implies that $\Delta G_1 = \Delta G_2 = 0$, so the two conditions are equivalent. That is, the conditions $|\nabla G_1|^2 = |\nabla G_2|^2 = h > 0$ and $\nabla G_1 \cdot \nabla G_2 = 0$ are quite restrictive and guarantee that either $G_1, G_2$ or $G_1(x, -y), -G_2(x,-y)$ are harmonic conjugates. In either case, $G$ is a conformal change of coordinates. This is part of the proof below, which answers your main question about the class of such coordinate transformations.
Discussion. The starting condition you've specified, namely that
$$
\begin{equation} \tag{*}\label{eq:conformal-lap}
\partial_x^2 + \partial_y^2 = h(\xi, \theta) \left( \partial_{\xi}^2 + \partial_{\theta}^2 \right)
\end{equation}
$$ with $G(x, y) = (\xi , \theta) \in C^2$ and $h > 0$, is equivalent to the condition that $(\xi, \theta) = G(x,y)$ is a conformal change of coordinates. Geometrically, conformality means that the coordinate transformation locally preserves angles, which analytically means that as a complex map, $G : D \to \mathbb{C}$ is (anti-)holomorphic and $\partial_x G, \partial_y G \neq 0$ on $D$.
Proof.
("$\Longleftarrow$") To see that this implies the transformation $\eqref{eq:conformal-lap}$, start by noting that by (anti-)holomorphicity, $G_1$ and $G_2$ satisfy either the Cauchy-Riemann equations $\partial_x G_1 = \partial_y G_2$ and $\partial_y G_1 = - \partial_x G_2$, or $\partial_x G_1 = -\partial_y G_2$ and $\partial_y G_1 = \partial_x G_2$. Then in either case, $\nabla G_1 \cdot \nabla G_2 = 0$ and together with $\partial_x G, \partial_y G \neq 0$ we have,
$$
|\nabla G_1|^2 = (\partial_x G_1)^2 + (\partial_y G_1)^2 = (\partial_y G_2)^2 + (\partial_x G_2)^2 = |\nabla G_2|^2 =: h > 0.
$$
Also straightforwardly, $\Delta G_1, \Delta G_2 = 0$. Combined with your computation of $\partial_x^2 + \partial_y^2$ in the new coordinates, we recover the form $\eqref{eq:conformal-lap}$.
("$\Longrightarrow$") In the opposite direction, again as you've noted, $|\nabla G_1|^2 = |\nabla G_2|^2 = h > 0$ and $\nabla G_1 \cdot \nabla G_2 = 0$ together imply that the Jacobian matrix of $G$ is $\sqrt{h} M$ with $M$ an orthogonal matrix on $D$. Since all $2 \times 2$ orthogonal matrices are either of the form $\left( \begin{smallmatrix} a & b \\ b & -a \end{smallmatrix} \right)$ or $\left( \begin{smallmatrix} a & -b \\ b & a \end{smallmatrix} \right)$, this implies either the Cauchy-Riemann equations or $\partial_x G_1 = - \partial_y G_2$ and $\partial_y G_1 = \partial_x G_2$ and since $h > 0$ we have $\partial_x G, \partial_y G \neq 0$ on $D$.
$\square$
Remarks.

*

*Since the coordinate transformations are from Euclidean coordinates, these are also known as isothermal coordinates, which speaks to the harmonicity condition on $G_1$ and $G_2$. There is some discussion on MathOverflow that might be of interest for generalisations to Riemannian manifold settings.

*In the Riemannian setting, letting $g$ be the Euclidean metric in $(x,y)$ coordinates, $G$ induces a change of metric by its pullback:
$$
  \begin{align*}
  \tilde{g} &:= G_* g \\
    &= \begin{pmatrix}
        (\partial_x G_1)^2 + (\partial_x G_2)^2 & \partial_x G_1  \partial_y G_1 + \partial_x G_2 \partial_y G_2 \\
        \partial_x G_1  \partial_y G_1 + \partial_x G_2 \partial_y G_2 & (\partial_y G_1)^2 + (\partial_y G_2)^2
       \end{pmatrix}
  \end{align*}
  $$
and the harmonic conjugate relations (that is, the Cauchy-Riemann equations) imply that $\tilde{g} = h \left( \begin{smallmatrix} 1 & 0 \\ 0 & 1 \end{smallmatrix} \right)$. Then, $\eqref{eq:conformal-lap}$ can be written $\Delta_g = h \Delta_{\tilde{g}}$, which is a form that holds for conformal changes of metric on any Riemannian surface (smooth Riemannian manifolds of dimension two).


text:
Q: ISO Year Week (YYYYww) date format in BigQuery I'm looking for a way to convert dates to ISO Year Week (YYYYww).
I used to use the following in Postgres. Does something similar exist for BigQuery?
to_char( current_date() :: DATE, 'IYYYIW' )

The output should have a leading 0 for weeks when applicable.
Cheers,

A: I have found the following solution:
SELECT FORMAT_DATE('%G%V', DATE '2020-01-15');

There is more related information in the official documentation.


text:
Q: On using "to what extent there exist" Is the phrase

to what extent there exist

a correct phrase? For example:

To what extent there exist disadvantaged families in this area?

I searched on it in google but did not find it used. So I am not sure if it is correct or not? Is there a better way to ask about the existence of a phenomenon in scientific research context?

A: You need a form of the verb "to do" in there somewhere:

To what extent does there exist disadvantaged families in this area?

That's a bit unusual though. It would be more idiomatic if you said:

To what extent do disadvantaged families exist in this area?


text:
Q: mysqli: can it prepare multiple queries in one statement? I would like to know if i can prepare one mysqli statement that executes multiple queries:
mysqli->prepare(query1 ...1,2,3 param...; query2...4,5 param...);
or
mysqli->prepare(insert into ...1,2,3 param...; insert into...4,5 param...);
and after all
mysqli->bind_param("sssss", 1, 2, 3, 4, 5);

In that way it make error: Call to a member function bind_param() on a non-object in...
$stmt = $sql->getQueryPrepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?); INSERT INTO process (id_user, idp) VALUES (?,?);");

$stmt->bind_param("ssssss",$id, $username, $pw, $email, $id, $idp);

$stmt->execute();
$stmt->close();

A: A prepared statement can only execute one MySQL query. You can prepare as many statements as you want in different variables:
$stmtUser = $sql->prepare("INSERT INTO user (id_user, username, pw, email) VALUES (?,?,?,?)");
$stmtProc = $sql->prepare("INSERT INTO process (id_user, idp) VALUES (?,?);");

And then execute them later. If you want to ensure that neither one is ever run unless both are able to run, then you need to look into transactions, like Thomas said.
Also, a general tip: "call to member function on a non-object" is the standard error you get when prepare() fails and so $stmt isn't actually a prepared statement object. It usually means you need to look for an error in your prepare() statement rather than anything later.

A: No, a single call to the mysqli prepare() function cannot prepare multiple queries at once. You can, however, prepare more than one query for execution by using different variables. The documentation for this function is available here.
It also looks like you are trying to setup a transaction, which is a different question than you asked. If that's what you really want to know, then you'll need to provide more information about your database setup and probably more specifics about the use case you are trying to solve.


text:
Q: How to display result a mysql query in node.js I'm trying to display the result of my query using res.end but i can't since i'm new to Node.js,Here's part of my code where the user enters the username and password in a form in an html file and i want to display the result of a query which is the username but what i'm getting is the all rows in the database table :
     app.post('/login/:email', function (req, res){
      connection.connect();
      email = req.body.email;
      password = req.body.password;
     if(email && password )
     {
     console.log(email);
     console.log(password);
   connection.query('SELECT username FROM user WHERE email = email and password = password', function     (error, rows, fields) {

        str='';
        for(i=0;i<rows.length;i++)
        str = str + rows[i].username +'\n';
         res.end( str);

      });
      connection.end();
     }
});

A: You are getting whole table because of this:
   connection.query('SELECT username FROM user WHERE email = email and password = password', function     (error, rows, fields) {

Every row has email = email and password = password, that is because both left and right side are evaluated as column name. That is like saying SELECT * FROM TABLE WHERE 1 = 1.
Try  changing it to:
   connection.query('SELECT username FROM user WHERE email = ? and password = ?', [email, password], function     (error, rows, fields) {

A: connection.query('SELECT username FROM user WHERE email = "email" and password = "password"', function     (error, rows, fields)
//hope this will work i add " " because string contain "" in query


text:
Q: Problems calling an as3 function from javascript So my team's project has an swf embedded in JavaScript, we're actually using java servlet's to create the html/JavaScript. I am attempting to use as3's ExternalInterface to add a callback which would get called in the javascript but everything I have tried will not work.
Here is some of the related code:
Javascript:(remember using servlets thats why this is all inside a string)

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">
    <param name="src" value="http://localhost:8080/download/FlashClient">
    <param name="width" value="760">
    <param name="height" value="600">
    <param name="align" value="middle">
    <param name="id" value="myswf">
    <param name="quality" value="high">
    <param name="bgcolor" value="#FFFFFF">
    <param name="name" value="myswf">
    <param name="allowScriptAccess" value="always">
    <param name="type" value="application/x-shockwave-flash">
    <param name="codebase" value="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="pluginspage" value="http://www.adobe.com/go/getflashplayer">
    <param name="wmode" value="opaque">
    <param name="flashvars" value="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk">
    <embed src="http://localhost:8080/download/FlashClient" width="760" height="600" align="middle" id="myswf" quality="high" bgcolor="#FFFFFF" name="myswf" allowScriptAccess="always" type="application/x-shockwave-flash" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="opaque" flashvars="challenge=c0oC5CjXjOpRagA0Eh0xi2uYCv-8HZfz-XpG2CCmJHZMnFQK8wYI4kultTUGYGff3N8-5lco_TrR2MfCvnUhVUyCOII6Xtem2rRIPD3SBJ18YxUSkH2GykI78Im2pfqw-UR44OqlOuZGafL3VRkn7KSiMm-AWbZt60MFHzHFaeEhIQke9aj04UkmaJL1MWoOU4CklVxoqX-ag146KilHEroL46JxcD9TLvCW9MG_Gv9fTAYOZK2_FEsHUMg0kP8WjyheWBftNxOuZoHQ9bIsB9EDe9pR4RwZryCjyL6p4T7Si0dMFfmEvml5mkhRYG74yj7pLDKTgHJeURUKOYY9RU9mFbsA82Q8-7cXeGlvQnk" />
    </object>
        This content requires the Adobe Flash Player and a browser with JavaScript enabled.
        Get Flash

        KingX Terms of Service |
        Privacy Policy |
        Report a Bug

Also I ripped out a bit of JavaScript code that didnt have anything to do with this problem(hopefully) so if there is a missing tag or something that's probably not my problem.
NOTE I embed this correctly and get into the swf allowing it to call javascript functions(as3 calls the getStuff fn), using the ExternalInterface, which works but JS->as3 does NOT work ='(.
Other notes,
FlashClient is the name of the swf....
I cant use the movie object for anything (the return value of getFlashMovie), if I try to use no code after works...
The action script code calls the external interface addCallback function correctly(called in a try catch that's how I know)
if(External...Availible)
External...addCallback("passStuff", as3PassStuff)
The only things I can think of;
1) The embed code isnt creating the object correctly, since I cant use the movie for anything
2) my swf is being created weird and doesnt allow script access.
We are using FlashBuilder to build the swf.

A: System.security.allowDomain("*");

in my swf and we're good.


text:
Q: refresh repaint() JAVA2D I've problems re-executing the repaint (), I can rotate the image but when I stop it (setRuletaGirando (false)) and change the value of the previous method to true, it does not rotate again.
paint the image and rotate this
public void paintComponent(Graphics g) {

    // se cargan las imagenes
    BufferedImage ruleta = cargarImagen("src/imagenes/Ruleta.png");
    BufferedImage flecha = cargarImagen("src/imagenes/Flecha.png");

    //posicion en la que se ubicara la imagen a rotar
    AffineTransform at = AffineTransform.getTranslateInstance(50, 50);

    //el metodo posiciones devuelve el entero (angulo) en la posicion iteradorimagen ,

    at.rotate(Math.toRadians(posiciones(iteradorImagen++)),ruleta.getWidth()/2,ruleta.getHeight()/2);

    Graphics2D ruleta2D=(Graphics2D) g;

    ruleta2D.setColor(Color.GREEN.darker());

    ruleta2D.fillRect(0, 0, this.getWidth(), this.getHeight());

    ruleta2D.drawImage(ruleta, at, null);
    ruleta2D.drawImage(flecha, 275, 85,50,50,this);

    // este metodo propio de la clase graphics2D es el que refresca el panel y
    //"hace girar la imagen"(repaint)
    if(ruletaGirando) {
        repaint();
    }
   }
   }
}

Method with the problem
    public void initGUI() {

        ruleta = new PanelRuleta();
        this.add(ruleta);
        Thread t = new Thread(){
           public synchronized void run() {
                try{
                    ruleta.setRuletaGirando(true);
                    Thread.sleep(4000);
                    ruleta.setRuletaGirando(false);
                    Thread.sleep(100);
                    ruleta.setRuletaGirando(true);
                }catch(InterruptedException e){}
            }
        };

        t.start();
    }

}

A: You will have to invoke the repaint() method again. Otherwise the paintComponent method won't be called.


text:
Q: What is causing Jest to show 75% branch coverage in this code? I have a file, parsePredicate.ts, which I believe has no branches in it. However, Jest coverage report is saying that it only has 75% branch coverage. Where are the branches?
parsePredicate.ts:
import parseIdentifier from "../parseIdentifier/parseIdentifier";
import parseOperator from "../parseOperator/parseOperator";
import { parseExpression } from "../parseExpression/parseExpression";

const parsePredicate = (str: string)=>{
    let {identifier: left, rest:identRest} = parseIdentifier(str);
    let {operator, rest:opRest} = parseOperator(identRest);
    let {expression: right, rest:exprRest} = parseExpression(opRest);
    return { left: left, operator: operator, right: right, rest: exprRest };
}
export default parsePredicate;

parsePredicate.test.ts:
import parsePredicate from "./parsePredicate";
import parseIdentifier from "../parseIdentifier/parseIdentifier";
import parseOperator from "../parseOperator/parseOperator";
import { parseExpression } from "../parseExpression/parseExpression";

jest.mock("../parseIdentifier/parseIdentifier");
jest.mock("../parseOperator/parseOperator");
jest.mock("../parseExpression/parseExpression");

test("Parsing a predicate with number returns proper values", ()=>{
    // @ts-ignore
    parseIdentifier.mockReturnValueOnce({identifier: "x", rest:" = 1"});
    // @ts-ignore
    parseOperator.mockReturnValueOnce({operator: "=", rest:" 1"});
    // @ts-ignore
    parseExpression.mockReturnValueOnce({expression: "1", rest:""});
    expect(parsePredicate("x = 1")).toStrictEqual({left:"x", operator:"=", right:"1", rest:""});
});
test("Parsing a predicate with math returns proper values", ()=>{
    // @ts-ignore
    parseIdentifier.mockReturnValueOnce({identifier: "x", rest:" = 1 + 1"});
    // @ts-ignore
    parseOperator.mockReturnValueOnce({operator: "=", rest:" 1 + 1"});
    // @ts-ignore
    parseExpression.mockReturnValueOnce({expression: "1 + 1", rest:""});
    expect(parsePredicate("x = 1 + 1")).toStrictEqual({left:"x", operator:"=", right:"1 + 1", rest:""});
});
test("Parsing a predicate with string returns proper values", ()=>{
    // @ts-ignore
    parseIdentifier.mockReturnValueOnce({identifier: "x", rest:" = 'Hello World'"});
    // @ts-ignore
    parseOperator.mockReturnValueOnce({operator: "=", rest:" 'Hello World'"});
    // @ts-ignore
    parseExpression.mockReturnValueOnce({expression: "'Hello World'", rest:""});
    expect(parsePredicate("x = 'Hello World'")).toStrictEqual({left:"x", operator:"=", right:"'Hello World'", rest:""});
});
test("Parsing a predicate with identifier returns proper values", ()=>{
    // @ts-ignore
    parseIdentifier.mockReturnValueOnce({identifier: "x", rest:" = ident"});
    // @ts-ignore
    parseOperator.mockReturnValueOnce({operator: "=", rest:" ident"});
    // @ts-ignore
    parseExpression.mockReturnValueOnce({expression: "ident", rest:""});
    expect(parsePredicate("x = ident")).toStrictEqual({left:"x", operator:"=", right:"ident", rest:""});
});

When I run jest --coverage I get the following output for my parsePredicate.ts file:
---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------------|---------|----------|---------|---------|-------------------
parsePredicate       |     100 |       75 |     100 |     100 |
  parsePredicate.ts  |     100 |       75 |     100 |     100 | 11

As you can see, it says that line #11 is uncovered. However, line 11 is just an export statement:
export default parsePredicate;

The lcov report looks like this:

Note that nothing changes if I press n or j.
I have been looking into this, and it seems like it may have to do with the esmodule glue code that is generated by Babel, however I am not sure how to go about fixing that.
Please leave a comment if you need any more information. Any help would be greatly appreciated.

A: After quite a long time of trying to figure out the problem on and off, I have come up to the following answer.
Basically, in my jest.config.js I was using the v8 coverage provider.
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",

I use node version 12.16.1, so this provider wasn't really great and had many issues.
Changing to the babel provider fixed all the problems I was having, and gave this code 100% branch coverage.
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "babel",


text:
Q: R: lme4 vs. glmmTMB for binomial GLMM I am fitting a GLMM to test if parasite prevalence in snails (positive snails divided by total snails) differs between different sites (site_type). Sites were sampled repeatedly over several months, so month was included as a random effect.
I have noticed that using either lme4 or glmmTMB provides different model fits (visualized and tested with the DHARMa package).

glmmTMB
glmmTMB_model <- glmmTMB::glmmTMB(BT_pos_tot/BT_tot ~ (1|month) + site_type,
                          weights = BT_tot,
                          data= df,
                          family= binomial)

sim_residuals_glmmTMB <- DHARMa::simulateResiduals(glmmTMB_model, 1000)
plot(sim_residuals_glmmTMB)
DHARMa::testDispersion(sim_residuals_glmmTMB)

> DHARMa::testDispersion(sim_residuals_glmmTMB)

    DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated

data:  simulationOutput
ratioObsSim = 0.042, p-value <0.0000000000000002
alternative hypothesis: two.sided

lme4
lme4_model <- lme4::glmer(BT_pos_tot/BT_tot ~ (1|month) + site_type,
                      weights = BT_tot,
                      data= df,
                      family= binomial)
sim_residuals_lme4 <- DHARMa::simulateResiduals(lme4_model, 1000)
plot(sim_residuals_lme4)
DHARMa::testDispersion(sim_residuals_lme4)

> DHARMa::testDispersion(sim_residuals_lme4)

    DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated

data:  simulationOutput
ratioObsSim = 1.9, p-value = 0.05
alternative hypothesis: two.sided

Questions

*

*Which method should be preferred?

*Why is the model fit so different?

The data
> dput(df)
structure(list(BT_pos_tot = c(0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 5, 0, 2, 0, 0, 0, 0,
4, 9, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 0, 0, 5, 11, 0, 0, 1,
0, 0, 2, 0, 0, 0, 0, 4, 0, 0, 0, 25, 0, 1, 0, 2, 0, 0, 0, 4,
0, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 21,
34, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 19, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 0, 1, 2, 5, 9, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 5, 2, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 17, 9, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 7, 4, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 4, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
1, 1, 7, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0), BT_tot = c(9, 129, 367,
0, 0, 20, 61, 21, 21, 0, 0, 0, 16, 17, 250, 27, 33, 0, 0, 0,
0, 0, 101, 93, 0, 213, 1123, 0, 1, 48, 0, 80, 0, 1, 837, 13,
5, 0, 13, 0, 36, 8, 0, 0, 0, 0, 105, 95, 157, 11, 0, 6, 13, 37,
154, 0, 0, 0, 23, 116, 89, 65, 2, 223, 62, 63, 0, 0, 297, 120,
0, 566, 909, 12, 0, 170, 68, 12, 25, 3, 1260, 22, 29, 2, 85,
76, 80, 45, 3, 0, 0, 0, 71, 481, 696, 0, 12, 0, 11, 76, 1, 0,
0, 30, 2, 230, 140, 0, 592, 95, 0, 0, 0, 1456, 351, 62, 401,
1699, 0, 0, 297, 49, 47, 0, 6, 1141, 67, 59, 2, 97, 47, 6, 0,
8, 8, 4, 1, 6, 166, 103, 0, 86, 64, 108, 116, 103, 847, 31, 95,
28, 0, 16, 64, 1, 0, 0, 103, 167, 0, 0, 0, 0, 3, 0, 1, 0, 0,
0, 0, 203, 221, 0, 127, 261, 0, 127, 0, 759, 44, 0, 109, 1262,
0, 0, 1, 0, 0, 0, 13, 818, 86, 34, 0, 32, 60, 0, 0, 38, 11, 1,
0, 0, 462, 635, 1, 4, 0, 0, 3, 19, 1, 0, 0, 0, 0, 150, 4, 0,
229, 252, 0, 0, 1, 703, 119, 0, 10, 886, 0, 0, 0, 0, 3, 0, 11,
948, 103, 17, 1, 1, 0, 0, 0, 21, 0, 0, 0, 3, 240, 600, 1, 0,
0, 0, 3, 14, 0, 0, 0, 21, 1, 37, 0, 21, 263, 78, 0, 0, 0, 799,
82, 42, 4, 53, 0, 0, 110, 0, 0, 0, 0, 679, 136, 6, 0, 0, 0, 0,
0, 2, 0, 0, 0, 85, 137, 34, 0, 9, 0, 0, 0, 1, 0, 0, 0, 0, 0,
1, 0, 0, 16, 13, 0, 0, 0, 550, 37, 0, 82, 33, 0, 1, 26, 0, 14,
0, 0, 412, 48, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 28, 196, 493, 0,
0, 0, 0, 0, 3, 2, 0, 0, 18, 2, 51, 7, 1, 6, 77, 0, 0, 0, 85,
4, 0, 480, 250, 0, 0, 2, 1, 6, 0, 0, 219, 38, 0, 0, 0, 0, 0,
7, 34, 0, 0, 0, 64, 202, 223, 7, 7, 0, 3, 14, 18, 0, 0, 0, 4,
64, 30, 2, 0, 20, 113, 5, 0, 0, 375, 42, 11, 160, 487, 0, 0,
25, 1, 7, 0, 0, 325, 44, 31, 0, 0, 10, 9, 5, 0, 0, 0, 0, 8, 78,
219, 0, 0, 0, 17, 1, 18, 0, 0, 0, 2, 21, 20, 9, 7, 59, 2, 0,
0, 0, 208, 7, 0, 187, 747, 0, 0, 3, 0, 3, 1, 0, 853, 19, 256,
0, 1, 13, 0, 1, 0, 0, 0, 0, 40, 463, 149, 2, 0, 7, 21, 11, 58,
0, 0, 0, 15, 36, 173, 0, 11, 46, 57, 0, 0, 0, 114, 56, 1, 79,
363, 0, 0, 9, 0, 1, 0, 0, 736, 30, 369, 29, 3, 0, 25, 2, 0, 0,
0, 0), month = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12"), class = "factor"), site_type = structure(c(6L,
1L, 2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L,
1L, 2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L,
7L, 1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L,
1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L,
3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L,
2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L, 4L,
5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L,
1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L,
3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,
1L, 2L, 7L, 1L, 1L, 2L, 3L, 4L, 2L, 4L, 6L, 1L, 2L, 1L, 2L, 4L,
5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L,
1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L,
3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L, 2L, 4L, 5L, 6L,
3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L, 1L, 2L,
4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L, 3L, 4L,
5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L,
2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L,
2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L,
1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L,
5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L,
2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L,
4L, 7L, 6L, 1L, 2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L,
1L, 2L, 3L, 1L, 2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L,
5L, 1L, 5L, 7L, 1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L,
6L, 1L, 2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L,
3L, 1L, 2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L,
5L, 7L, 1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L,
2L, 1L, 2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L,
2L, 3L, 4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L,
1L, 2L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L, 6L, 1L, 2L, 1L,
2L, 4L, 5L, 6L, 3L, 1L, 2L, 4L, 5L, 5L, 1L, 2L, 3L, 1L, 2L, 3L,
4L, 7L, 1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 5L, 1L, 5L, 7L, 1L, 2L,
1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 4L, 7L), .Label = c("can.2",
"canal.3", "pond", "rice.p", "river", "rivulet", "spillway",
"stream"), class = "factor")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -523L))


text:
Q: File.ReadAllBytes & Memorystream.ToArray return wrong data I have a weird problem. I am making a C# MVC application which generates PDF's and offers them for download with a download button.
public ActionResult Download()
{
    string url = (string)TempData["url"];

    byte[] thePdf = System.IO.File.ReadAllBytes(url);

    return File(thePdf, "application/pdf");
}

All of a sudden I can't properly convert a PDF file to byte[], either with File.ReadAllBytes() or with a Memorystream (or any other stream).
When I used a Memorystream I got an InvalidOperationException on both the ReadTimeOut and WriteTimeOut.
I implemented the code mentioned above in a new C# MVC Project and there everything worked fine. So the issue must be with the project that i'm working in.
EDIT:
When I read out the bytes, it does return a full byte array but when it is downloaded and converted back to a PDF, the PDF is empty (all pages do exist) and the name is some collection of weird characters.
In the new project, it is just the normal PDF as it should be.
Does anyone have any clue what this might be and how i could fix it?
(I can clarify more if needed)

A: Try something like this:
public ActionResult Download()
{
    string url = (string)TempData["url"];

    using (WebClient client = new WebClient())
    {
       // Download data.
       byte[] thePdf = client.DownloadData("http://url-to-your-pdf-file.com/file1");
       return File(thePdf,"application/pdf");
    }
}

A: Seems like I had a line or two too much in FilterConfig. I added 2 custom filters and that seemed to mess up everything. Now that i removed them everything works again!


text:
Q: Callable object in Kotlin or Swift Is it possible to create a callable object in Kotlin and/or Swift?
I have many objects that have just one method execute. The object is basically used as a closure. Some dependencies are captured during object construction. Some arguments are passed when the execute method is called.
The reason I'm not using plain functions is the classes implement interfaces and type checking is much more helpful though out the program.

A: You can overload the invoke operator:
class Callable(val prop: String) {
    operator fun invoke(para : String) {
        println("Invoke: $prop $para")
    }
}

fun main() {
    val c = Callable("prop")
    c("para")
}


text:
Q: Integer to string in C without preallocated char array Please, look at the following code that just convert an unsigned int to a string (there may be some unhandled cases but it's not my question), allocating  a char array in the heap and returning it, leaving the user the responsibility to free it after the use. Can you explain me why such function (and others similar) do not exist in C standard library? Yes, printf("%s\n", itos(5)) is a memory leak, but this programming pattern is already used and is consider a good practice[1]. IMO, if such functions had existed since the dawn of C we would had little memory leaks more but tons of buffer overflows less!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

char* itos(unsigned int value)
{
    int string_l = (value == 0) ? 1 : (int)log10(value) + 1;
    char *string = malloc((string_l + 1) * sizeof(char));
    int residual = value;
    int it;
    for (it = string_l - 1; it >= 0; it--) {
        int digit;
        digit = residual % 10;
        residual = residual / 10;
        string[it] = '0' + digit;
    }
    string[string_l] = '\0';
    return string;
}

int main(void)
{
    char* string = itos(534534345);
    printf("%s\n", string);
    free(string);
    return 0;
}

[1] http://www.opengroup.org/onlinepubs/009695399/functions/getaddrinfo.html
EDIT:
Habbie's answer:
char *string;
asprintf(&string, "%d", 155);
printf("%s\n", string);
free(string);

A: In my eyes, memory management is up to the caller, not the callee.  For instance, when I'm not using the standard malloc() implementation throughout my program I would be very upset about having to find and call the corresponding free(), the upshot is I wouldn't use such a function.
Edit: Your getaddrinfo() example is perfect, they provide both getaddrinfo() and freeaddrinfo(), that's the only way to make sure I'm calling the right free().

A: turns out asprintf is what you need :)

A: Programming has evolved since it was created - this is simply something that wasn't present since the dawn of C, but has evolved in other languages since.  I particularly like the way objective-c handles this by returning a string object which has been autoreleased (meaning it will be automatically freed later on, after the object has gone out of scope). You could implement something similar in C if you wanted to:

*

*create a pool for temporary allocations outside your main loop

*allocate from the pool as needed using your own allocation function

*periodically free the pool at a shallow level in your call stack (for example once per cycle in your very outer main loop)

Another way to achieve the same thing, but allowing you to use system functions that use malloc to allocate memory:

*

*outside your main loop create a list (initially empty) of 'to-be-freed' objects

*write a function called 'autofree' that adds pointers to the list and returns the pointer

*whenever you need to use it like this: printf("%s\n", autofree(itos(5)));

*each time round your main loop, free all the pointers in the list and empty the list

If you do this in a nice way, you can create multiple such autofree pools and nest them around inner loops that potentially create lots of allocations that you want to be freed sooner rather than back in your main loop.


text:
Q: ObjectInputStream fails in Java Thread I'm unable to get input and output streams from socket, my code blocks everytime it reach the getInputStream/getOutputStream.
class Connection implements Runnable {
    private static final Logger logger = Logger.getLogger(Connection.class.getName());
    Socket connection = null;
    Boolean serverIsDown = false;
    Thread thread = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    Context ctx = null;

    public Connection(Socket accept, Boolean serverIsDown) {
        logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress());
        this.connection = accept;
        this.serverIsDown = serverIsDown;

        this.thread = new Thread(this, "Client Connection");
        this.thread.start();

    }

    public void init() throws IOException {
        while (true) {
            System.out.println("Hit enter to send object");
            System.in.read();
            Request request = new Request();
            oos.writeObject(request);
        }
    }

    @Override
    public void run() {
        try {
            this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here
            this.oos = new ObjectOutputStream(this.connection.getOutputStream());
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

There's no output errors when it blocks.

A: as the documentation mentioned :
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)
Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
I suggest you use two threads handling input and output stream from accepted socket,to avoid blocking. and the other better way is to use thread pool and some async io (ex;selector) instead of assigning each accepted socket with a thread.
also refer to the other post as below:
new ObjectInputStream() blocks

A: You create a new stream for each object. Only create one output and one input stream. Object streams send header data which is maybe corrupted when you create a new stream.


text:
Q: remove , from string via def - tokenized Trying to tokenize and strip comma off value
current output with
def clean(string):
result = ""
for i,char in enumerate(line):
    if char == " ":
        if string[i+1].isdigit() or string[i+1] == " ":
            continue
    result += char
return result

latitude  +41.136778, -95.948622  65.000000   red
  latitude  +41.136778, -95.948622  65.000000   red
  latitude  +41.136778, -95.948622  65.000000   blue
  latitude  +41.136778, -95.948622  65.000000   red

If I try to add a comma to the string as such:
def clean(string):
result = ""
for i,char in enumerate(line):
    if char == " ":
        if string[i+1].isdigit() or or string[i+1] + "," string[i+1] == " ":
            continue
    result += char
return result

I get the following:

latitude  +41.137342,longitude=-95.947951bar=65.000000foo=23.849165secscolor=red   latitude   +41.137338,longitude=-95.947936bar=65.000000foo=0.036936secscolor=blue   latitude   +41.137338,longitude=-95.947936bar=65.000000foo=58.715930secscolor=blue

Desired output:

latitude  +41.136778  longitude bar -95.948622    foo 65.000000   color blue
     latitude   +41.136778  longitude bar -95.948622    foo 65.000000   color red

Thanks

A: Not sure to have completely understood, but I think the following built-in fonction might be what you're looking for:
return string.replace(",", " ")

PS: you can use it multiple times:
return string.replace(",", " ").replace("=", " ")


text:
Q: What's wrong with this handler? JS I need the text to be changed only in the selected
cell. The first time all is well. When I try in another cell, the text also changes as it should, but at the same time in the previous one too, and so on.

//change text
var changeText = function(e) {
  var inputChangeText, applyChanges, blockTd;
  inputChangeText = document.getElementById('changeText');
  applyChanges = document.getElementById('applyToChanges');

  inputChangeText.value = e.target.textContent;

  applyChanges.addEventListener('click', function() {
    e.target.textContent = inputChangeText.value;
  }, false);
}

//allow to change
function eventsInTable() {
  var checkBoxChanges = document.getElementById('changes');
  var table = document.getElementById('tableCinema');

  if (checkBoxChanges.checked) {
    table.addEventListener('click', changeText, false);
  } else {
    table.removeEventListener('click', changeText, false);
    alert("You haven't access to change");
  }
}

    Type

    1
    *
    *

Change: <input id="changes" type="checkbox" name="" onclick="eventsInTable()">
 Get text for change: <input id="changeText" type="text" name="" value="">

<button id="applyToChanges">Apply</button>

A: Hope this helps you.

var input = document.querySelector('#changeText');
var button = document.querySelector('#applyToChanges');
var table = document.querySelectorAll('table tr td');

var tobechanged = null; // remembers which td was last clicked
for(i=0;i<table.length;i++){ // adds onclicked event for every td element
  table[i].onclick = function(){
    tobechanged = this;
    input.value = this.innerHTML;
  }
}

button.onclick = function(){
  tobechanged.innerHTML = input.value; // make changes to innerhtml of last td clicked.
}
table td{
border:1px solid black;
}

        Type

        1	*	*

Get text for change: <input id="changeText" type="text" name="" value="">

<button id="applyToChanges">Apply</button>

A: Every time you call changeText() you add another listener, and they all run when you click the Apply button.
Instead of adding a listener in changeText(), just set a global variable to the element that needs to be changed.

var targetElement;

var inputChangeText = document.getElementById('changeText');

var applyChanges = document.getElementById('applyToChanges');
applyChanges.addEventListener('click', function() {
  if (targetElement) {
    targetElement.textContent = inputChangeText.value;
  }
}, false);

//change text
var changeText = function(e) {
  inputChangeText.value = e.target.textContent;
  targetElement = e.target;
}
//allow to change
function eventsInTable() {
  var checkBoxChanges = document.getElementById('changes');
  var table = document.getElementById('tableCinema');

  if (checkBoxChanges.checked) {
    table.addEventListener('click', changeText, false);
  } else {
    table.removeEventListener('click', changeText, false);
    alert("You haven't access to change");
  }
}

    Type

    1
    *
    *

Change: <input id="changes" type="checkbox" name="" onclick="eventsInTable()">
 Get text for change: <input id="changeText" type="text" name="" value="">

<button id="applyToChanges">Apply</button>


text:
Q: Verificar se dois elementos de uma lista são números Estou a tentar verificar se dois elementos de uma lista de 3 elementos são números.
Quero verificar apenas o segundo e o terceiro elementos da lista.
Tenho o seguinte código e não identifico o erro:
 (defun ICidadep (lista)
  (if((numberp (second lista))and (numberp(third lista)))t))

A: A sintaxe do and segue a mesma ideia dos outros comandos do Lisp, ou seja, em vez de fazer:
(condicao1 and condicao2)

O correto é:
(and condicao1 condicao2)

Então no seu caso seria:
(defun ICidadep(lista)
    (and (numberp (second lista))
         (numberp (third lista))))

Ou, se quiser usar como condição do if:
; se forem números, retorna 1, senão retorna zero
(defun ICidadep(lista)
    (if (and (numberp (second lista))
             (numberp (third lista)))
     1 0))

Claro que você pode trocar o 1 e 0 pelo que precisar.


text:
Q: Delete row from MySQL table via android I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> a, View v,int position, long id) {
                            Show_Alert_box(v.getContext(),
                                    "Please select action.", position);
                        }
                    });

public void Show_Alert_box(Context context, String message, int position) {
    final int pos = position;

    final AlertDialog alertDialog = new AlertDialog.Builder(context)
            .create();
    //alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
    alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
            SQLiteDatabase db = dbhelper.getWritableDatabase();
            try{

                JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);

                try {
                    int success = json2.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about product update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //adapter.notifyDataSetChanged();
                db.close();
            }catch(Exception e){
            }

        }
    });
    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            alertDialog.dismiss();
        }
    });

    alertDialog.setMessage(message);
    alertDialog.show();
}

This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        //from here
        while ((line = reader.readLine()) != null) {
            if(!line.startsWith("<", 0)){
                if(!line.startsWith("(", 0)){
                    sb.append(line + "\n");
                }
            }
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

`
And this is my PHP code:
$response = array();

if (isset($_POST['id'])) {
$id = $_POST['id'];

// include db connect class
$db = mysql_connect("localhost","tbl","password");

if (!$db) {

    die('Could not connect to db: ' . mysql_error());

}

//Select the Database

mysql_select_db("shareity",$db);

// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");

// check if row deleted or not
if (mysql_affected_rows() > 0) {
    // successfully updated
    $response["success"] = 1;
    $response["message"] = "Product successfully deleted";

    // echoing JSON response
    echo json_encode($response);
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

I'm adding the params like this:
            params.add(new BasicNameValuePair(KEY_ID, id));
            params.add(new BasicNameValuePair(KEY_AID, aid));
            params.add(new BasicNameValuePair(KEY_ANAME, an));
            params.add(new BasicNameValuePair(KEY_EVENT, ev));
            params.add(new BasicNameValuePair(KEY_COMMENT, cb));
            params.add(new BasicNameValuePair(KEY_USER, cby));
            params.add(new BasicNameValuePair(KEY_TIME, cd));

I don't get any result. Can I know why?

A: I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
    $servername = "your servername";
    $username = "your username";
    $password = "your password";
    $dbname = "your dbname";

    $link = mysql_connect($servername, $username, $password);
    mysql_select_db($dbname, $link);
    $id=$_POST['id'];
    $result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);

    $response["success"] = 1;
    $response["message"] = "Deleted successfully!";
    echo json_encode($response);
?>

Change the servername to your database url and so on the other information.


text:
Q: Attribute error when generating random numbers in Python I asked a similar question regarding this same piece of code earlier but once again I have found myself stuck. Particularly on the generation of a license plate containing two letters, two numbers, and then two letters. I hope that this question isn't a duplicate but in this circumstance I am very stuck with what to do, this is the code so far and I hope you can identify where I am going wrong:
from datetime import date, datetime, time, timedelta
import time, string
from random import uniform, random

def timeDelta():
    print("Average Speed Checker")
    start = (input("Car has passed Cam1: "))
    licensePlate = str(firstLetters + randomNumber + " " + secondLetters)
    print(licensePlate)
    if start in ("y"):
        camInput1 = datetime.now()
        print(camInput1)
        print("Car is travelling...")
        time.sleep(1)
        print("Car is travelling...")
        time.sleep(1)
        print("Car has passed cam2")
        camInput2 = camInput1 + timedelta(seconds = uniform(5, 10))
        timeDelta = camInput2 - camInput1
        distance = 200
        duration = timeDelta.total_seconds()
        print("Time Delta is equal to: {0}".format(duration))
        speedCarMs = distance/duration
        print("Car is travelling in m/s at: {0}".format(speedCarMs))
        speedCarMph = 2.237*speedCarMs
        print("Car is travelling in MPH at: {0}".format(speedCarMph))
        if speedCarMph > 60:
            fileInput:

def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    randomNumber = random.sample(possibleNumbers, 2)

def randomLetters1(y):
    return ''.join(random.choice(string.ascii_uppercase) for x in             range(y))
firstLetters = (randomLetters1(2))
secondLetters = (randomLetters1(3))

print("Choose which function you want to use: ")
while True:
    answer = (input("Choice: "))
    if answer in ("speed"):
        timeDelta()
else:
    print("Invalid response")

According to python, the issue is to do with this:
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'

A: You did not import the random module. You imported the random.random() function:
from random import uniform, random

If you wanted to use choice() and sample() as well, import that in addition:
from random import uniform, random, choice, sample

and adjust your use of those functions:
def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    randomNumber = sample(possibleNumbers, 2)

def randomLetters1(y):
    return ''.join(choice(string.ascii_uppercase) for x in range(y))

Or, instead, import just the module:
import random

and your code will work as you don't actually use random() anywhere, provided you replace uniform() with random.uniform():
camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10))

I'll reiterate again that you don't need to create camInput2, as camInput1 + some_timedelta - camInput1 produces the same value as some_timedelta; you can just use:
timeDelta = timedelta(seconds = random.uniform(5, 10))

You never call the randomNumbers() function, nor does the function return anything. The randomNumber local name in that function is not available outside of the function.
Have the function return the result and use the function where you now try to use the result via the randomNumber name:
def possibleNumber():
    possibleNumbers = (1,2,3,4,5,6,7,8,9,0)
    return random.sample(possibleNumbers, 2)

and
licensePlate = str(firstLetters + possibleNumber() + " " + secondLetters)

A: random.random, which you refer to in your code as simply random, because you imported it directly into your namespace (from random import ... random) instead of importing the entire module (import random), is a free function, which does not have an attribute named choice.
For the code you've written, calling random.choice, and random.sample, your import statement should be import random. Alternatively, switch your function calls to simply choice(...) and sample(...)...

A: I encountered the same issue when one day my code stopped working because of this same error.
Reading the other answers i came up with this workaround:
Give an alias to the random module, so that when you call the alias.choice method there is no ambiguity:
import json,random as rd, string
from random import uniform, random, choice, sample

def randomString(stringLength):
    letters = string.ascii_letters
    return ''.join(rd.choice(letters) for i in range(stringLength))


text:
Q: How to render 18267 tiny Container widgets in Flutter without hurting performance? I want to render 18267 tiny "Container" widgets in a Gridview.builder in Flutter to show the entire span of an average human life for an app I'm building. But when I do that, the app on all 3 platforms (web, mobile and desktop) slows down immensely to the point that it takes several seconds just to scroll down a bit. Also, the app takes quite a bit of time to even start when I try to render only 1/3rd of the Container widget.
Here's how the screen looks like with 5000 container widgets.
enter image description here
And here's what the code is right now.
Widget build(BuildContext context) {
    totalDays = (deathDate.difference(birthDate).inHours / 24).round();
    // totalDays = 15000;
    print(totalDays);
    // int count = 5;
    totalDays = 5000;
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: Text("347 Days - 68 Hours - 67000 Seconds left"),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SizedBox(
          height: size.height,
          width: size.width,
          child: GridView.builder(
            itemCount: totalDays,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 180,
                childAspectRatio: 1 / 2,
                mainAxisSpacing: 5,
                crossAxisSpacing: 5),
            itemBuilder: (ctx, count) {
              return Container(
                width: 15,
                height: 15,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

Is there any way I can render that many widgets efficiently without hurting performance?
Thanks.

A: These tiny squares do not need to be Container widgets. Consider using a CustomPaint to draw rectangles instead (similar to html canvas if you are familiar with that). The Flutter team made a short video tutorial on this.
After using CustomPaint, if you still run into performance issues (especially when scrolling, like have mentioned in the question), consider wraping the CustomPaint widget with a RepaintBoundary widget.


text:
Q: Different outputs when using <%= %> To get fully qualified path of application I have wrote a function:
    public class Generic
    {
        public static string FullyQualifiedApplicationPath
        {
            get
            {
                //Return variable declaration
                string appPath = string.Empty;

                //Getting the current context of HTTP request
                var context = HttpContext.Current;

                //Checking the current context content
                if (context != null)
                {
                    //Formatting the fully qualified website url/name
                    appPath = string.Format("{0}://{1}{2}{3}",
                                            context.Request.Url.Scheme,
                                            context.Request.Url.Host,
                                            context.Request.Url.Port == 80
                                                ? string.Empty
                                                : ":" + context.Request.Url.Port,
                                            context.Request.ApplicationPath);
                }

                if (appPath.EndsWith("/"))
                    appPath = appPath.Substring(0, appPath.Length - 1);

                return appPath;
            }
        }

    }

when I use it in  tag between <%=%> I am getting different outputs.
<link href="<%= Generic.FullyQualifiedApplicationPath %>/Styles/StyleSheet.css" rel="stylesheet" type="text/css" />

html output:
<link href="<%= Generic.FullyQualifiedApplicationPath %>/Styles/StyleSheet.css" rel="stylesheet" type="text/css" />

just wandering why asp.net engine sends <%= Generic.FullyQualifiedApplicationPath %> to client.
--NJ

A: ASP.NET basically treated your inline evaluation as string literal and escaped it.  You may try using Databinding syntax <%# %>
<link runat="server" id="lnkStyle" href='<%# Generic.FullyQualifiedApplicationPath   + "/Styles/StyleSheet.css"%>' rel="stylesheet" type="text/css" />

then in your code behind, override OnPreRender, and put in the following logic
lnkStyle.DataBind();
scptJQuery.DataBind();

It is important that the binding syntax is not mixed with other literals, or ASP.NET would treat the whole attribute as string literal.

A: It's because in head tag Link consider as server control and in server controls hreaf automatically decoded.
you can check add runat attribute on a tag
<a runat="server" href='<%= Generic.FullyQualifiedApplicationPath %>/Styles/StyleSheet.css'>

output will be
/Styles/StyleSheet.css" >

I think solution is pass href from code behind
<link rel="stylesheet" type="text/css" runat="server" id="mystyle" />

in code behind
mystyle.Href= Generic.FullyQualifiedApplicationPath + "/Styles/StyleSheet.css";