text:
Q: Call Function in Excel VSTO Add-in from Python (SAP Analysis Plug-in VBA macros) (Run-time error 1004: The macro may not be available) Problem summary
I am having problem with a Python code that is trying to execute a VBA Macro inside a Excel Workbook. Whenever it tries to use excel_instance.Application.Run() it raises an error:

Run-time error '1004': Cant run the macro 'SAPLogon'. The macro may
not be available in this workbook or all macros may be disabled.

So, apparently the Script is not recognizing the functions SAPLogon and SAPExecuteCommand (that belongs to SAP VSTO Plug-in. I believe it is happening because the SAP Plugin is not loading (more information about that in the section: Why do I think the problem is related to load Plugins?) into the Excel instance I have created. At least that's what I think it is.
Does anyone know how to solve it?

Detailed Problem
My intention with this project is to automate the refresh of Excel Workbooks that uses SAP Analysis for Office AddIn. This Plug-In connects with SAP to  extract information from Business Warehouses. As much as I could understand it is made with VSTO programing and it has a Macro API to use it inside Excel with the help of VBA Codes (more info here)
I want to integrate this with Python so that I can embed this code with another projects to automatically get pieces of data from SAP. So, with the help of this blog (that implements a solution with VBA) I started to look for my own solution with Python.
Bellow you can see the flow I want to do:

Here you can see the detailed process I want to cover with the Python Script:
- Green: Represent processes that I managed to implement
- Red: Process that currently is not working

Python code that I am currently using
import win32com.client as win32  # allow easy access to Window's Component Object Model (COM) and control Microsoft applications
from pathlib import Path  # Module to handle file paths

# Path of excel file to import
sap_aof_excel_file = Path.cwd().joinpath('Test_Data.xlsm')

# Declaring variables
bwclient = "999"
bwuser = "USERNAME"
bwpassword = "PASSWORD"

# Launch Excel: Create an Exel object and store it into a variable named 'excel_instance'
excel_instance = win32.gencache.EnsureDispatch('excel_instance.Application')

# Make it visible otherwise it doesn't work
excel_instance.Visible = True
excel_instance.DisplayAlerts = False

# Open the file in the new Excel instance,
#     The 1st false: don't update the links
#     The 2nd false: and don't open it read-only
workbook_sap = excel_instance.Workbooks.Open(sap_aof_excel_file, False, False)

# Force the plugin to be enabled in the instance of Excel
for addin in excel_instance.Application.COMAddIns:
    if addin.progID == 'SapExcelAddIn':
        if addin.Connect == False:
            addin.Connect = True
        elif addin.Connect == True:
            addin.Connect = False
            addin.Connect = True

# logs in to Business Warehouse
lResult = excel_instance.Application.Run("SAPLogon", "DS_1", bwclient, bwuser, bwpassword)

# execute a command to refresh the data
lResult = excel_instance.Application.Run("SAPExecuteCommand", "RefreshData", "DS_1")

# Save the file and close it
workbook_sap.Save
workbook_sap.Close()

# force the application to close
excel_instance.DisplayAlerts = True
excel_instance.Application.Quit()

# Clear out the memory
excel_instance = None
workbook_sap = None

Why do I think the problem is related to load Plugins?
I was really trying to figure out one solution to this problem. I realized that if I open the Excel Workbook by myself the SAPLogon function works well when called by a VBA Macro. It only does not work if I call it from a Python Script. So I went to VBA Studio and saw that the instance initiated by Python apparently do not load plugins.
Workbook opened by mylself: with the Plugins loaded in the explorer

Workbook opened with Python statement: without the plugins
The statement used in Python to open up the instance was win32.gencache.EnsureDispatch('Excel.Application')

So I decided to make a test. What if I call another plugin, like Data Analysis will it work?
The answer is: No. It raises the same error as SAP Plugin.

That made me happy. At least I think it is a problem related to the COM interface and not related to restrictions in the access of SAP Plugin through Python. After few research I found that you can load certain types of Plugins with the method RegisterXLL. So I added the lines bellow to my code:
# Register (or loads) XLL Excel Plugin called Data Analysis
excel_instance.RegisterXLL(r'C:\Program Files (x86)\Microsoft Office\root\Office16\Library\Analysis\ANALYS32.XLL')
# Call "Moveavg" Analysis ToolPack Function after execution of RegisterXLL
lResult = excel_instance.Application.Run("Moveavg", 'arnols', 'souza', False, True, False)

It worked!
The code executed the function from Data Analysis Plugin.

So obviously I tried to load the SAP Plugin the same way. But it wasn't successful. This method only works for XLL, not VSTO Plugins. Also, I couldn't found a solution to load properly VSTO Plugins.
excel_instance.RegisterXLL(r'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto')
It raises an error. =(

Alternatives that I have tried without success

*

*Tentative 1: Call VSTO Functions from Other Solutions (Link)

*

*Notes: I tryed to call the SAPLogon function using the statement bellow
excel_instance.Application.COMAddIns['SapExcelAddIn'].Object.SAPLogon("DS_1", bwclient, bwuser, bwpassword)

*What happened: Error

AttributeError: .SAPLogon

*

*Tentative 2: Tried to initiate the Excel Instance dynamically

*

*Notes: Changed the statement in the code
excel_instance = win32.dynamic.Dispatch('Excel.Application')

*What happened: Nothing different happened

*Tentative 3: Tried to specify the location where the Plugin is

*

*Notes: Tried two paths to the place where the plugin is

# Need to load the add ins before opening the workbook
#addin_path = r'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto'
addin_path = r'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.dll'
excel_instance.AddIns.Add(addin_path).Installed = True

*

*What happened: Error

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel',
'Add method of AddIns class failed', 'xlmain11.chm', 0, -2146827284),
None)

*

*Tentative 4: Tried exautivelly to call the Function with absulute paths

*

*Notes: Lots of tetatives

test0 = "SAPLogon"
test1 = r'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto!SAPLogon'
test2 = r'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto|vstolocal!SAPLogon'

test3 = r"'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto'!SAPLogon"
test4 = r"'C:\Program Files (x86)\SAP BusinessObjects\Office AddIn\SapExcelAddIn.vsto|vstolocal'!SAPLogon"

test5 = 'SapExcelAddIn.vsto!SAPLogon'
test6 = 'SapExcelAddIn.vsto|vstolocal!SAPLogon'

lResult = excel_instance.Application.Run(testn, "DS_1", bwclient, bwuser, bwpassword)

*

*What happened: Error

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel',
"Cannot run the macro 'SAPLogon'. The macro may not be available in
this workbook or all macros may be disabled.", 'xlmain11.chm', 0,
-2146827284), None)

A: In your VSTO addin, if you create a macro for running some background code without any ui then I suggest to create XLL instead of VSTO addin so that you can register it with RegisterXLL function as you mention in your question.
You can create XLL with Excel-DNA framework. You dont need to write too much code,
just copy paste VSTO code and changes some reference.
Or you can try to add VSTO addin using excel_instance.AddIns.Add(addin_path) and later on make installed=true.
But before doing this, check your addin is register in your user/machine registry.


text:
Q: Where can I find geodata on livestock densities? I am currently looking for geodata that represents livestocks (cattle, pig, poultry) at most detailed resolution for France. Up to now, the best data I was able to find is the FAO's GLOBAL LIVESTOCK DENSITIES (census data) data (See FAO data).
For France, the raster has an resolution that is around 3.6km. Does anyone know a better and free to use/not that expensive source? I would be also willing to geocode a livestock farms dataset or something like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Most pythonic+computationally efficient way to check if each element in 2D array A is in any of the single arrays in 2D array B, and save the results Say that I have these two 2d arrays
A = np.array(
    [[1, 3],
    [1, 4],
    [1, 7],
    [3, 4],
    [3, 7],
    [7, 4]]
)

B = np.array(
    [[2, 3],
    [4, 7]]
)

I want to record if each 1D array in A contains both elements of any of the 1d arrays in B.
For clarity, the order is not important in any case.
I also want to record if there were any 1D arrays where both elements in B were not in any of the 1D arrays in A.
Here is an example ideal result:
[{'label': 'Fail', 'pair': array([1, 3])},
 {'label': 'Fail', 'pair': array([1, 4])},
 {'label': 'Fail', 'pair': array([1, 7])},
 {'label': 'Fail', 'pair': array([3, 4])},
 {'label': 'Fail', 'pair': array([3, 7])},
 {'label': 'Pass', 'pair': array([4, 7])},
 {'label': 'n/a', 'pair': array([2, 3])}]

 array([4, 7]) has a pass because each element in that 1D array in B is contained in one of the 1D arrays in A.
 array([2, 3]) has a n/a because each element in that 1D array in B is not contained in one of the 1D arrays in A.
The rest have a Fail because each element in those 1D arrays in A is Not contained any of the 1D arrays in B.
This is my best attempt
record = []
B_leftovers = set()
for idxA, A_comb in enumerate(A):
    fulfilled = False
    for idxB, B_comb in enumerate(B):
        if B_comb[0] in A_comb and B_comb[1] in A_comb:
            record.append(
                {'pair': A_comb,
                'label': 'Pass'}
            )
            fulfilled = True
            if frozenset([B_comb[0], B_comb[1]]) in B_leftovers:
                B_leftovers.remove(frozenset([B_comb[0], B_comb[1]]))
            continue
        else:
            B_leftovers.add(frozenset([B_comb[0], B_comb[1]]))
    if fulfilled == False:
        record.append(
            {'pair': A_comb,
            'label': 'Fail'}
        )

for item in B_leftovers:
    first, second = list(item)
    record.append(
        {'pair': np.array([first, second]),
        'label': 'n/a'}
    )

record

The solution seems a little convoluted, tricky to read, and may not be most computationally efficient due to the double loop.
This question is different from other recommended questions similar to this because the order or the elements is not relevant and each 1D array in both 2D arrays is being compared to each other.

A: This is not a numpy solution but works.
(i) Create a list of sets from B: B_sets
(ii) Iterate over A and in each iteration, check if an array in A is a superset of any set in B_sets. Depending on whether it is or not, construct a dictionary differently. Keep a list of sets in B_sets that were a subset of any set in A at least once.
(iii) Add the sets on B_sets that were never a subset of any set in A into the final output list: out
B_sets = [set(arr) for arr in B]

out = []
subset_B = []
for arr in A:
    out.append({})
    for b in B_sets:
        if set(arr).issuperset(b):
            out[-1]['label'] = 'Pass'
            subset_B.append(b)
            break
    else:
        out[-1]['label'] = 'Fail'
    out[-1]['pair'] = arr

out += [{'label': 'n/a', 'pair': np.array(list(b_set))} for b_set in B_sets if b_set not in subset_B]

Output:
[{'label': 'Fail', 'pair': array([1, 3])},
 {'label': 'Fail', 'pair': array([1, 4])},
 {'label': 'Fail', 'pair': array([1, 7])},
 {'label': 'Fail', 'pair': array([3, 4])},
 {'label': 'Fail', 'pair': array([3, 7])},
 {'label': 'Pass', 'pair': array([7, 4])},
 {'label': 'n/a', 'pair': array([2, 3])}]

A: Does this solve your question?
from itertools import permutations

record = []
B_leftovers = {tuple(e) for e in B}
for idxA, A_comb in enumerate(A):
    if any(x in B for x in permutations(A_comb)):
        record.append({'pair': A_comb, 'label': 'Pass'})
        # if row has len > 2, you will have to tweak this
        for p in permutations(A_comb):
            B_leftovers.remove(p)
    else:
        record.append({'pair': A_comb, 'label': 'Fail'})

# same as you did
for item in B_leftovers:
    first, second = list(item)
    record.append(
        {'pair': np.array([first, second]),
        'label': 'n/a'}
    )


text:
Q: Быстро извлечь [netloc] из URL (scheme://netloc/path;parameters?query) и преобразовать UNIX epoch в [datetime] в столбцах DataFrame На входе небольшой txt файл размером в 50 тыс. строк
data_dir = 'data'
filename = 'gender_age_dataset.txt'
file_path = '/'.join([data_dir,filename])
df = pd.read_csv(file_path, sep='\t')

В этом файле имеется столбец с json строкой user_json состоящей из 2 атрибутов:
url и timestap.
Задача провести обработку 2 атрибутов json до Десериализации json-строк ко всему датасету.( на каждую строчку json ,будет скопирована строка из датасета столько раз сколько в json строке содержится записей)
В итоге строк будет 5 млн и постобработка на слабой машине займёт часы.
Код проводит десерилизацию json строк с размноживанием основной строки на которой json:
data = df.drop('user_json',1).join(df.user_json.apply(lambda x: json.loads(x))).to_dict('records')
res = json_normalize(data, [['user_json','visits']], ['uid','gender','age'])

2-строки из файла :
gender  age     uid     user_json
F       18-24   d50192e5-c44e-4ae8-ae7a-7cfe67c8b777    {"visits": [{"url": "http://zebra-zoya.ru/200028-chehol-organayzer-dlja-macbook-11-grid-it.html?utm_campaign=397720794&utm_content=397729344&utm_medium=cpc&utm_source=begun", "timestamp": 1419688144068}, {"url": "http://news.yandex.ru/yandsearch?cl4url=chezasite.com/htc/htc-one-m9-delay-86327.html&lr=213&rpt=story", "timestamp": 1426666298001}, {"url": "http://www.sotovik.ru/news/240283-htc-one-m9-zaderzhivaetsja.html", "timestamp": 1426666298000}, {"url": "http://news.yandex.ru/yandsearch?cl4url=chezasite.com/htc/htc-one-m9-delay-86327.html&lr=213&rpt=story", "timestamp": 1426661722001}, {"url": "http://www.sotovik.ru/news/240283-htc-one-m9-zaderzhivaetsja.html", "timestamp": 1426661722000}]}
M       25-34   d502331d-621e-4721-ada2-5d30b2c3801f    {"visits": [{"url": "http://sweetrading.ru/?p=900", "timestamp": 1419717886224}, {"url": "http://sweetrading.ru/?p=884", "timestamp": 1419717884437}, {"url": "http://sweetrading.ru/?p=1002", "timestamp": 1419717816375}, {"url": "http://101.ru/?an=port_channel_mp3", "timestamp": 1419717804934}, {"url": "http://sweetrading.ru/?cat=62", "timestamp": 1419714194423}, {"url": "http://sweetrading.ru/?p=1046", "timestamp": 1419713998481}, {"url": "http://sweetrading.ru/?p=978", "timestamp": 1419713927085}, {"url": "http://sweetrading.ru/?cat=171", "timestamp": 1419713908863}, {"url": "http://sweetrading.ru/?cat=62", "timestamp": 1419713908679}, {"url": "http://sweetrading.ru/?p=3648", "timestamp": 1419713798879}, {"url": "http://oesex.ru/955457", "timestamp": 1419595564407}, {"url": "http://www.interfax.ru/russia/408800", "timestamp": 1419542965224}, {"url": "http://101.ru/?an=port_channel_mp3&channel=30", "timestamp": 1418818241900}, {"url": "http://www.interfax.ru/russia/413508", "timestamp": 1418802080857}, {"url": "http://www.euroavtoprokat.ru/sitemap/car-rental/france.htm", "timestamp": 1418722961181}, {"url": "http://www.euroavtoprokat.ru/sitemap/car-rental.htm", "timestamp": 1418722945825}, {"url": "http://www.euroavtoprokat.ru/car-rental/germany.htm", "timestamp": 1418722937847}, {"url": "http://www.euroavtoprokat.ru/car-rental/germany.htm", "timestamp": 1418722923196}, {"url": "http://www.euroavtoprokat.ru/sitemap/car-rental.htm", "timestamp": 1418722909804}, {"url": "http://www.eavtoprokat.ru/prokat-avto/france", "timestamp": 1418646101953}, {"url": "http://www.wordparts.ru/numeral/", "timestamp": 1418592793587}, {"url": "http://rsdn.ru/forum/alg/3305190.flat", "timestamp": 1418591162814}, {"url": "http://www.euroavtoprokat.ru/car-rental/turkey/istanbul.htm", "timestamp": 1418571531780}, {"url": "http://citieslist.ru/", "timestamp": 1418488992092}, {"url": "http://www.euroavtoprokat.ru/car-rental/turkey/istanbul.htm", "timestamp": 1418480798674}, {"url": "http://rutv.ru/brand/show/episode/453757", "timestamp": 1418253037406}, {"url": "http://www.fodors.com/community/europe/best-car-rental-company-in-italy.cfm", "timestamp": 1418247198586}, {"url": "http://wheelsabroad.com/car-rental/united-kingdom/england/london?gclid=cjwkeaia-5-kbrdylpg5096r8masjabqedm4cmiichc-_-ewkbtsqyci5bu9ucwvjmxp4o0tficaarocljdw_wcb", "timestamp": 1418245144696}, {"url": "http://lestinet.com/site/stopagent.ru", "timestamp": 1418243376170}, {"url": "http://android-help.ru/q2a/16774/\u043a\u0430\u043a-\u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c-root-\u043f\u0440\u0430\u0432\u0430-\u043d\u0430-philips-w832-android-4-0-4", "timestamp": 1418169606439}, {"url": "http://club.dns-shop.ru/rabinovich/blog/\u044f-\u0432\u0441\u0435-\u0435\u0449\u0435-\u0434\u0435\u0440\u0436\u0443\u0441\u044c-\u043e\u0431\u0437\u043e\u0440-\u0441\u043c\u0430\u0440\u0442\u0444\u043e\u043d\u0430-philips-xenium-w832/", "timestamp": 1418169602505}, {"url": "http://www.supportforum.philips.com/ru/showthread.php?1529-philips-xenium-w832/page6", "timestamp": 1418167859617}, {"url": "http://www.supportforum.philips.com/ru/showthread.php?842-\u043d\u0435-\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442-gps-\u0432-\u0441\u043c\u0430\u0440\u0442\u0444\u043e\u043d\u0435-philips-xenium-w832", "timestamp": 1418166430112}, {"url": "http://rabota.ua/info/jobsearcher/post/umora.aspx", "timestamp": 1418114698621}, {"url": "http://www.enter.ru/product/appliances/myasorubka-philips-hr2728-2020103007131", "timestamp": 1418053557067}, {"url": "http://www.ferra.ru/ru/byt/news/2013/12/02/polaris-pmg-1805/", "timestamp": 1417866883735}, {"url": "http://www.ferra.ru/ru/byt/news/2013/10/12/bosch-mfw6-propower/", "timestamp": 1417862586856}, {"url": "http://www.linotype.com/1266/neuehelvetica-family.html", "timestamp": 1417856979616}, {"url": "http://www.linotype.com/1546/tradegothic-family.html?site=webfonts", "timestamp": 1417812010753}, {"url": "http://www.vandelaydesign.com/best-ecommerce-website-designs/", "timestamp": 1417807232287}, {"url": "http://www.awwwards.com/20-of-the-very-best-e-commerce-web-sites.html", "timestamp": 1417805189928}, {"url": "http://101.ru/?an=port_channel_mp3&channel=82", "timestamp": 1417711286305}, {"url": "http://www.just.ru/myasorubki/56658_elektromyasorybky_kenwood_mg_450/?from=yandex_msk&utm_source=yandex&utm_medium=cpc&utm_campaign=10817239_model_bytovaya-tehnika-melkaya_msk_p_api&utm_content=612422293_2792852770_\u043c\u044f\u0441\u043e\u0440\u0443\u0431\u043a\u0443 mg 450&position_type=premi", "timestamp": 1417701042306}, {"url": "http://101.ru/?an=port_channel_mp3&channel=5", "timestamp": 1417695760398}, {"url": "http://101.ru/?an=port_channel_mp3&channel=5", "timestamp": 1417689964129}, {"url": "http://101.ru/?an=port_channel_mp3&channel=17", "timestamp": 1417683034834}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417608945879}, {"url": "http://101.ru/?an=port_channel_mp3&channel=24", "timestamp": 1417605700777}, {"url": "http://101.ru/?an=port_channel_mp3&channel=24", "timestamp": 1417605639264}, {"url": "http://101.ru/?an=port_channel_mp3&channel=82", "timestamp": 1417605624817}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg470-meat-grinder-0wmg470008", "timestamp": 1417604804579}, {"url": "http://livedemo00.template-help.com/magento_48517/blackberry-bold-9000-phone.html", "timestamp": 1417604730951}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg470-meat-grinder-0wmg470008", "timestamp": 1417548651645}, {"url": "http://www.kenwoodworld.com/en-int/products/blenders/meat-grinders/mg474-meat-grinder", "timestamp": 1417548321763}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417548310507}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417548309162}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?feat=6405fda1-43cc-42cc-8860-1c2a492555c5&tabsegment=key-features", "timestamp": 1417548297576}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?tabsegment=key-features", "timestamp": 1417548284970}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417548264964}, {"url": "http://www.kenwoodworld.com/en-int/products/blenders/meat-grinders", "timestamp": 1417546314287}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg700-meat-grinder-0wmg700006", "timestamp": 1417545459520}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg700-meat-grinder-0wmg700006", "timestamp": 1417545200191}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/kmix-by-kenwood/kmix-kitchen-machines-/kmx51-kmix-kitchen-machine-0wkmx51002", "timestamp": 1417545116313}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/---mg517---0wmg517007", "timestamp": 1417544991760}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417544967371}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?feat=ac86d868-3ea4-4523-93e1-885bbf4222cd&tabsegment=key-features", "timestamp": 1417544772661}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?feat=3a288c22-e5f2-448e-a573-ccde95fd2341&tabsegment=key-features", "timestamp": 1417544765049}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?feat=ac86d868-3ea4-4523-93e1-885bbf4222cd&tabsegment=key-features", "timestamp": 1417544748628}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001?tabsegment=key-features", "timestamp": 1417544731238}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417544522237}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417544351791}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/-mg350-0w21910001", "timestamp": 1417544282950}, {"url": "http://www.kenwoodworld.com/ru-ru", "timestamp": 1417544269909}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg516-meat-grinder-and-roto-food-cutter-0wmg516006?tabsegment=specifications", "timestamp": 1417544204394}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg516-meat-grinder-and-roto-food-cutter-0wmg516006", "timestamp": 1417544190747}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg516-meat-grinder-and-roto-food-cutter-0wmg516006", "timestamp": 1417544045014}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg516-meat-grinder-and-roto-food-cutter-0wmg516006?tabsegment=specifications", "timestamp": 1417544035023}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg516-meat-grinder-and-roto-food-cutter-0wmg516006", "timestamp": 1417544015196}, {"url": "http://www.kenwoodworld.com/ru-ru", "timestamp": 1417544004579}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009?tabsegment=specifications", "timestamp": 1417543914820}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543814629}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543642699}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543628088}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543616074}, {"url": "http://www.kenwoodworld.com/uk/products/food-mixers/chef-major-attachments/potato-peeler-at444-awat444001", "timestamp": 1417543439173}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543352117}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543294005}, {"url": "http://www.kenwoodworld.com/uk/search-results", "timestamp": 1417543192107}, {"url": "http://www.kenwoodworld.com/uk", "timestamp": 1417543022466}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009?tabsegment=specifications", "timestamp": 1417542940415}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009?tabsegment=support", "timestamp": 1417542907491}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009?tabsegment=specifications", "timestamp": 1417542866623}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542858206}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542839578}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542795850}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542742883}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542725367}, {"url": "http://www.kenwoodworld.com/ru-ru/all-products/blenders-mixers-and-meat-grinders/meat-grinders-ru/mg510-meat-grinder-0wmg510009", "timestamp": 1417542659966}, {"url": "http://www.kenwoodworld.com/ru-ru", "timestamp": 1417542501523}, {"url": "http://101.ru/?an=port_channel_mp3&channel=24", "timestamp": 1417542435930}, {"url": "http://www.shop-script.ru/platform/", "timestamp": 1417473193974}, {"url": "http://101.ru/?an=port_channel_mp3&channel=34", "timestamp": 1417451297674}]}

Код постобработки url из json:
import re
import os, sys
import json
from urllib.parse import urlparse
from urllib.request import urlretrieve, unquote
for c in range(len(res)):
        a=urlparse(unquote(res['url'][c]))
        res['url'][c]=str(re.search("(?:www\.)?(.*)",a.netloc).group(1))

Было: http://news.yandex.ru/yandsearch?cl4url=chezasite.com/htc/htc-one-m9-delay-86327.html&lr=213&rpt=story
Стало:news.yandex.ru

Код постобработки времени 'timestamp' из json:
import datetime
from datetime import timedelta
mytime=datetime.datetime.fromtimestamp(int(res['timestamp'][1]/1000))
if  mytime.replace(minute=30) < mytime:
    mytime = mytime.replace(second=0, microsecond=0, minute=0) + timedelta(hours=1)
else:
    mytime=mytime.replace(second=0, microsecond=0, minute=0)

Было 1426666298001   Стало:2015-03-18 11:00:00

Как реализовать коды постобработки внутри кода десерилизацию json строк с размноживанием основной строки на которой json ? Обязательно препишу если что-то не понятно

A: Векторизированное решение:
In [22]: res['url'] = res['url'].str.extract(r'^\s*(?:https?://)([^/]*).*', expand=False)

In [23]: res['timestamp'] = pd.to_datetime(res['timestamp'], unit='ms')

Результат:
In [24]: res
Out[24]:
                  timestamp                   url                                   uid gender    age
0   2014-12-27 13:49:04.068         zebra-zoya.ru  d50192e5-c44e-4ae8-ae7a-7cfe67c8b777      F  18-24
1   2015-03-18 08:11:38.001        news.yandex.ru  d50192e5-c44e-4ae8-ae7a-7cfe67c8b777      F  18-24
2   2015-03-18 08:11:38.000        www.sotovik.ru  d50192e5-c44e-4ae8-ae7a-7cfe67c8b777      F  18-24
3   2015-03-18 06:55:22.001        news.yandex.ru  d50192e5-c44e-4ae8-ae7a-7cfe67c8b777      F  18-24
4   2015-03-18 06:55:22.000        www.sotovik.ru  d50192e5-c44e-4ae8-ae7a-7cfe67c8b777      F  18-24
5   2014-12-27 22:04:46.224        sweetrading.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
6   2014-12-27 22:04:44.437        sweetrading.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
7   2014-12-27 22:03:36.375        sweetrading.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
8   2014-12-27 22:03:24.934                101.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
9   2014-12-27 21:03:14.423        sweetrading.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
..                      ...                   ...                                   ...    ...    ...
97  2014-12-02 17:54:18.206  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
98  2014-12-02 17:53:59.578  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
99  2014-12-02 17:53:15.850  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
100 2014-12-02 17:52:22.883  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
101 2014-12-02 17:52:05.367  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
102 2014-12-02 17:50:59.966  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
103 2014-12-02 17:48:21.523  www.kenwoodworld.com  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
104 2014-12-02 17:47:15.930                101.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
105 2014-12-01 22:33:13.974    www.shop-script.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34
106 2014-12-01 16:28:17.674                101.ru  d502331d-621e-4721-ada2-5d30b2c3801f      M  25-34

[107 rows x 5 columns]

Замер скорости для 5.350.000 строк (около 9 секунд на моем железе):
In [38]: df = pd.concat([res] * 50000, ignore_index=True)

In [39]: df.shape
Out[39]: (5350000, 5)

In [40]: %timeit df['url'].str.extract(r'^\s*(?:https?://)([^/]*).*', expand=False)
8.81 s ± 146 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [41]: %timeit pd.to_datetime(df['timestamp'], unit='ms')
144 ms ± 1.88 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

PS использование urlparse более идиоматично и, наверняка, покрывает гораздо больше "хитрых" вариантов URL, но его трудно будет ускорить так, чтобы было сравнимо с векторизированными Pandas методами. Поэтому предлагаю использовать регулярные выражения (RegEx) и настраивать/исправлять их для более сложных случаев.


text:
Q: Tic-Tac-Toe game glitch Can someone... anyone, help me figure out why when the 'fourCorners' function is activated, it fills in 2 boxes instead of one. Any assistance would be greatly appreciated.
Here's a link to my code: https://codepen.io/DRick504/pen/bRGgRJ
  function fourCorners() {

    var compArr = [3,0,2,1]

    var compNextMove = compArr[num]

     $('#players').text(num)

    if (num===4) {

      return false;

    } else if (compNextMove===0 && $('#one').is(':empty')) {

      $('#one').text(opp)
      $('#one').slideDown(800)

    } else if (compNextMove===1 && $('#three').is(':empty')) {

      $('#three').text(opp)
      $('#three').slideDown(800)

    } else if (compNextMove===2 && $('#seven').is(':empty')) {

      $('#seven').text(opp)
      $('#seven').slideDown(800)

    } else if (compNextMove===3 && $('#nine').is(':empty')) {

      $('#nine').text(opp)
      $('#nine').slideDown(800)

    }

  num=num+1

}


text:
Q: not getting errorElementClass Scenerio:I have added validation to observable-array , eg is about a observable field in observable array
      eg:
this.field = ko.observable().extend({
           required: { params: true, message: "field is required." },
           digit: { params: true, message: "field must be number." },
           min: { params: 0, message: "field must be between 0 to 9999." },
           max: { params: 9999, message: "field must be between 0 to 9999." }
       });

Also initialize the validations:
 ko.validation.init({
           registerExtenders: true,
           messagesOnModified: false,
           insertMessages: false,
           decorateElement: true,
           errorElementClass: 'input-validation-error',
           errorMessageClass: 'field-validation-error'
       });

But not getting errorElementClass: 'input-validation-error',for other validations except required validations Note:It is taking class=valid for other validation rule violation,but error message is displayed '

A: I have setup similar things in  jsFiddle:
ko.validation.init({
    registerExtenders: true,
    messagesOnModified: false,
    insertMessages: true,
    decorateElement: true,
    errorElementClass: 'input-validation-error',
    errorMessageClass: 'field-validation-error'
});

function Money() {
    this.Amount = ko.observable().extend({
        required: {
            params: true,
            message: "field is required."
        },
        digit: {
            params: true,
            message: "field must be number."
        },
        min: {
            params: 0,
            message: "field must be between 0 to 9999."
        },
        max: {
            params: 9999,
            message: "field must be between 0 to 9999."
        }
    });

    this.onSubmit = function (e) {
        return this.Amount.isValid();
    }
}

ko.applyBindings(new Money());

try this in FF
I would suggest checking following steps

*

*reference to script files in following order

*

*jquery

*knockout

*knockout-validation

*make sure ko.validations.init call at the very top in domReady

*Version mis match is not there. latest ko.validation seems to working with knockout 3.0


text:
Q: How to Convert a negative milliseconds into correct timeZone in Java I am working with Java dates , I am unable to get out of this issue.
In my file the Time value is saved like (HH:MM:SS)
00:00:08
below is the code and output ..
  String timeinsec = "00:00:08";
  DateFormat df = new SimpleDateFormat("hh:mm:ss");
  Date time =  df.parse(timeinsec);

What happened is when I assigned the value and time variables. time.fastTime variable show
"-17992000"
when I convert back this value to HH:MM:SS it shows me.
"-4:-59:-51"
Anybody can help to fix TimeZone issue.
My current time zone is GMT+5

A: Try this;
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60);

A: here is the convert back code:
Date new_time = Time_array.get(0).time;  //-17992000 stored in "fastTime" variable
long diff = ((long)new_time.getTime());  //TimeUnit.MILLISECONDS

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
String hms = String.format("%d:%02d:%02d", diffHours, diffMinutes, diffSeconds);

in dubug: the value of hms = -4:-59:-51

A: I was trying various ways so finally i wrote this code and my requirement is fulfilled.
Calendar cal = Calendar.getInstance();
String timeinsec = "00:00:08";
DateFormat df = new SimpleDateFormat("hh:mm:ss");
Date time =  df.parse(timeinsec);
cal.setTime(time);
hms = String.format("%d:%02d:%02d", cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));

The output was : 00:00:08

A: hh is 1~12. You should use HH (0~23)
String timeinsec = "00:00:08";
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date time =  df.parse(timeinsec);


text:
Q: How do I find out what is causing Azure B2C 500 Internal Server Error? I am trying to add orchestration steps to my Azure B2C IEF user journey however, when I make changes I often times get error: "500 - Internal Server Error"
I have tried using Application Insights, but that does not tell you anything related to error 500.
Here is my Technical Profile
    <TechnicalProfile Id="Step1">
      <DisplayName>Step 1</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Email" Required="true"/>
        <OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
        <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
      </OutputClaims>
    </TechnicalProfile>

And here is my User Journey Step
    <OrchestrationStep Order="3" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
          <Value>objectId</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="SignUpWithLogonEmailExchange" TechnicalProfileReferenceId="Step1" />
      </ClaimsExchanges>
    </OrchestrationStep>

Is there a way to find out what is causing these 500 - internal server errors?

A: ContentDefinition: The SelfAssertedAttributeProvider technical profile must have a ContentDefinition specified in the Metadata section. That is missing in your technical profile.
OutputClaims:
There is no ValidationTechnicalProfile in the technical profile Step1. That could potentially be an issue. Since these are OutputClaims, the policy must specify a way to create a value for each of those (even if at run time it may not actually get created). So an OutputClaim must have one of the three:

*

*Specify a DefaultValue, which guarantees that it will have that value after the TechnicalProfile has been invoked.

*Specify a UserInputType in the ClaimType under the ClaimsSchema section, which indicates that there is a way to retrieve that value from the user.

*Specify it as an OutputClaim of a ValidationTechnicalProfile, which will allow another provider to retrieve such a value (e.g. from AD Graph, or a Rest API).

CryptographicKeys: SelfAssertedAttributeProvider TechnicalProfile also needs a CryptographicKeys section which specifies a key used by the provider.
I would recommend copying a technical profile from the Starter Packs Github and modify those since those will contain all the required elements.
(The fact that the service is returning 500 is a bug, and needs to be fixed.)


text:
Q: Is python's builtin sort parallelized? Will python automatically parallelize sorting across all cores?
Sorting a list of objects based on an integer property, which sorts a list of size 2M in ~1.7s. My machine has 16 logical cores and 4 GPUs which I would like to leverage to speedup the sort. I found a couple parallel merge sort implementations online but none seemed popular which is surprising given the parallel hardware available today. Would these implementations be better on machines with 8-16 cores?

A: EDIT: This method doesn't really perform very well due to the overhead of copying memory around (among other reasons) and the slowness of the built-in heapq.merge operation. I suggest just using numpy.ndarray.sort() if possible since it's surprisingly quick.

A simple method for parallelizing to n threads is to split your collection into n equal pieces, and then feed each chunk into a separate thread. Once the threads are done, collate their sorted results into one list via a stable merge operation.
from heapq import merge
from multiprocessing.pool import Pool

def sort_parallel(xs, n_workers):
    pool = Pool(n_workers)
    pos = [i * len(xs) // n_workers for i in range(n_workers + 1)]
    xss = [xs[i:j] for i, j in zip(pos[:-1], pos[1:])]
    pool.map(sort_inplace, xss)
    return list(merge(*xss))

def sort_inplace(xs):
    xs.sort()

A:
Will python automatically parallelize sorting across all cores?

There is nothing in the Python Language Specification (or more precisely, the Python Standard Library Specification) that would prevent an implementor from parallelizing either list.sort() or sorted(). There is, however, also nothing in the Python Language Specification or the Python Standard Library Specification that would force an implementor to parallelize either list.sort() or sorted().
Therefore, it is completely up to each implementation whether they implement them serial, parallel, or print out the list, fax it to Malaysia, and have it hand-sorted in a sweat shop. Also, an implementation is free to change the implementation strategy at any time without warning, as long as it does not violate the invariants guaranteed by the Library Specification. (Which is basically only that the result must be sorted and that the sort must be stable.)
Or, to answer the question succinctly:

Will python automatically parallelize sorting across all cores?

You can't know.


text:
Q: Python Blackjack Run module IDLE error? I try to run the following module written for a blackjack 21 game in Python but get an error saying:
Unindent does not match any outer indentation level.

Questions

*

*Please help resolve the error.

*Also is there a stable option to run modules and get them checked with a python checker which I know there is but an easy to use one without adding code in python , just running it to check where the code got broken?
example
if the screenshot is unclear:
koloda = [6,7,8,9,10,2,3,4,11] * 4

import random
random.shuffle(koloda)

print(' Lets play blackjack, shall we? ')
count = 0

while True:
    choice = input(' Will you pick another card? y/n\n ')
    if choice == ' y ':
        current = koloda.pop()
        print(' You got a higher card %d ' %current)
        count += current
    if count > 21:
               print(' Sorry, you lost ')
           break
         elif count == 21:
              print(' Congrats, you got 21! ')
               break
     else:
           print(' You have %d points. ' %count)
     elif choice -- 'n':

           print(' You have %d points and you ended this game. ' %count)
           break

   print('See you again!')

Thanks in advance

A: Your indentations are inconsistent. In python, you can choose how you indent blocks (e.g. tabs, 4 spaces, 3 spaces...), but you should always stick to your initial choice. Otherwise you'll get indentation errors.
Regarding your other question, there are many IDEs that will report syntax errors (such as the ones in your code) while writing. I like Pycharm, but you can choose anything you like. PyCharm also has an option to convert indentation between spaces and tabs, which can help you fix your code.


text:
Q: How to render a doctype with Python's xml.dom.minidom? I tried:
document.doctype = xml.dom.minidom.DocumentType('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"')

There is no doctype in the output. How to fix without inserting it by hand?

A: You shouldn't instantiate classes from minidom directly. It's not a supported part of the API, the ownerDocuments won't tie up and you can get some strange misbehaviours. Instead use the proper DOM Level 2 Core methods:
>>> imp= minidom.getDOMImplementation('')
>>> dt= imp.createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd')

('DTD/xhtml1-strict.dtd' is a commonly-used but wrong SystemId. That relative URL would only be valid inside the xhtml1 folder at w3.org.)
Now you've got a DocumentType node, you can add it to a document. According to the standard, the only guaranteed way of doing this is at document creation time:
>>> doc= imp.createDocument('http://www.w3.org/1999/xhtml', 'html', dt)
>>> print doc.toxml()
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

If you want to change the doctype of an existing document, that's more trouble. The DOM standard doesn't require that DocumentType nodes with no ownerDocument be insertable into a document. However some DOMs allow it, eg. pxdom. minidom kind of allows it:
>>> doc= minidom.parseString('')
>>> dt= minidom.getDOMImplementation('').createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd')
>>> doc.insertBefore(dt, doc.documentElement)
<xml.dom.minidom.DocumentType instance>
>>> print doc.toxml()
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

but with bugs:
>>> doc.doctype
# None
>>> dt.ownerDocument
# None

which may or may not matter to you.
Technically, the only reliable way per the standard to set a doctype on an existing document is to create a new document and import the whole of the old document into it!
def setDoctype(document, doctype):
    imp= document.implementation
    newdocument= imp.createDocument(doctype.namespaceURI, doctype.name, doctype)
    newdocument.xmlVersion= document.xmlVersion
    refel= newdocument.documentElement
    for child in document.childNodes:
        if child.nodeType==child.ELEMENT_NODE:
            newdocument.replaceChild(
                newdocument.importNode(child, True), newdocument.documentElement
            )
            refel= None
        elif child.nodeType!=child.DOCUMENT_TYPE_NODE:
            newdocument.insertBefore(newdocument.importNode(child, True), refel)
    return newdocument


text: Q: Javascript random text fade out / in I have some text that randomly changes every 3 seconds, it is working like a charm but i want to make whenever it changes there is a fade out, fade in transition. This is my script/


text:
Q: how to make timer inside timer in batch I want to make timer that makes cmd every 2 sec for 60 sec
timeout/t 60
timeout /t 2
start everlast.bat
timeout /t 2
start everlast.bat

I dont even now how to do it

A: You should try to explain better what you intend. I simply guess you might try to do something like this.
@Echo off
Echo Start %time%
For /l %%A in (1,1,30) Do Start everlast.bat & Timeout /t 2
Echo End   %time%

Edit Added time output to measure elapsed time

A: If you really want to check the time you would need to convert the current time to seconds to do the calculations.
@echo off

for /F "tokens=1-4 delims=:.," %%a in ("%time%") do set /A "current=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)"

set /A expire=current + 60

:label
timeout /T 2 >nul
start "" "everlast.bat"
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do set /A "current=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)"
IF %current% lss %expire% GOTO label

A: echo off
set /a time=60
:timer
ping localhost -n 2 >nul
set /a time=%time%-1
ping localhost -n 2 >nul
set /a time=%time%-1
start everlast.bat
if %time% LEQ 0 goto EOF
goto timer

:EOF
exit

that should work if i'm correct


text:
Q: Deployment "angular-deployment" exceeded its progress deadline I am trying to deploy an angular app into  k8, but i am getting available 0 when i am running the command
kubectl get deployments

This is the result i am getting
NAME                 READY   UP-TO-DATE   AVAILABLE   AGE
angular-deployment   0/5     3            0           24h

This is deployment yaml file I am using
apiVersion: apps/v1 # Kubernetes API version
kind: Deployment  # Kubernetes resource kind we are creating
metadata:
 name: angular-deployment
spec:
 selector:
   matchLabels:
    app: angular
 replicas: 5 # Number of replicas that will be created for this deployment
 template:
   metadata:
    labels:
      app: angular
   spec:
     containers:
      - name: angular
        image: ng-docker-k8s:1.0 # Image that will be used to containers in the cluster
        ports:
        - containerPort: 80 # The port that the container is running on in the cluster
        imagePullPolicy: Always
        ---

kind: Service  # Kubernetes API version
apiVersion: v1 # Kubernetes resource kind we are creating
metadata:
  name: angular-service
spec:
 selector:
   app: angular
 ports:
  - protocol: TCP
    port: 80   # The port that the service is running on in the cluster
    targetPort: 80   # The port exposed by the service
    nodePort: 31000
  type: NodePort     # type of the service.

and also i have tried running the command
kubectl rollout status deployment/angular-deployment
Waiting for deployment "angular-deployment" rollout to finish: 3 out of 5 new replicas
have been updated...
error: deployment "angular-deployment" exceeded its progress deadline

I am  new to kubernates/k8  please help


text:
Q: How to fill multidimensional array with loop I have an array :
$days = array(
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
);

And I have a query witch is getting me the days from the database (day_name,ID);
For what I need your help: I want to  fill the array with the loop below and make it associative. Example result :
thursday => array(
    'ID' => 1,
    'name' => thursday
),
friday => array(
    'ID' => 1,
    'name' => thursday
),
....eg

My code now:
$query='Query days from database';

foreach($query as $res)
{
    foreach($days as $day)
    {
        if($res == $day)
        {
            // now there I want to put informations
        }
    }
}

A: There's no need for nested loops. Initialize the array as an associative array. Then use the name column from the database query to index into the result and assign to that element.
$days = ['sunday' => [], 'monday' => [], ...];
foreach ($query as $row) {
    $days[$row['name']] = $row;
}

A: In case you can't initialize arrays (Like suggested in @Barmar Answer), you need to look for the array key to override it with an array. Like here :
$days=array('Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
       );
    print_r($days);

//Example
$res[0]['name']="Sunday";
$res[0]['ID']="7";
$res[1]['name']="Monday";
$res[1]['ID']="1";

foreach($res as $k => $v){
$daykey = array_search($res[$k]['name'], $days);
if ($daykey !== false) {
    $days[$daykey]=array($res[$k]['name']=>array('ID'=>$res[$k]['ID'],'name'=>$res[$k]['name']));
} else {
    //do nothing... or whatever
}
}
print_r($days);


text:
Q: Why import bootstrap css with webpack instead of just linking to it? I have been learning webpack for use in a Single Page App.
One of the examples is using:
 import 'bootstrap/dist/css/bootstrap.min.css';

along with a loader like this:
{
   test: /\.css$/,
   use: ['style-loader', 'css-loader']
}

This works to inject bootstrap css into main.js and it then gets injected into the dom at runtime.
Ok fine.  But why?  I don't see a benefit to this over just have a normal link.
The other side of the code is that this is now increasing the size of the bundle (my app bundle is already over 5 megs) is just going to increase the startup time vs using a CDN.
Am I missing anything?
Update
I think I found the answer to this: The next step is to extract the imported css to a css file with MiniCssExtractPlugin like explained here

A: It will not make any difference when you have one dependency. But if you have a bunch of third party libraries , you can bundle and minify in to one. It will give you advantage when your application gone in to production.
And also other benefits would be converting .scss in to css
Sample web pack configuration
module.exports = {
    mode: 'development',
    entry: {
        'main.app.bundle': ['main.ts', "./somestyle.css"]
    },
    optimization: {
        splitChunks: {

               cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        }
    },
    output: {
        publicPath: '/dist/',
        filename: '[id].js',
        chunkFilename: "[name].js",
        path: path.resolve(__dirname, 'dist'),

    },
    module: {
        rules: [{
                test: /\.(sa|sc|c)ss$/,
                use: [
                    'exports-loader?module.exports.toString()',
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    'css-loader',
                    'sass-loader',
                ]
            },

            {
                // This plugin will allow us to use html templates when we get to the angularJS app
                test: /\.html$/,
                exclude: /node_modules/,
                loader: 'html-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
            }
        ]
    },
    node: {
        fs: 'empty'
    },
    resolve: {
        modules: [
            __dirname,
            'node_modules',
        ],
        extensions: [".ts", ".tsx", ".js"]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HashOutput({
            validateOutput: false,
        }),
        new MiniCssExtractPlugin({
            filename: 'application.bundle.css',
            chunkFilename: '[name].css'
        })
    ],
    devtool: 'source-map',
    externals: [],
    devServer: {
        historyApiFallback: true
    }
};


text:
Q: tikz: nodes overlapping with edges on graph I'm trying to reproduce a graph from a paper using Tikz, the graph that I'm trying to reproduce is the following:

But without the horizontal curved line and brackets on the left subtree. So far, this is what I get:
\documentclass[a4paper,12pt]{article}
\usepackage{tikz}

\tikzset{
    treenode/.style = {align=center, inner sep=0pt, text centered,
        font=\sffamily\Large\bfseries, text width=5cm},
    burned/.style = {treenode, circle, white, draw=red, fill=red, text width=1.5em, very thick},
    saved/.style = {treenode, circle, white, draw=green, fill=green, text width=1.5em, very thick},
    untouch/.style = {treenode, circle, white, draw=gray, fill=gray, text width=1.5em, very thick}
}

\begin{document}

\begin{tikzpicture}[auto, node distance=2cm, thick]
% nodes
\node[burned](1){F};
    \node[saved](2) [below left of=1] {S};
    \node[untouch](3) [below left of=2] {};
    \node[untouch](4) [below right of=2] {};
    \node[burned](5) [below of=1] {B};
    \node[burned](6) [below right of=1] {B};
    \node[saved](7) [below of=5] {S};
    \node[burned](8) [below of=6] {B};
    \node[untouch](9) [below of=7] {};
    \node[saved](10) [below of=8] {S};
    \node[untouch](11) [below of=9] {};
    \node[untouch](12) [below of=11] {};
    \node[untouch](13) [below of=10] {};
    \node[untouch](14) [below of=13] {};

%edges
\path
    (1) edge node [right] {} (2)
        edge node [below] {} (5)
        edge node [left] {} (6)
    (2) edge node [right] {} (3)
        edge node [right] {} (4)
    (5) edge node [below] {} (7)
        edge node [left] {} (8)
    (7) edge node [below] {} (9)
    (9) edge node [below] {} (11)
    (11) edge node [below] {} (12)
    (6) edge node [right] {} (7)
        edge node [below] {} (8)
    (8) edge node [below] {} (10)
    (10) edge node [below] {} (13)
    (13) edge node [below] {} (14);
\end{tikzpicture}

\end{document}

Which produces the following graph:

So, basically I have three questions:

*

*Is there any way to avoid the overlapping between the edges and nodes?

*Also, there is any way to get the nodes from the same level to be aligned? (Like in the graph of the paper)

*There is another LaTex package or tikz library with a more intuitive syntax to draw graphs (i.e. graphs with edges/nodes)? Maybe something similar do Graphviz dot syntax.

A: Probably someone will suggest using forest for this kind of graph. It will be a good suggestion. But while waiting for it, you can start using  positioning library and its =of (instead of of=)  syntax.
\documentclass[a4paper,12pt]{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\tikzset{
    treenode/.style = {align=center, inner sep=0pt, text centered,
        font=\sffamily\Large\bfseries, text width=5cm},
    burned/.style = {treenode, circle, white, draw=red, fill=red, text width=1.5em, very thick,sibling distance=30mm},
    saved/.style = {treenode, circle, white, draw=green, fill=green, text width=1.5em, very thick,sibling distance=15mm},
    untouch/.style = {treenode, circle, white, draw=gray, fill=gray, text width=1.5em, very thick,sibling distance=7.5mm}
}

\begin{document}

\begin{tikzpicture}[auto, thick, on grid, ]
% nodes
\node[burned](1){F};
    \node[saved](2) [below left = 1 and 2 of 1] {S};
    \node[untouch](3) [below left = 1 and 1 of 2] {};
    \node[untouch](4) [below right = 1 and 1 of 2] {};
    \node[burned](5) [below = 1 of 1] {B};
    \node[burned](6) [below right = 1 and 2 of 1] {B};
    \node[saved](7) [below = of 5] {S};
    \node[burned](8) [below = of 6] {B};
    \node[untouch](9) [below = of 7] {};
    \node[saved](10) [below = of 8] {S};
    \node[untouch](11) [below = of 9] {};
    \node[untouch](12) [below =of 11] {};
    \node[untouch](13) [below = of 10] {};
    \node[untouch](14) [below = of 13] {};

%edges
\path
    (1) edge node [right] {} (2)
        edge node [below] {} (5)
        edge node [left] {} (6)
    (2) edge node [right] {} (3)
        edge node [right] {} (4)
    (5) edge node [below] {} (7)
        edge node [left] {} (8)
    (7) edge node [below] {} (9)
    (9) edge node [below] {} (11)
    (11) edge node [below] {} (12)
    (6) edge node [right] {} (7)
        edge node [below] {} (8)
    (8) edge node [below] {} (10)
    (10) edge node [below] {} (13)
    (13) edge node [below] {} (14);
\end{tikzpicture}

\end{document}

Update: forest version.
\documentclass[a4paper,12pt]{article}
\usepackage{forest}

\tikzset{
    treenode/.style = {align=center, inner sep=0pt, text centered,
        font=\sffamily\Large\bfseries, text width=5cm},
    burned/.style = {treenode, circle, white, draw=red, fill=red, text width=1.5em, very thick,sibling distance=30mm},
    saved/.style = {treenode, circle, white, draw=green, fill=green, text width=1.5em, very thick,sibling distance=15mm},
    untouch/.style = {treenode, circle, white, draw=gray, fill=gray, text width=1.5em, very thick,sibling distance=7.5mm}
}

\begin{document}

\begin{forest}
[F,burned
    [S, saved, , for descendants={untouch}
        [][]]
    [B, burned, name=B1
        [S, saved, name=S1, for descendants={untouch} [[[]]]]]
    [B, burned, name=B2
        [B, burned, name=B3 [S, saved, , for descendants={untouch} [[]]]]]]
    \draw (B1)--(B3) (B2)--(S1);
\end{forest}
\end{document}


text:
Q: "ps -ef | grep java" using java program I'm attempting to execute ps -ef | grep java through java program. Here is my code-
//  String sudoScript = "sh -c \"ps -ef | grep java\"";
    String sudoScript = "ps -ef | grep java";
    try {
        System.out.println("command=" + sudoScript);
        Process p1 = Runtime.getRuntime().exec(sudoScript);
        System.out.println("exit code: "+p1.waitFor());
        FileInputStream fis1 = (FileInputStream) p1.getErrorStream();
        int content1;
        while ((content1 = fis1.read()) != -1) {
            // convert to char and display it
            System.out.print((char) content1);
        }
        BufferedReader stdInput1 = new BufferedReader(
                new InputStreamReader(p1.getInputStream()));
        while ((sudoScript = stdInput1.readLine()) != null) {
            System.out.println(sudoScript);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

This is the output I got when I executed the command as ps -ef | grep java-
command=ps -ef | grep java
exit code: 1
ERROR: Garbage option.
********* simple selection *********  ********* selection by list *********
-A all processes                      -C by command name
-N negate selection                   -G by real group ID (supports names)
-a all w/ tty except session leaders  -U by real user ID (supports names)
-d all except session leaders         -g by session OR by effective group name
-e all processes                      -p by process ID
T  all processes on this terminal     -s processes in the sessions given
a  all w/ tty, including other users  -t by tty
g  OBSOLETE -- DO NOT USE             -u by effective user ID (supports names)
r  only running processes             U  processes for specified users
x  processes w/o controlling ttys     t  by tty
*********** output format **********  *********** long options ***********
-o,o user-defined  -f full            --Group --User --pid --cols --ppid
-j,j job control   s  signal          --group --user --sid --rows --info
-O,O preloaded -o  v  virtual memory  --cumulative --format --deselect
-l,l long          u  user-oriented   --sort --tty --forest --version
-F   extra full    X  registers       --heading --no-heading --context
                    ********* misc options *********
-V,V  show version      L  list format codes  f  ASCII art forest
-m,m,-L,-T,H  threads   S  children in sum    -y change -l format
-M,Z  security data     c  true command name  -c scheduling class
-w,w  wide output       n  numeric WCHAN,UID  -H process hierarchy

I tried using sh -c "ps -ef | grep java". But not luck. Got the following output-
command=sh -c "ps -ef | grep java"
exit code: 1
-ef: -c: line 0: unexpected EOF while looking for matching `"'
-ef: -c: line 1: syntax error: unexpected end of file

How can I overcome this?

A: Found it! Worked for me.
try {
    Process p1 = Runtime.getRuntime().exec(new String[] { "ps", "-ef" });
    InputStream input = p1.getInputStream();
    Process p2 = Runtime.getRuntime().exec(new String[] { "grep", "java"});
    OutputStream output = p2.getOutputStream();
    IOUtils.copy(input, output);
    output.close(); // signals grep to finish
    List<String> result = IOUtils.readLines(p2.getInputStream());
    System.out.println(result);
} catch (Exception e) {
    e.printStackTrace();
}


text:
Q: flot chart not drawing from ajax data I am trying to draw a flot chart using some Ajax data which is as follows when I console.log it :
[{ label:"series1",
          data : [[1459555200000,200],[1459987200000,440]],last:true}]

but when I use it as data in flot chart, the chart is blank , whereas if I hardcode it it runs great.
My code is:
$.get('chartgadmin.php',
    function (d) {
    console.log(d);
        var data = [d];
        var labelColor = chart.css('color');
        var options = {
            colors: chart.data('color').split(','),
            series: {
                shadowSize: 0,
                lines: {
                    show: true,
                    lineWidth: false,
                    fill: true
                },
                curvedLines: {
                    apply: true,
                    active: true,
                    monotonicFit: false
               }
            },
            legend: {
                container: $('#flot-visitors-legend')
            },
            xaxis: {
                mode: "time",
                timeformat: "%d %b",
                font: {color: labelColor}
            },
            yaxis: {
                font: {color: labelColor}
            },
            grid: {
                borderWidth: 0,
                color: labelColor,
                hoverable: true
            }
        };
        chart.width('100%');
        // Create chart
        var plot = $.plot(chart, data, options);
});

Any help will be appreciated.
Thanks

A: It seems you are not parsing your argument  " d " in chart readable format,so whenever you are passing hardcode data it works fine,but the object which you are passing directly will get by the chart datasource,so you have to use,
JSON.parse(d);


text:
Q: directoryChooser.showDialog in javaFX app is freezing application after dierctory selection DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory = directoryChooser.showDialog(vbox_container.getScene().getWindow());
                                if (selectedDirectory == null) {
                                    Logging.log(getClass(), LogType.INFO, "USER NOT SELECT OF DOWNLOAD DIRECTORY");
                                } else {
                                    new UpdateDownload(version, selectedDirectory) {
                                        @Override
                                        public void onPreExecute() {
                                            Label label = new Label("Downloading...");
                                            label.getStyleClass().addAll("text-color-white");
                                            vbox_container.getChildren().add(label);
                                        }
                                    }.execute();
                                }

After confirm of location in  DirectoryChooser  application is freezing for about 5 sec, than everything working fine... how to avoid described 5 secs freeze?


text:
Q: Find all functions that are analytic on the closed disk and that satisfy I got these questions incorrect on an old exam because I wasn't really sure where to go after applying Liouville.

*

*Find all functions that are analytic on a closed disk of radius 4 centered at the origin and that satisfy $f(z) = 8$ for all $z$ on the circle $|z| = 4$.

*Find all entire functions $f$ that satisfy the condition $|f(z)| ≤ \sqrt{|z|}$ for all $z \in \mathbb{C}$.
I know I'm supposed to show that the function is bounded and entire, but am not really sure where to go from there. Thanks in advance for your help!

A: Hints: (1) What do you know about an analytic function that is constant on a set of points with a limit point?
(2) Look at the Cauchy Integral Formula, specifically at the so-called Cauchy estimates. What can you conclude about $f^{(n)}(0)$ for all $n$?

A: (1) Using maximum principle for the real part of $f$, which is harmonic function, helps.
 (2) by Picard's theorem an entire function that misses three points in its range is constant.


text:
Q: Check if any of the selected cells is ReadOnly In a WPf datagrid I have a grid that has both editable and read-only cells. On selection of cells, if at least one cell is editable (not read-only) I have to enable Cut and Paste icons from the toolbar.
I have bound the IsEnabled property of Cut/Paste icons to a property CanPerformCutPaste.
This is the code that is currently working.
private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
   CanPerformCutPaste = dataGrid.SelectedCells.Any(c => !GetDataGridCell(c, dataGrid).IsReadOnly);
}

public static DataGridCell GetDataGridCell(DataGridCellInfo cellInfo, DataGrid grid)
{
       if (cellInfo == null || grid == null)
          return null;

       grid.ScrollIntoView(cellInfo.Item as DataRowView, cellInfo.Column);
       var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
       if (cellContent != null)
          return (DataGridCell)cellContent.Parent;

       return null;
}

Is there a better way to achieve this functionality? I don't want this to result in a performance issue for large number of cells.
Edit:
The columns are never set to read-only. Only some cells based on a condition are read-only. Therefore the column property cannot be checked.

A: You most likely want to check the last selected Cell, instead of checking all the selected cells each time, and besides checking the column property of the selected cell is enough, here a simple example:
 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Button Content="Copy/Past" Grid.Row="0" IsEnabled="{Binding CanPerformCutPaste}"></Button>
    <DataGrid  ItemsSource="{Binding Items}" x:Name="Dg" Grid.Row="1" AutoGenerateColumns="False" SelectionUnit="Cell" SelectedCellsChanged="Dg_OnSelectedCellsChanged">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
            <DataGridTextColumn Header="Location" Binding="{Binding Location}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

and the SelectedCellsChanged handler:
   private void Dg_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        if (Dg.SelectedCells.Any())
        CanPerformCutPaste = Dg.SelectedCells.Last().Column.IsReadOnly;
    }

Ps: I am sure you know that the vm should implements the INotifyPropertyChanged Interface
private bool _canPerformCutPaste  ;
    public bool CanPerformCutPaste
    {
        get
        {
            return _canPerformCutPaste;
        }

        set
        {
            if (_canPerformCutPaste == value)
            {
                return;
            }

            _canPerformCutPaste = value;
            OnPropertyChanged();
        }
    }


text:
Q: Boost asio read from stdin asynchronously I want to read from standard input (in terms of c++, std::cin) with boost asio function async_read(). The following code does not compile and gives me a very long error message due to instantiation error. Can someone answer, how do I read from stdin asynchronously using this function?
char buf[64];

boost::asio::async_read(std::cin, boost::asio::buffer(buf),
                          [](const boost::system::error_code &ec, std::size_t size){});

Edit: I know there is a similar question already asked here Using boost::asio::async_read with stdin?, however it is not clear to me in which way the marked answer relates to the question

A: You have to use posix::stream_descriptor
For example:
using namespace boost::asio;
io_context ioc;
posix::stream_descriptor input_stream(ioc, STDIN_FILENO);
// assume that you already defined your read_handler ...
async_read(input_stream, buffer(buf), read_handler);
ioc.run();

Note that you shouldn't mix the above code with std::cin
For more information please see here.


text:
Q: Show a Function is Strictly Convex I wish to show the function $f: \mathbb{R}^N \to \mathbb{R}$ such that $f(x) = (1 + |x|^2)^{\frac{1}{2}}$ is strictly convex. I am aware of the fact that $|x|^2$ is strictly convex and thus the shift $1 + |x|^2$ is strictly convex. However, I do not think the composition of a strictly convex function with $x^{\frac{1}{2}}$ is necessarily strictly convex. I also tried to show the Hessian matrix is positive definite, but the computation is intractable in $N$-dimension. Any suggestions?

A: $$df_x(h)=\frac{x\cdot h}{\sqrt{1+|x|^2}}$$
$$d^2f_x(h,k)=\frac{h\cdot k}{\sqrt{1+|x|^2}}-\frac{(x\cdot h)(x\cdot k)}{(1+|x|^2)^{3/2}}$$
$$(1+|x|^2)^{3/2}d^2f_x(h,h)=|h|^2(1+|x|^2)-(x\cdot h)^2\ge|h|^2$$
(by Cauchy-Schwarz inequality) hence $d^2f_x$ is positive definite.

A: I have to restrict the answer (thanks to @Anne Bauval) to the so called strictly convex norms, which by definition satisfy
$$\left \|ax+(1-a)y)\right\|<a\|x|+(1-a)\|y\|,\quad x\neq y,\ \|x\|=\|y\|\neq 0,\ 0<a<1$$
For example the euclidean norm has that property, as well
as (see)$$\|x\|_p=\left (\sum_{n=1}^N|x_n|^p\right )^{1/p},\ 1<p<\infty $$
For such norms we do not need to calculate the partial derivatives and  the $N$ dimensional Hessian, which can be unpleasent for some norms.
Assume the norm $g(x)=\|x|$ is strictly convex.  The function $h(t)=(1+t^2)^{1/2}$ is strictly increasing for $t\ge 0$ and  strictly convex as $$h''(t) =(1+t^2)^{-3/2}>0$$  Their composition $h(g(x))$ is thus strictly convex (verification at the end). Hence $f(x)$ is strictly convex because $$f(x)=(1+\|x\|^2)^{1/2}=h(g(x))$$
Verification
Consider nontrivial convex linear combination
$a,b>0,\ a+b=1$ and $x\neq y.$

*

*$\|x\|\neq \|y\|.$
By the triangle inequality and homogeneity of the norm we have
$$g(ax+by) \leq ag(x)+bg(y)$$  and $g(x)\neq g(y).$ Therefore
$$h(g(ax+by))\le h(ag(x)+bg(y))\\ <ah(g(x))+bh(g(y))$$

*$\|x\|=\|y\|$
Due to the strict convexity of the norm we have
$$g(ax+by)<ag(x)+bg(y)$$ and
$$h(g(ax+by))<h(ag(x)+bg(y))\le ah(g(x))+bh(g(x))$$

A: Let $x, x_0 \in \mathbb R^n$.  Then by Cauchy-Schwarz on the two vectors $(1, x)$ and $(1, x_0)$ $$1 + \langle x, x_0 \rangle \leq (1+ \lVert x \rVert^2)^{\frac12} (1+ \lVert x_0 \rVert^2)^{\frac12}$$ with equality if and only if $x=x_0$. Rewrite this as $$f(x) \geq f(x_0) + \frac{\langle x-x_0, x_0 \rangle}{(1+\lVert x_0 \rVert^2)^{\frac12}}.$$  This shows that $f$ lies strictly above its tangent plane at $x_0$ for $x \neq x_0$.  This holds for any choice of $x_0$.  Therefore, $f$ is strictly convex.


text:
Q: Convert php curl to curl I am not familer with PHP and need help to convert below php code to command line curl. Please advise. I tried different ways using postman but did not work out.
$username="";
$password="";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://www.xxx.co.uk/apinew");
curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('username' => $username,'pass' => $password,'type' => 'both','buildname' => 'Little Westwood House','subBname' => '','number' => '','depstreet' => '','street' => 'Bucks Hill','postcode' => 'WD4 9AR')));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

print_r($server_output);


text:
Q: Es6 - Match two different object keys with different name I am working on two API's that I don't have permission to change their field names (Sample below)
const api1 = {
  studentId: 'abc',
  studentName: 'John Doe',
  studentAge: 19,
  course: 'Engineering',
}

const api2 = {
  id,
  personalInfo: {
    name,
    age
  },
  course:
}

Basically I will need to transfer the data from api2 to api 1 so what I did is:
const payload = {}
payload["studentId"] = api2.id,
payload["studentName"] = api2.personalInfo.name,
payload["studentAge"] = api2.personalInfo.age,
payload["course"] = api2.course,

Is there a way how I can do this dynamically ?

A: You could take a wrapper object which wraps all wanted properties of the given API to a new API.
This approach takes an object which maps the given properties to new format/names of the wanted structure by getting the entries of the object and iterating these until a non object is found and then it assigns the value to a new object. If an object is found it take this object and gets the values from the nested object.
If nested target properties are supplied, like
{ studentName: 'personalInfo.name' }

(for example for creating API2 from API1) you need to split the value and create an object with a nested structure, like
const
    path = value.split('.'),
    last = path.pop();

path.reduce((o, k) => o[k] ??= {}, target)[last] = source[key];

in the else part.

const
    assign = (source, wrapper, target = {}) => {
        Object.entries(wrapper).forEach(([key, value]) => {
            if (value && typeof value === 'object') assign(source[key], value, target);
            else target[value] = source[key];
        });
        return target;
    },
    api1 = { studentId: 'abc', studentName: 'John Doe', studentAge: 19, course: 'Engineering' },
    api2 = { id: 'someId', personalInfo: { name: 'someName', age: 'someAge' }, course: 'someCourse' },
    wrapper = { id: 'studentId', personalInfo: { name: 'studentName', age: 'studentAge' }, course: 'course' },
    payload = assign(api2, wrapper);

console.log(payload);


text:
Q: Get taxonomies (for custom post type) to use parent archive styling by default I just created a new custom post type called research.  I added three taxonomies, research field, author and publication. I then created archive-research.php and content-research.php to create a different style. I was under the impression that all the taxonomies from research would use this archive, so I was either wrong or I've screwed something up.  The whole point of the various taxonomies was to be able to create various listings I could add to the menu, but they all end up using the default archive.  The only way to use the custom archive is to visit mywebsite.com/research, but that shows everything. I know it's possible to create custom taxonomies templates as well, but is there is some way to have the taxonomies use their parent archive by default?
Anyway, here is the code I'm currently using, maybe I'm just missing something, I'm still rather new at wordpress.
function create_research_cpt() {

$labels = array(
    'name' => __( 'Research', 'Post Type General Name', 'textdomain' ),
    'singular_name' => __( 'Research', 'Post Type Singular Name', 'textdomain' ),
    'menu_name' => __( 'Research', 'textdomain' ),
    'name_admin_bar' => __( 'Research', 'textdomain' ),
    'archives' => __( 'Research Archives', 'textdomain' ),
    'attributes' => __( 'Research Attributes', 'textdomain' ),
    'parent_item_colon' => __( 'Parent Research:', 'textdomain' ),
    'all_items' => __( 'All Research', 'textdomain' ),
    'add_new_item' => __( 'Add New Research', 'textdomain' ),
    'add_new' => __( 'Add New', 'textdomain' ),
    'new_item' => __( 'New Research', 'textdomain' ),
    'edit_item' => __( 'Edit Research', 'textdomain' ),
    'update_item' => __( 'Update Research', 'textdomain' ),
    'view_item' => __( 'View Research', 'textdomain' ),
    'view_items' => __( 'View Research', 'textdomain' ),
    'search_items' => __( 'Search Research', 'textdomain' ),
    'not_found' => __( 'Not found', 'textdomain' ),
    'not_found_in_trash' => __( 'Not found in Trash', 'textdomain' ),
    'featured_image' => __( 'Featured Image', 'textdomain' ),
    'set_featured_image' => __( 'Set featured image', 'textdomain' ),
    'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
    'use_featured_image' => __( 'Use as featured image', 'textdomain' ),
    'insert_into_item' => __( 'Insert into Research', 'textdomain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this Research', 'textdomain' ),
    'items_list' => __( 'Research list', 'textdomain' ),
    'items_list_navigation' => __( 'Research list navigation', 'textdomain' ),
    'filter_items_list' => __( 'Filter Research list', 'textdomain' ),
);
$args = array(
    'label' => __( 'Research', 'textdomain' ),
    'description' => __( 'Studies, Papers, Data & Research', 'textdomain' ),
    'labels' => $labels,
    'menu_icon' => 'dashicons-admin-page',
    'supports' => array('title', 'editor', 'thumbnail', ),
    'taxonomies' => array('field', 'authors', 'publications', ),
    'public' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'menu_position' => 5,
    'show_in_admin_bar' => true,
    'show_in_nav_menus' => true,
    'can_export' => true,
    'has_archive' => true,
    'hierarchical' => true,
    'exclude_from_search' => false,
    'show_in_rest' => true,
    'publicly_queryable' => true,
    'capability_type' => 'post',
);
register_post_type( 'research', $args );

}
add_action( 'init', 'create_research_cpt', 0 );

function create_field_tax() {

$labels = array(
    'name'              => _x( 'Research Fields', 'taxonomy general name', 'textdomain' ),
    'singular_name'     => _x( 'Research Field', 'taxonomy singular name', 'textdomain' ),
    'search_items'      => __( 'Search Research Fields', 'textdomain' ),
    'all_items'         => __( 'All Research Fields', 'textdomain' ),
    'parent_item'       => __( 'Parent Research Field', 'textdomain' ),
    'parent_item_colon' => __( 'Parent Research Field:', 'textdomain' ),
    'edit_item'         => __( 'Edit Research Field', 'textdomain' ),
    'update_item'       => __( 'Update Research Field', 'textdomain' ),
    'add_new_item'      => __( 'Add New Research Field', 'textdomain' ),
    'new_item_name'     => __( 'New Research Field Name', 'textdomain' ),
    'menu_name'         => __( 'Research Field', 'textdomain' ),
);
$args = array(
    'labels' => $labels,
    'description' => __( '', 'textdomain' ),
    'hierarchical' => true,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'show_in_rest' => false,
    'show_tagcloud' => true,
    'show_in_quick_edit' => true,
    'show_admin_column' => false,
);
register_taxonomy( 'field', array('research', ), $args );

}
add_action( 'init', 'create_field_tax' );

function create_author_tax() {

$labels = array(
    'name'              => _x( 'Authors', 'taxonomy general name', 'textdomain' ),
    'singular_name'     => _x( 'Author', 'taxonomy singular name', 'textdomain' ),
    'search_items'      => __( 'Search Authors', 'textdomain' ),
    'all_items'         => __( 'All Authors', 'textdomain' ),
    'parent_item'       => __( 'Parent Author', 'textdomain' ),
    'parent_item_colon' => __( 'Parent Author:', 'textdomain' ),
    'edit_item'         => __( 'Edit Author', 'textdomain' ),
    'update_item'       => __( 'Update Author', 'textdomain' ),
    'add_new_item'      => __( 'Add New Author', 'textdomain' ),
    'new_item_name'     => __( 'New Author Name', 'textdomain' ),
    'menu_name'         => __( 'Author', 'textdomain' ),
);
$args = array(
    'labels' => $labels,
    'description' => __( '', 'textdomain' ),
    'hierarchical' => false,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'show_in_rest' => false,
    'show_tagcloud' => true,
    'show_in_quick_edit' => true,
    'show_admin_column' => false,
);
register_taxonomy( 'author', array('research', ), $args );

}
add_action( 'init', 'create_author_tax' );

function create_publication_tax() {

$labels = array(
    'name'              => _x( 'Publications', 'taxonomy general name', 'textdomain' ),
    'singular_name'     => _x( 'Publication', 'taxonomy singular name', 'textdomain' ),
    'search_items'      => __( 'Search Publications', 'textdomain' ),
    'all_items'         => __( 'All Publications', 'textdomain' ),
    'parent_item'       => __( 'Parent Publication', 'textdomain' ),
    'parent_item_colon' => __( 'Parent Publication:', 'textdomain' ),
    'edit_item'         => __( 'Edit Publication', 'textdomain' ),
    'update_item'       => __( 'Update Publication', 'textdomain' ),
    'add_new_item'      => __( 'Add New Publication', 'textdomain' ),
    'new_item_name'     => __( 'New Publication Name', 'textdomain' ),
    'menu_name'         => __( 'Publication', 'textdomain' ),
);
$args = array(
    'labels' => $labels,
    'description' => __( '', 'textdomain' ),
    'hierarchical' => false,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'show_in_rest' => false,
    'show_tagcloud' => true,
    'show_in_quick_edit' => true,
    'show_admin_column' => false,
);
register_taxonomy( 'publication', array('research', ), $args );

}
add_action( 'init', 'create_publication_tax' );

A:
I was under the impression that all the taxonomies from research would
  use this archive

According to the doc, yes, you can use archive-research.php to render the appropriate archive index page for the custom post type research. However, for the custom taxonomies, you'd need taxonomy-{taxonomy}.php. So:

*

*taxonomy-field.php

*taxonomy-author.php

*taxonomy-publication.php
Or, if you want just one template, then in archive.php, you can construct the Loop like this: (which is based on the archive.php template for Twenty Seventeen theme version 1.4)
<?php
if ( have_posts() ) : ?>
    <?php
    /* Start the Loop */
    while ( have_posts() ) : the_post();

        if ( 'research' === get_post_type() ) {
            // Load template based on the Post Type.
            get_template_part( 'template-parts/post/content', 'research' );
        } else {
            // Load template based on the Post Format.
            get_template_part( 'template-parts/post/content', get_post_format() );
        }

    endwhile;

else :

    get_template_part( 'template-parts/post/content', 'none' );

endif; ?>

[EDIT] Referring to the following comment:

It's just I want to use a different look for the research archives as
  opposed to the blog, and didn't want to have to go through each
  taxonomy

Add this to the theme's functions.php file:
add_filter( 'template_include', function ( $template ) {
    if ( is_tax( array( 'field', 'author', 'publication' ) ) ) {
        return locate_template( 'archive-research.php' );
    }
    return $template;
} );


text:
Q: Android header views scrolling separate to list view hi I'm creating a list view using a merge adapter. but i'm having some issues with the headers . they seem to scroll to independently of the list often just snapping to the top of the page. how do i get it so that the headers stay in place?or does anyone no what could cause this?
heres my code
arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
arrayAdapter3 = new ArrayAdapter<String>(this, R.layout.single_item, newsList3);

 RelativeLayout layout = new RelativeLayout(this);
 RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);

    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.titlerect);
    layout.addView(mImage,labelLayoutParams);

    TextView latestFixtures;
       latestFixtures = new TextView(this);
       latestFixtures.setText("Latest League Fixture");
       layout.addView(mImage,labelLayoutParams);

    ListView list = getListView();
       list.setTextFilterEnabled(true);

setListAdapter (arrayAdapter);

    adapter = new MergeAdapter();
    adapter.addView(layout);
    adapter.addAdapter(arrayAdapter);
    adapter.addView(layout);
    adapter.addAdapter(arrayAdapter2);
    adapter.addView(layout);
    adapter.addAdapter(arrayAdapter3);
    setListAdapter(adapter);

}

code
05-15 13:35:14.489: E/ListView(1045): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
05-15 13:35:14.489: E/ListView(1045):   at android.widget.ListView.setupChild(ListView.java:1834)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.ListView.makeAndAddView(ListView.java:1803)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.ListView.fillDown(ListView.java:670)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.ListView.fillFromTop(ListView.java:727)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.ListView.layoutChildren(ListView.java:1646)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.AbsListView.onLayout(AbsListView.java:1260)
05-15 13:35:14.489: E/ListView(1045):   at android.view.View.layout(View.java:7277)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.TableLayout.onLayout(TableLayout.java:440)
05-15 13:35:14.489: E/ListView(1045):   at android.view.View.layout(View.java:7277)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
05-15 13:35:14.489: E/ListView(1045):   at android.view.View.layout(View.java:7277)
05-15 13:35:14.489: E/ListView(1045):   at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
05-15 13:35:14.489: E/ListView(1045):   at android.view.View.layout(View.java:7277)
05-15 13:35:14.489: E/ListView(1045):   at android.view.ViewRoot.performTraversals(ViewRoot.java:1203)
05-15 13:35:14.489: E/ListView(1045):   at android.view.ViewRoot.handleMessage(ViewRoot.java:1957)
05-15 13:35:14.489: E/ListView(1045):   at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 13:35:14.489: E/ListView(1045):   at android.os.Looper.loop(Looper.java:143)
05-15 13:35:14.489: E/ListView(1045):   at android.app.ActivityThread.main(ActivityThread.java:4263)
05-15 13:35:14.489: E/ListView(1045):   at java.lang.reflect.Method.invokeNative(Native Method)
05-15 13:35:14.489: E/ListView(1045):   at java.lang.reflect.Method.invoke(Method.java:507)
05-15 13:35:14.489: E/ListView(1045):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-15 13:35:14.489: E/ListView(1045):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-15 13:35:14.489: E/ListView(1045):   at dalvik.system.NativeStart.main(Native Method)

A: Either use MergeAdapter or use addHeaderView(), not both.


text:
Q: Rails update_all for each array element I have a follow method, it works well
def update
  ids = params["_json"].map { |hash| hash["id"] }  # --> return [10, 20, 30, 40 ]
  positions = params["_json"].map { |hash| hash["position"] } # --> return [0, 1, 2, 3 ]

  query = MyQueryQuery.new
  query.visible = true
  query.active = true

  available = query.fetch.map(&:id)
      ::Model.where(id: (ids & available))
        .update_all(show_home: true, updated_at: DateTime.now)
end

How can I change this method to update a new column in my Model called position with each element from postions array? For example, in Model(id: 10, position: 0), Model(id: 20, position: 1), Model(id: 30, position: 2) etc ....

A: You can remove the .map from positions and get the elements from hash to update, like that.
positions = params["_json"]

positions.each do |p|
  model = Model.find(p['id'])
  model.update(position: p['position'])
end


text:
Q: Windows Authentication - How to impersonate a user while developing locally? I'm inherited an ASP.NET website project where they have used Windows Authentication. The "admin" account that they are testing are on a separate network, and I need to impersonate that account (there is a table in a database that I currently have that holds the admin account's related contents, so I first need to be able to "logged in" as that user in order to see the contents). I've tried to set the web.config like this:
<identity impersonate="true" userName="admin.user" password="admin.pass" />

Where "admin.user" and "admin.pass" are the actual admin's account credentials. However, when I run the site, I received this error message:
Parser Error Message: Could not create Windows user token from the credentials specified in the config file. Error from the operating system 'Logon failure: unknown user name or bad password.

I'm not familiar with Windows Authentication and impersonation so any help would be appreciated.
Thanks.

A: Host it on IIS and then it should work.


text:
Q: Python - Matching a part of a word in a line and taking in multiple till the end of a line I currently have a config file which has words starting in as "ltm  AZ2b, then followed by a few lines of config and then finally followed by vs-index as the end of the line.
Here's an example:

ltm virtual ync-Prod-Environment-VS {
.....
.....
}
...
vs-index 56
--right under this is another config set:
ltm virtual ync-Prod-Environment-VS-AZ2b {
.....
.....
}
...
vs-index 45

As you can see above(highlighted as well), there are multiple sets of config, and each set starts with ,-VS (multiple lines of config under this) and another set of similar config with the same name but with AZ2b, like: -VS-AZ2b (multiple lines of config under this as well)
I'm trying to extract only the config set which starts with -VS-AZ2b and ends with its vs-index.
I've written the following code but it is not working very well:

import re
fhandle=open('C:/Python Programs/Active.txt', 'r')
str=fhandle.read()
y=re.findall('^.+AZ2b .+? vs-index [0-9].', str, re.DOTALL)
for line in y:
     line = line.replace('\n', "\n")
     print line

The output that i get is everything - including the config set with -VS. Not sure why. Can someone help?
Just to check, i took a file and added only the config sets with -VS and the program did not return anything. So i guess the code is only partially correct.
Thanks!

A: Actually i got it to work. I had to modify the regex this way:
y=re.findall('^.+AZ2b [\s\S]*?.+vs-index [0-9].\n}',str, re.MULTILINE)
The [\s\S]*? was missing in the regex. I got this info from here in stackflow:
Also re.DOTALL was not working very well for this as it was matching everything, so i had to use re.MULTILINE instead
Can I match multiline string in python without using re.DOTALL?
Thanks all!!


text:
Q: working with bootstrap scrollspy in MVC 5
I am using Bootstrap ScrollSpy in MVC 5 application.
ScrollSpy works fine with plain html and jquery but I want to implement the same thing in MVC 5.

About

Contact

the above code works fine, but when I tried to implement the same thing in MVC I somehow get confused.

 @Html.ActionLink("About", null, null, null, new { @class = "hidden-xs" })

 @Html.ActionLink("Contact", null,null, null, new { @class = "hidden-xs" })

This is not working as expected as its trying to redirect to specified actionname or I may be doing something wrong.
Suggest something.

A: Requirement for Bootstrap scrollspy to work, the scrollable elements must match the ID of the links.
Here
Contact
 should match div with id

Using Mvc:

 @Html.ActionLink("Contact", "Index", "Home", null, null, "contact", null, null)

 Contact

Check difference between HTML.ActionLink vs Url.Action here.
So finally in server side both generates url with trailing slash before hash(#) as shown below:
Contact

And thus above link doesn't  match div with id
 because of / before #
Solution Using Mvc:
Create Custom UrlHelper
Create a folder named Helpers and add a class named UrlExtensions finally add below code:
public static class UrlExtensions
{

    public static string HashAnchorLinks(this UrlHelper url, string hashLinkName)
    {

     string hashAnchorLink = string.Format("#{0}", hashLinkName);

     return hashAnchorLink;

    }

}

In View:
@using YourProjectName.Helpers;

 About

 Contact

Note:
Best solution would be using plain html as you did before, instead of using server to return the hash link.
References:
1.
2.
3.

A: Your not passing the right parameters in into the ActionLink().
@Html.ActionLink("About", "Home", "About", new object { }, new { @class = "hidden-xs"})
@Html.ActionLink("Contact", "Home", "Contact", new object { }, new { @class = "hidden-xs"})

Here is a explanation of the function.


text:
Q: compare all elements of arraylist with first element  int odo_str=o.getSpans();
ArrayList<integer> newlist = new ArrayList<integer>();
 newlist.add(odo_str);

In an arraylist how to compare all elements with first element in the arraylist,if it is greater than first element then i want to store them in one array,if elements are less than first element then want to store them in another arraylist.how to do it.thanks.

A: Here's some help:
To get the first element in the ArrayList:
<T> firstElement = ArrayList<T>.get(0);

To iterate through an ArrayList:
for (T element : yourArrayList) { //do things }

Conditional example:
if (element > firstElement) { //do things }

Storing item in array:
yourArray[index] = element;

Storing item in ArrayList:
yourOtherArrayList.add(element);

A: Hope this help:
public class Main {

        public static void main(String[] args) {
            List<Integer> myList = Arrays.asList(12,34,45,23,45,7,68,4,345,56,67,4,999,454,6,76,0);
            Iterator<Integer> iter = myList.iterator();
            List<Integer> lessList = new ArrayList<Integer>(), biggerList = new ArrayList<Integer>();
            Integer firstItem = iter.next();
            while (iter.hasNext()) {
                Integer currElement = iter.next();
                if (firstItem.compareTo(currElement) > -1) {
                    lessList.add(currElement);
                } else {
                    biggerList.add(currElement);
                }
            }

            System.out.println(lessList.toString());
            System.out.println(biggerList.toString());
        }

    }

This print:
[7, 4, 4, 6, 0]
[34, 45, 23, 45, 68, 345, 56, 67, 999, 454, 76]


text:
Q: URL with %7B and %7D I'm learning to use APIs with Flutter and I'm trying to use the Open Weather Map to this but, my code is inserting this %7B and %7D in every variable that I use in URL.
actual URL:
https://api.openweathermap.org/data/2.5/weather?lat=%7B-15.783783783783784%7D&lon=%7B-47.93345625648786%7D&appid=%7Bf0060b47028a54500c466c7288e41d31%7D

This is what i want:
https://api.openweathermap.org/data/2.5/weather?lat=-15.783783783783784&lon=-47.93345625648786&appid=f0060b47028a54500c466c7288e41d31

What's wrong with my code ?
My code:
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

const apiKey = 'f0060b47028a54500c466c7288e41d31';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  double latitude;
  double longitude;

  void getLocation() async {
    Location location = Location();
    await location.getCurrentLocation();
    latitude = location.latitude;
    longitude = location.longitude;
    getData();
  }

  void getData() async {
    var url = Uri.https('api.openweathermap.org', '/data/2.5/weather', {
      'lat': '{$latitude}',
      'lon': '{$longitude}',
      'appid': '{$apiKey}',
    });
    var response = await http.get(url);

    if (response.statusCode == 200) {
      String data = response.body;

      var temperature = jsonDecode(data)['main']['temp'];

      print(temperature);
    } else {
      print(response.statusCode);
      print(url);
    }
  }

  @override
  void initState() {
    getLocation();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }

  @override
  void deactivate() {
    super.deactivate();
  }
}

A: In your getData() function, try removing the curly braces around the url parameters, like this:
var url = Uri.https('api.openweathermap.org', '/data/2.5/weather', {
  'lat': '$latitude',
  'lon': '$longitude',
  'appid': '$apiKey',
});

Alternatively, you can concatenate the URL tring yourself like this.
var baseUrl = 'https://api.openweathermap.org/data/2.5/weather?';
var appid = 'f0060b47028a54500c466c7288e41d31';
var latString = '-15.783783783783784';
var lonString = '-47.93345625648786';

var urlString =
    baseUrl + 'lat=$latString' + '&' + 'lon=$lonString' + '&' + 'appid=$appid';