Q: Cannot access `properties` key/value content when querying ArcGIS Feature Service for GeoJSON Using ArcGIS with a developer account, I created a new layer, uploaded a .geojson file, and happily followed along the "query a feature layer" tutorial on their labs site. I successfully generated an OAuth Token in Postman, but when I changed the "f" (format) value in the x-www-form-urlencoded body to "geojson" it looks similar to the originally GeoJSON file, but the properties are missing/null and the only key info included are the Polygon coordinates. The data remains in the ArcGIS Dashboard but isn't included in the data. Any advice? Is this a bug?
Original File (.geojson):
{
  "type": "FeatureCollection",
  "features": [{
    "geometry": {
      "coordinates": [
        [
          [50.0115001901903, 50.2259915257836, 0],
          [50.0115418500254, 50.225991583611, 0],
          [50.0115447598285, 50.2242567612666, 0],
          [50.0115031005844, 50.2242567034437, 0],
          [50.0115001901903, 50.2259915257836, 0]
        ]
      ],
      "type": "Polygon"
    },
    "ID": "asdf98d0-fa90-4293-a780-a6988f5486f7",
    "id": 1,
    "type": "Feature",
    "properties": {
      "CreationDate": "Wed, 17 June 2020 18:40:41 GMT",
      "Editor": "dkoch"
    }
  }]
}

Received file from POST /0/query rest endpoint with f: geojson, token: (working token), where: 1=1:
{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            50.0115001901903,
                            50.2259915257836
                        ],
                        [
                            50.0115418500254,
                            50.225991583611
                        ],
                        [
                            50.0115447598285,
                            50.2242567612666
                        ],
                        [
                            50.0115031005844,
                            50.2242567034437
                        ],
                        [
                            50.0115001901903,
                            50.2259915257836
                        ]
                    ]
                ]
            },
            "properties": null
        }
    ]
}

A: I think you need to specify the "outFields" parameter.
To return all available fields I believe its "outFields=*"


Q: Sql sum of count field with different product name once Is there any good method to get the count of different product once.
for example
/* the table like */
id      count         product
 1       5              a
 2       2              b
 3       6              c
 4       2              a
 ......

I want to get the sum of product use one sql command. because the product number is very large.
the value like
a b c
7 2 6

Thank you very much!

A: It's a simple sum and group by
select product, sum(count)
from mytable
group by product

A: Select product, sum(count)
from table_name
group by product

You might want to go through tutorial of group_by clause
http://www.techonthenet.com/sql/group_by.php

A: i dont know if you looking for pivote result as you done in your question , if yes use this
SELECT Sum(CASE
             WHEN ( product = 'a' ) THEN ` count `
           ELSE 0
           END)AS a,
       Sum(CASE
             WHEN ( product = 'b' ) THEN ` count `
           ELSE 0
           END)AS b,
       Sum(CASE
             WHEN ( product = 'c' ) THEN ` count `
           ELSE 0
           END)AS c
FROM   table1

DEMO HERE
result:
 A  B  C
 7  2  6

note this query is only if you have 3 limited values on product.


Q: admin page shows Front controller reached 100 router match iterations in magento 2 my magento 2 site front end has no problem.
but when i open admin login page it will shows
1 exception(s):
Exception #0 (LogicException): Front controller reached 100 router match iterations

Exception #0 (LogicException): Front controller reached 100 router match iterations
#0 /var/www/html/lib/internal/Magento/Framework/Interception/Interceptor.php(74): Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))
#1 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(70): Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch', Array)
#2 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'requestPreproce...')
#3 /var/www/html/app/code/Magento/Store/App/FrontController/Plugin/RequestPreprocessor.php(94): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#4 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(67): Magento\Store\App\FrontController\Plugin\RequestPreprocessor->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#5 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'install')
#6 /var/www/html/lib/internal/Magento/Framework/Module/Plugin/DbStatusValidator.php(69): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#7 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(67): Magento\Framework\Module\Plugin\DbStatusValidator->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#8 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#9 /var/www/html/app/code/Magento/PageCache/Model/App/FrontController/VarnishPlugin.php(55): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#10 /var/www/html/lib/internal/Magento/Framework/Interception/Chain/Chain.php(67): Magento\PageCache\Model\App\FrontController\VarnishPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#11 /var/www/html/lib/internal/Magento/Framework/Interception/Interceptor.php(138): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#12 /var/www/html/app/code/Magento/PageCache/Model/App/FrontController/BuiltinPlugin.php(68): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#13 /var/www/html/lib/internal/Magento/Framework/Interception/Interceptor.php(142): Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#14 /var/www/html/var/generation/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array)
#15 /var/www/html/lib/internal/Magento/Framework/App/Http.php(135): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#16 /var/www/html/lib/internal/Magento/Framework/App/Bootstrap.php(258): Magento\Framework\App\Http->launch()
#17 /var/www/html/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#18 {main}


Q: creating multiple src directories in eclipse I am doing this tutorial, which asks me to create multiple source directories in eclipse.  Can someone explain how to do that?  I am describing the steps I have taken so far as follows:
The image below shows the tutorial's directory structure on left, and my current directory structure on right:

As you can see, I need to create the following folders under Java Resources:
src/test/java
src/test/resources
src/main/resources

However, when I right click on the Java Resources folder and select new source folder, I get the following dialog box, for which I have clicked on the Browse... Folder Name button to open the subdialog which is also shown:

At this point, none of the choices seem to be what I want.  So how do I create the three new src subdirectories that are specified by the tutorial?

A: Right-click your project, select Build Path and Configure Build Path.... In the Source tab, if src/main/resources or src/test/java appear, remove them. This might be a bug with the Maven plugin, I don't know. They appear like they are there, but aren't really.
Then use Add Folder... to add the folders you need. Do this by selecting a folder (to add folders to), like src/main, clicking Create New Folder... and using the folder name resources (or as appropriate).

A: You close the "Existing Folder Selection" dialog (since you don't want an existing folder, but a new one), and you enter src/test/java in "Folder Name". Then you click Finish. You repeat this operation for every new folder you want.
Of course, you could also use your file manager to create the folders, and select them in Eclipse.


Q: Chrome - why is it sending if-modified-since requests? I have a page with lots of small images (icons). When used with chrome, each time the page is reloaded, chrome requests each icon from the server with if-modified-since header.
All icons are served with expires and max-age headers. Firefox loads images from its cache.
Why is chrome doing that and how can I prevent it?
Thanks

A: A quick experiment with Chrome’s inspector shows that this only happens when the page is reloaded, not when it is loaded normally. Chrome is just trying to refresh its cache. Think about it — if you set Expires and Max-Age to several decades, are you asking the browser to cache that resource and never check to see if it gets updated? It’s caching the resource when it can, but when the page needs to be refreshed it wants to make sure that the entire page is refreshed. Other browsers surely do it too (although some have an option for the number of hours to wait before refreshing).
Thanks to modern browsers and servers, refreshing a large number of icons won’t be as slow as you think — requests are pipelined to eliminate multiple round-trip delays, and the entire purpose of the If-Modified-Since header is to allow the server to compare timestamps and return a "Not Modified" status code. This will happen for every resource the page needs, but the browser will be able to make all the requests at once and verify that none of them have changed.
That said, there are a few things you can do to make this easier:

*

*In Chrome’s inspector, use the resources tab to see how they are being loaded. If there are no request headers, the resource was loaded directly from the cache. If you see 304 Not Modified, the resource was refreshed but did not need to be downloaded again. If you see 200 OK, it was downloaded again.

*In Chrome’s inspector, use the audits tab to see what it thinks about the cacheability of your resources, just in case some of the cache headers aren’t optimal.

*All of those If-Modified-Since requests and 304 responses can add up, even though they only consist of headers. Combine your images into sprites to reduce the number of requests.

A: Modern browsers are getting more complex and intelligent with their caching behaviour.  Have a read through http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx for some examples and more detail.
As Florian says, don't fight it :-)

A: Have you checked the request headers?
"‘Cache-Control’ is always set to ‘max-age=0′, no matter if you press enter, f5 or ctrl+f5. Except if you start Chrome and enter the url and press enter."
http://techblog.tilllate.com/2008/11/14/clientside-cache-control/

A: With chrome it matters whether you're refreshing a page or simply visiting it.
When you refresh, chrome will ping the server for each file regardless of whether or not they are already cached.  If the file hasn't been modified you should see a 304 Not Modified response.  If the file has been modified you'll see a 200 OK response instead.
When not refreshing, cached files will have a 200 OK status but if you look in the size/content column of the network panel you'll see (from cache).

A: Google Chrome will ignore the Expires header if it's not a valid date by the RFC. For instance, it always requires days to be specified as double-digits. 1st of May should be set as "01 May" (not "1 May") and so on. Firefox accepts them, this misleads the user that the problem is at the browser (this case, Chrome) and not the header values themselves.
So, if you are setting the expire date manually (not using mod_expires or something similar to calculate the actual date) I recommend you to check your static file headers using REDbot.

A: That sounds like it's trying to avoid an outdated cache by asking the server whether the images have changed since it last requested them. Sounds like a good thing, not something you would like to prevent.

A: Assuming you are running Apache, you can try explicitly setting up cache lifetimes for certain files types and/or locations in the filesystem.

<FilesMatch ".(jpg|jpeg|png|gif)$">
    Header set Cache-Control "max-age=604800, public" # 7 days
</FilesMatch>

or something like

ExpiresByType image/jpeg "access plus 7 days"
ExpiresByType image/gif "access plus 7 days"
ExpiresByType image/png "access plus 7 days"

Typically, I will group types of files by use in a single directory and set lifetimes accordingly.
Browsers should not request files at all until this ages have expired, but may not always honor it.  You may want/need to futz with Last-Modified and ETag headers.  There is lots of good info on the web about this.


Q: wrapping titles and sections around figures I need to do this kind of layout on LaTeX, but I have no idea how I could wrap figures around titles. Does anyone know of any way to do this ? Or would someone happen to know a template to do just what you can see on the drawing I uploaded ?
Thanks a lot :)

A: Use short titles so that the images don't show up in the table of contents.  The macro \sectioncalc computers \titlewidth to be used for section titles.  (The section number is not included.)  A lot depends on how wide your titles are and how big the images (and how you want them placed relative to the titles).  And you don't HAVE to use \maketitle.
The 16pt is a bit of a kludge, but none of the lengths I found in \section and \@startsection worked.
\documentclass{article}
\usepackage{showframe}
\usepackage{mwe}

\newlength\titlewidth

\def\sectioncalc{\settowidth{\titlewidth}{\normalfont\Large\bfseries\thesection}%
  \titlewidth=\dimexpr\textwidth-\titlewidth-16pt\relax}% \@tempskipa=18pt

\title{\parbox{\textwidth}{\raisebox{-0.5\height}{\includegraphics[width=2in]{example-image}}%
  \hfill\parbox[c]{2in}{\textbf{This is a multiline title}}}}

\begin{document}
\maketitle

%\setcounter{section}{21}
\section[First Secdtion]{\sectioncalc\parbox[b]{\titlewidth}{First Section
  \hfill\raisebox{-0.5\height}[0.5\height][0pt]{\includegraphics[width=2in]{example-image}}}}
\subsection{First Subsection}

\hangindent=-2.2in
\hangafter=-2
\lipsum[1]

\end{document}


Q: How to find the median month between two dates? I need to find the median month value between two dates in a date frame. I am simplifying the case by showing four examples.
import pandas as pd
import numpy as np
import datetime
df=pd.DataFrame([["1/31/2016","3/1/2016"],
                 ["6/15/2016","7/14/2016"],
                 ["7/14/2016","8/15/2016"],
                 ["8/7/2016","9/6/2016"]], columns=['FromDate','ToDate'])

df['Month'] = df.ToDate.dt.month-df.FromDate.dt.month

I am trying to append a column but I am not getting the desired result.
I need to see these values: [2,6,7,8].

A: You can calculate the average date explicitly by adding half the timedelta between 2 dates to the earlier date. Then just extract the month:
# convert to datetime if necessary
df[df.columns] = df[df.columns].apply(pd.to_datetime)

# calculate mean date, then extract month
df['Month'] = (df['FromDate'] + (df['ToDate'] - df['FromDate']) / 2).dt.month

print(df)

    FromDate     ToDate  Month
0 2016-01-31 2016-03-01      2
1 2016-06-15 2016-07-14      6
2 2016-07-14 2016-08-15      7
3 2016-08-07 2016-09-06      8

A: You need to convert the string to datetime before using dt.month.
This line calculates the average month number :
df['Month']   = (pd.to_datetime(df['ToDate']).dt.month +
                 pd.to_datetime(df['FromDate']).dt.month)//2
print(df)
    FromDate     ToDate  Month
0  1/31/2016   3/1/2016      2
1  6/15/2016  7/14/2016      6
2  7/14/2016  8/15/2016      7
3   8/7/2016   9/6/2016      8

This only works with both dates in the same year.
jpp's solution is fine but will in some cases give the wrong answer:
["1/1/2016","3/1/2016"]  one would expect 2 because February is between January and March, but jpp's will give 1 corresponding to January.


Q: Problema con reloj de Javascript Tengo este codigo el cual hace un reloj en Javascript. El único problema que tengo es que no agarra el uso horario correctamente y le resta 30 minutos a la hora y le suma una hora.
Logre arreglar lo de la hora que se suma demas, pero no logró arreglar los 30 minutos extra porque si le sumo los 30 minutos, el reloj muestra la hora mal.
Mi horario es UTC-4
Aqui dejo mi codigo

window.onload = date_time('date_time');

function date_time(id) {
  date = new Date;
  year = date.getFullYear();
  month = date.getMonth();
  months = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
  d = date.getDate();
  day = date.getDay();
  days = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sabado');
  h = date.getHours() - 1;
  var session = "AM";

  if (h < 10)
  {
    h = "0" + h;
  }

  if (h >= 12 && session == "AM") {
    h = h - 11;
    session = "PM";
  }

  m = date.getMinutes();
  if (m < 10)
  {
    m = "0" + m;
  }

  s = date.getSeconds();
  if (s < 10)
  {
    s = "0" + s;
  }

  result = '' + days[day] + ',' + ' ' + d + ' ' + 'de ' + months[month] + ' ' + 'del' + ' ' + year + '' + ', ' + h + ':' + m + ':' + s + ' ' + session;
  document.getElementById(id).innerHTML = result;
  setTimeout('date_time("' + id + '");', '1000');
  return true;
}
body {
  background-image: url("imagenes/fondo_une.jpg")
}

A: intentalo asi:
regresando los valores a su estado normal.
te agrege la opcion 2 que es para el format del toLocaleString pasandole un timezone deseado en mi ejemplo America/Bogota.

window.onload = date_time();

function date_time() {

date = new Date();
year = date.getFullYear();

month = date.getMonth();
months = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
d = date.getDate();
day = date.getDay();
days = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sabado');
var session = "AM";

h = ("0" + date.getHours()).slice(-2);
m = ("0" + date.getMinutes()).slice(-2);
s = ("0" + date.getSeconds()).slice(-2);

if (h >= 12) {
    h = h - 11;
    session = "PM";
}

result = `${days[day]}, ${d} de ${months[month]} del  ${year},  ${h}:${m}:${s} ${session}`;

time  = date.toLocaleString('en-US', { timeZone: 'America/Bogota', hour: 'numeric', minute: 'numeric', second: 'numeric',hour12: true });
result2 = `version 2: ${days[day]}, ${d} de ${months[month]} del  ${year}, ${time}`;

document.getElementById("date_time").innerText = result;
document.getElementById("date_time2").innerText = result2;
setTimeout(date_time, '1000');
return true;
}
body {
  background-image: url("imagenes/fondo_une.jpg")
}

referencia:
toLocaleString


Q: Сохранить картику с Bitmap C# Мне нужно из Bitmap создать картинку формата *.png или *.jpg
Помогите!

A: Помог метод Image.Save (String, ImageFormat)
Bitmap PictureImg = new Bitmap(2560, 1920);

PictureImg.Save("img.png", System.Drawing.Imaging.ImageFormat.Png);


Q: creating a network from a list in python3 So, I'm stuck with this problem.
I am given a list of users who are friends
For example: the list appears so that
0 1,
1 2,
1 8,
2 3

and should return
[(0,[1]), (1,[0,2,8]), (2,[1,3]), (3,[2]), (8,[1])]

This is what I have so far:
network = []

for i in lines[1: (len(lines))]:
    network.append(i.split(" "))

network.sort()
secondary = [[]] * (len(lines)//2) #empty lists
for j in network:
    for k in secondary:
    #to make a new list for each user
        secondary[k].append(network[j][0])

But it says:
TypeError: list indices must be integers or slices, not list

I've tried experimenting and I'm still not sure why


Q: How to create an Accessible PDF Document without allowing Content copying? I am trying to create a secured document in such a way that "It should be read by Screen Reader devices like NVDA, JAWS etc. but Content Copying for Accessibility should be disabled". I had followed the below steps:

*

*Selected a file and opened the Protect tool.

*Customized Security Settings via "Encrypt with Password".

*I don't need to set a Document Open Password and hence I customized Permissions as below:
a. I have enabled "Restrict Editing And Printing of The Document" and set "Printing Allowed" to None and "Changes Allowed" to None.
b. I have disabled "Enable Copying Of Text, Images, And Other Content" to disallow Content Copying.
c. I have enabled "Enable Text Access For Screen Reader Devices For The Visually Impaired" to allow NVDA Screen Reader to read my PDF file.
d. I have selected Acrobat versions "Acrobat 7.0 and later" and "Acrobat X and later", one at a time and checked.
Here, The problem I faced was, NVDA Screen Reader is reading the file content aptly but at the same time, I was also able to copy the contents of the PDF file while NVDA is turned on (i.e., reading). I know this is because I had enabled "Enable Text Access For Screen Reader Devices For The Visually Impaired" which allowed Content Copying for Accessibility.
My requirement is to have a PDF which has the following features:

*

*Secured PDF

*Content copying and Content copying for Accessibility should be disabled to prevent all streams of users from copying my PDF file's Content.

*Editing and Printing of the document, Copying Of Text, Images, And Other Content should be restricted (allowed with Password anyway).

*Screen Reader devices like NVDA, JAWS should be able to read the PDF contents
Is there a way to accomplish this using Adobe Acrobat Pro DC?
Thanks in Advance!
Regards,
Sirisha Gorasa.


Q: What is an efficient way to do this in R? In R,
I am trying to filter out all cases from x whose $a is in y$b or y$d (when y$c is true).
x[(x$a %in% y$b | x$a %in% y[y$c == TRUE, ]$d), ]

Is this right? Is there a better way to do this?
Thanks

A: If it is a logical column, no need to == TRUE.  Also, when subsetting a single column, directly subset instead of subsetting it from the data.frame which is inefficient
x[(x$a %in% y$b | x$a %in% y$d[y$c]), ]

Or make it a bit more compact
x[(x$a %in% c(y$b, y$d[y$c])),]

A: It might be worth to give subset a try.
subset(x, a %in% b | a %in% y[y$c, 'd'])


Q: C++ read a Registry entry in SOFTWARE\WOW6432 from a 64-bit app I've got some 32-bit C++ code to read a Key/Value pair from the Registry as follows:
    // Get a handle to the required key
    HKEY    hKey;
    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\MyKey", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
    {
        // Look up the value for the key
        bOK = (RegQueryValueEx(hKey, szKey, NULL, NULL, (PBYTE)szValue, &dwMax) == ERROR_SUCCESS);

        // Release the handle
        RegCloseKey(hKey);
    }

As it's a 32-bit app it reads from  SOFTWARE\WOW6432Node\MyKey
This was working fine until I ported the app to 64-bit, so it now reads  from SOFTWARE\MyKey.
My installer won't let me put entries into both the 32-bit and 64-bit parts of the Registry, so I need the 64-bit app to go on  getting its data from WOW6432Node.
Does anyone know how to do this?
Many thanks
Tony Reynolds

A: As documented under 32-bit and 64-bit Application Data in the Registry:

The KEY_WOW64_64KEY and KEY_WOW64_32KEY flags enable explicit access to the 64-bit registry view and the 32-bit view, respectively. For more information, see Accessing an Alternate Registry View.

The latter link explains that

These flags can be specified in the samDesired parameter of the following registry functions:

*

*RegCreateKeyEx

*RegDeleteKeyEx

*RegOpenKeyEx

The following code accomplishes what you are asking for:
// Get a handle to the required key
HKEY    hKey;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\MyKey", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS)
{
    // ...
}


Q: RGB Color, wrong color I am currently working on an iOS Application in Swift 3 and wanted to change the color of my NavigationBar
with the following code:
self.navigationController?.navigationBar.barTintColor = UIColor.init(red: 53.0/255.0, green: 70.0/255.0, blue: 90.0/255.0, alpha: 1.0)

This code works quite fine but there's one problem. The color I entered in RGB format is displayed wrong.
Should be like this color:
But looks like this (left: is current Color () right: as already said should look like):

A: Set navigationController?.navigationBar.isTranslucent = false.
You can also achieve this by unchecking Translucent from storyboard.

A: Change navigation bar to Opaque instead of Translucent.
Swift
self.navigationController?.navigationBar.isTranslucent = true

Objective-C
[[UINavigationBar appearance] setTranslucent:YES];

Please find in image.

And if you are setting navigations background color then change
  navigation background color instead of tint color.


Q: A joke about blind date I cannot understand this joke on Twitter:

Has a blind date. The dates blind.

I know what blind date is, but what's the meaning of the second sentence?

A: There's a missing apostrophe there: "date's"
"The date's blind" means his/ her date is literally blind or handicapped.


Q: Xamarin forms WebAuthenticator usage I'm trying to implement Facebook Auth for Xamarin Forms App.
I'm doing everything like in this tutorial https://learn.microsoft.com/en-us/xamarin/essentials/web-authenticator?tabs=android so I'm using server side auth. Here is my mobile app code:
   public class WebAuthViewModel:ObservableObject
    {
        private const string AuthenticationUrl = "https://myapp.com/mobileauth/";

        private string _accessToken = "";
        private bool _isAuthenticated = false;

        public string AuthToken
        {
            get => _accessToken;
            set => SetProperty(ref _accessToken, value);
        }

        public ICommand FacebookCommand { get; }

        public WebAuthViewModel()
        {
            FacebookCommand = new Command(async()=>await OnAuthenticate("Facebook"));
        }

        async Task OnAuthenticate(string scheme)
        {
            try
            {
                WebAuthenticatorResult result = null;

                var authUrl = new Uri(AuthenticationUrl + scheme);
                var callbackUrl = new Uri("myapp://");
                result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);

                AuthToken = string.Empty;

                if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
                {
                    AuthToken += $"Name: {name}{Environment.NewLine}";
                }

                if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
                {
                    AuthToken += $"Email: {email}{Environment.NewLine}";
                }

                AuthToken += result?.AccessToken ?? result?.IdToken;
                IsAuthenticated = true;
            }
            catch (Exception ex)
            {
                AuthToken = string.Empty;
            }
        }
    }

Also I have some back-end code. All this works fine, I'm getting access token, UserId and so on.
But I still have some questions.
What is the right way to validate if login is still valid?
How should I authorize app actions?
And how could I implement Logout?
I will be grateful for advices or links.

A: As a user, you don’t want to have to sign in every time you use the app. Luckily, MSAL already caches your authorization and can log you in silently if it’s still valid.When properly authenticated we receive an access token that we can subsequently use to query other APIs that are secured by MSAL.
Signing out is pretty straight forward. We go through all the available accounts that MSAL has locally cached for us and sign them out. We also clear the access token that we stored in secure storage when we signed in.
public async Task<bool> SignOutAsync()
{
  try
  {
    var accounts = await _pca.GetAccountsAsync();

    // Go through all accounts and remove them.
    while (accounts.Any())
    {
        await _pca.RemoveAsync(accounts.FirstOrDefault());
        accounts = await _pca.GetAccountsAsync();
    }

    // Clear our access token from secure storage.
    SecureStorage.Remove("AccessToken");

    return true;
  }
  catch (Exception ex)
  {
    Debug.WriteLine(ex.ToString());
    return false;
  }
}


Q: HTTP header weird field explanation If you look on the response header of the http://www.yale.edu, there is a field such as
Expires: Sun, 19 Nov 1978 05:00:00 GMT.

What does it stand for?
If you want to look at it yourself, just type in terminal
 curl -I http://www.yale.edu

A:
A couple of years back, this was the main way of specifying when assets expires. Expires is simply a basic date-time stamp. It’s fairly useful for old user agents which still roam unchartered territories. It is however important to note that cache-control headers, max-age and s-maxage still take precedence on most modern systems. It’s however good practice to set matching values here for the sake of compatibility. It’s also important to ensure you format the date properly or it might be considered as expired.

taken from here
After that the response is no longer cached. See here
Also worth to look at


Q: How to get a box to drop down and show links when clicked on? I have 6 boxes that are corresponding to different facets of IT. For example, if I click on a box that is based on CyberSecurity, how do I make it to where there are 3 links that will drop down from the box and shows 3 more branches of CyberSecurity? Would this have more to do with CSS/HTML? As you can tell I have not done something like this before.

A: Is this in the navigation? It is possible to use managed metadata in order to create a drop down list. I'm using it in my current project. I created a term set in term-set management corresponding to the hierarchy of organization, set it as "use for navigation" then selected it under the navigation options in site settings.
Use managed metadata then select term store.
Hope that helps.


Q: Using VBScript how can I check if the Spooler service is started and if not start it? I'd like to use VBScript to check if the Spooler service is started and if not start it, the code below checks the service status but I need some help modifying this so I can check if it is started.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service")
For Each objService in colRunningServices
    Wscript.Echo objService.DisplayName  & VbTab & objService.State
Next

Many thanks
Steven

A: How about something like this. This command will start it if it isn't already running. No need to check in advance.
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run "NET START spooler", 1, false

A: strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colRunningServices = objWMIService.ExecQuery _
    ("select State from Win32_Service where Name = 'Spooler'")

For Each objService in colRunningServices
    If objService.State <> "Running" Then
        errReturn = objService.StartService()
    End If
Next

Note you can also use objService.started to check if its started.

A: Just for the completeless, here's an alternative variant using the Shell.Application object:
Const strServiceName = "Spooler"

Set oShell = CreateObject("Shell.Application")
If Not oShell.IsServiceRunning(strServiceName) Then
  oShell.ServiceStart strServiceName, False
End If

Or simply:
Set oShell = CreateObject("Shell.Application")
oShell.ServiceStart "Spooler", False    ''# This returns False if the service is already running


Q: If $f: U \to X$ is an atlas for a stack, and $f$ is an open immersion, is $X$ a scheme? Suppose that $X$ is a stack over the category of schemes which has the representable diagonal. If $X$ admits a surjection $f$ from a scheme $U$ which is also an open immersion (all pullbacks of $f$ are open immersions), then is $X$ a scheme?
For any $\phi : V \to X$ a morphism from a scheme, the pullback of $f$ is an isomorphism. I'd like to be able to conclude that $f$ is an isomorphism or equivalence of categories. Therefore, I am also asking the following question: if $f: X \to Y$ is a representable morphism of stacks, can the properties of $f$ to (isomorphism, equivalence, ...) be checked by base changing to some (sufficiently good / big) atlas $u : U \to Y$?
The moral question is - what properties of morphisms of stacks can be checked scheme-locally on the target?
I'm asking this because I'm trying to understand better the definition of Deligne-Mumford and Artin stacks, and it seems like asking the atlas to be an open immersion would be a reasonable way to strengthen the definition (and maybe get something uninteresting). (On the other end of the spectrum of Grothendieck topologies, what about asking for a f.p.p.f. atlas?)
I know the following: If  $f : X \to Y$ is a morphism of schemes, and we know that for every affine subscheme $u : U \to Y$, the pullback of $f$ to $X \times U \to U$ is an isomorphism, then is $f$ an isomorphism. This is because inverses are unique and so can be glued together, but in the case of an equivalence of categories / with stacks, I am less sure.


Q: Validating a password with c++ and giving specific errors I am trying to write a c++ program that validates a password that requires one uppercase letter, one lowercase letter, and a digit using functions.
The issue is that I'm trying to display the specific errors that are occurring, not just "Invalid, try again.", but I'm having a hard time figuring out how to do that. It should keep asking until they enter a valid password.
#include<iostream>
#include<string>
#include<cctype>

using namespace std;

int validate(string);
string find(int);

int main()
{
    string pw;
    int val;
    string result;

    do{
            cout << "Enter password: " << endl;
            cin >> pw;
            val = validate(pw);
            cout << find(val) << endl;

      } while (val != 0);

}
//VALIDATES PASSWORD
int validate(string pw)
{
    int valid = 0;
    char c;
    int length = pw.length();
    bool digit = false;
    bool upper = false;
    bool lower = false;

    int i = 0;

    if (pw.length() < 6)
        valid = 1;

    while (i < pw.length())
    {
        c = pw[i];
        i++;

        if (isdigit(c))
        {
            digit = true;
            valid++;
        }
        if (isupper(c))
        {
            upper = true;
            valid++;
        }
        if (islower(c))
        {
            lower = true;
            valid++;
        }

        //Valid input
        if (length >= 6 && upper && lower && digit)
            valid = 0;

}

return valid;

}
//RETURNS STRING WITH PROBLEM
string find(int valid)
{

    string result;

    if (valid == 0)
    {
        result = "Valid Password ";
    }
    else
    {
        result = "Invalid Password: ";

        if (valid == 1)
            result = result + " Too short ";
        else if (valid == 2)
            result = result + " too short, needs a digit, and an uppercase letter";
        else if (valid == 3)
            result = result + " too short, needs a digit, and a lowercase letter";
        else if (valid == 4)
            result = result + " too short, and needs an uppercase letter";
        else if (valid == 5)
            result = result + " too short, and needs a lowercase letter";
        else if (valid == 6)
            result = result + " too short, needs a digit";

        else if (valid == 7)
            result = result + " Needs a didgit ";
        else if (valid == 8)
            result = result + " Needs digit and uppercase letter ";
        else if (valid == 9)
            result = result + " Needs digit and lowercase letter";

        else if (valid == 10)
            result = result + " Needs an uppercase letter ";
        else if (valid == 11)
            result = result + " Needs uppercase and lowercase letter";

        else if (valid == 12)
            result = result + " Needs a lowercase letter";

    }

    return result;
}

A: I think you are confusing the number of characters (valid) and the type of error -
else if (valid == 9)
    result = result + " Needs digit and lowercase letter";

could be produced from 123456abc
As valid == 9 really only counts the characters in the set.  Separate counting and whether character classes are used.

A: It's better to use some flags (bool variables) instead of one number.
If you want to use one number, you must create 2^(things to check) situations
using that number. Here 2^4 = 16 situations is required.
One of the easiest way to mix flags in one number is this:
nth digit = nth flag
for example use this order (length, lower, upper, digit).
So,
to set length validity, add 1000 to number;
to set lower validity, add 100 to number;
to set upper validity, add 10 to number;
to set digit validity, add 1 to number;

Now,
((number)%10 == 1)  means digit validity
((number/10)%10 == 1)  means upper validity
((number/100)%10 == 1)  means lower validity
((number/1000)%10 == 1)  means length validity

Following code uses separate flags:
#include<iostream>
#include<string>

using namespace std;

class PasswordStatus
{
    bool len, low, up, dig;
    //============
public:
    PasswordStatus()
    {
        len = low = up = dig = false;
    }
    //-----------
    void ShowStatus()
    {
        cout << endl << "Password Status:" << endl;
        cout << "Length : " << (len ? "OK" : "Too Short") << endl;
        cout << "Contains Lower Case : " << (low ? "Yes" : "No") << endl;
        cout << "Contains Upper Case : " << (up ? "Yes" : "No") << endl;
        cout << "Contains Digit : " << (dig ? "Yes" : "No") << endl;
    }
    //-----------
    void checkValidity(string pass)
    {
        int sLen = pass.length();

        len = (sLen >= 6);

        for(int i = 0; i<sLen; i++)
        {
            char c = pass[i];

            if(!low && islower(c)) {low = true; continue;}
            if(!up && isupper(c)) {up = true; continue;}
            if(!dig && isdigit(c)) {dig = true; continue;}
        }
    }
    //-----------
    bool IsTotalyValid()
    {
        return low && up && dig && len;
    }
};
//====================================================================
int main()
{
    PasswordStatus ps;
    string pw;

    do
    {
        cout << endl << "Enter password: " << endl;

        cin >> pw;

        ps.checkValidity(pw);
        ps.ShowStatus();
    } while (!ps.IsTotalyValid());

    cout << "Valid Password : " << pw;
    return 0;
}


Q: Integrals of orthogonal polynomials and combinatorics A beautiful result due to Evans and Gillis is that the function
$$A(n_1,n_2,\cdots,n_r)=\int_0^\infty L_{n_1}(x)L_{n_2}(x)\cdots L_{n_r}(x)e^{-x}dx$$
counts the number of generalized derangements (up to a sign, I believe). Here, $L_{n}(x)$ is a Laguerre polynomial There's a nice application of it here. For example the usual derangements are counted by:
$$(-1)^n\int_0^\infty L_1^n(x)e^{-x}dx.$$
Messing around with Mathematica, it seems like one can try using other polynomials with their respective weights to produce integer valued $A(n_1,n_2,\cdots,n_r)$. For example, Hermite Polynomials:
$$\int_{-\infty}^\infty H_{n_1}(x)\cdots H_{n_r}(x)e^{-x^2}dx$$
which tends to give either an integer, or an integer multiple of $\sqrt{\pi}$. For example:
$$\int_{-\infty}^\infty H_{1}(x)H_{2}(x)H_{3}(x)H_{4}(x)e^{-x^2}dx=4224\sqrt{\pi},$$
$$\int_{-\infty}^\infty H_{1}(x)H_{2}(x)H_{3}(x)H_{5}(x)e^{-x^2}dx=19776.$$
$H_1(x)=2x$ is the simplest case and
$$\frac{(2n)!}{n!}=\frac{1}{\sqrt{\pi}}\int_{-\infty}^\infty H_1(x)^{2n}e^{-x^2}dx,$$
which corresponds to this OEIS sequence. The only permutation related thing on that sequence is a "downgrade permutation" which is a permutation that sends another permutation to a descending sequence. Then this integral counts the number of self-downgrade permutations. This seems semi-promising as it's some kind of order-derangement condition.
I didn't have much luck with Jacobi polynomials, which gave rational numbers.
So here's a general question. Has this kind of phenomena, as in the case of Laguerre polynomials, been studied for other families? In other words, for a family of orthogonal polynomials $P_n(x)$, with orthogonality weight $w(x)$ on a space $A$, is there a combinatorial interpretation for:
$$\int_A P_{n_1}(x)\cdots P_{n_r}(x)w(x)dx?$$
Are there any references on this? As far as I'm aware, Askey was able to reprove Evan's and Gillis result using analytic techniques (Evan's proof was actually combinatorial).
Naively, all orthogonal polynomials fall into some category of the Askey Scheme, meaning that really these identities are somehow connected to the right set of hypergeometric functions and their weights. Unfortunately, that's not exactly illuminating.


Q: How to generate breadcrumbs when I have a following category structure I have a following nested categories structure array and now I need to generate breadcrumbs for each category. Suppose I am currently viewing the Adidas category page which is in Brands->Apparel->Adidas so I need breadcrumbs like this Brands/Apparel/Adidas.
Categories array structure follows:
[1] => Array
(
    [name] => 01e3f447-4b81-11e7-a858-b8763f541038
    [nodeInfo] => stdClass Object
        (
            [idCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
            [category] => Brands
            [slug] => brands
            [description] =>
            [image] =>
            [parentCategory] =>
            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
            [date] => 2017-06-07 14:58:31
        )

    [children] => Array
        (
            [0] => Array
                (
                    [name] => 0ded5b28-4b81-11e7-a858-b8763f541038
                    [nodeInfo] => stdClass Object
                        (
                            [idCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
                            [category] => Apparel
                            [slug] => apparel
                            [description] =>
                            [image] =>
                            [parentCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                            [date] => 2017-06-07 14:58:51
                        )

                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [name] => 3681265e-4b81-11e7-a858-b8763f541038
                                    [nodeInfo] => stdClass Object
                                        (
                                            [idCategory] => 3681265e-4b81-11e7-a858-b8763f541038
                                            [category] => Adidas
                                            [slug] => adidas
                                            [description] =>
                                            [image] =>
                                            [parentCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
                                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                                            [date] => 2017-06-07 14:59:59
                                        )

                                    [children] =>
                                )

                            [1] => Array
                                (
                                    [name] => 3f211015-4b81-11e7-a858-b8763f541038
                                    [nodeInfo] => stdClass Object
                                        (
                                            [idCategory] => 3f211015-4b81-11e7-a858-b8763f541038
                                            [category] => Columbia
                                            [slug] => columbia
                                            [description] =>
                                            [image] =>
                                            [parentCategory] => 0ded5b28-4b81-11e7-a858-b8763f541038
                                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                                            [date] => 2017-06-07 15:00:14
                                        )

                                    [children] =>
                                )

                        )

                )

            [1] => Array
                (
                    [name] => 1988d10a-4b81-11e7-a858-b8763f541038
                    [nodeInfo] => stdClass Object
                        (
                            [idCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
                            [category] => Footwear
                            [slug] => footwear
                            [description] =>
                            [image] =>
                            [parentCategory] => 01e3f447-4b81-11e7-a858-b8763f541038
                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                            [date] => 2017-06-07 14:59:11
                        )

                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [name] => 49becbc8-4b81-11e7-a858-b8763f541038
                                    [nodeInfo] => stdClass Object
                                        (
                                            [idCategory] => 49becbc8-4b81-11e7-a858-b8763f541038
                                            [category] => Polo
                                            [slug] => polo
                                            [description] =>
                                            [image] =>
                                            [parentCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
                                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                                            [date] => 2017-06-07 15:00:31
                                        )

                                    [children] =>
                                )

                            [1] => Array
                                (
                                    [name] => 4e647bee-4b81-11e7-a858-b8763f541038
                                    [nodeInfo] => stdClass Object
                                        (
                                            [idCategory] => 4e647bee-4b81-11e7-a858-b8763f541038
                                            [category] => Nike
                                            [slug] => nike
                                            [description] =>
                                            [image] =>
                                            [parentCategory] => 1988d10a-4b81-11e7-a858-b8763f541038
                                            [idStatus] => e9d3b949-1301-11e7-a9b8-b8763f541038
                                            [date] => 2017-06-07 15:00:39
                                        )

                                    [children] =>
                                )

                        )

                )

        )

)


Q: How do I avoid having the database password stored in plaintext in sourcecode? In the web-application I'm developing I currently use a naive solution when connecting to the database:
Connection c = DriverManager.getConnection("url", "username", "password");

This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?

A: In .NET, the convention is to store connectionstrings in a separate config file.
Thereon, the config file can be encrypted.
If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.

A: You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html

A: I can recommend these techniques for .NET programmers:

*

*Encrypt password\connection string in config file

*Setup trusted connection between client and server (i.e. use windows auth, etc)

Here is useful articles from CodeProject:

*

*Encrypt and Decrypt of ConnectionString in app.config and/or web.config

A: Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.
Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.
Also, never give priviliges to the db account over or above what is essentially needed.
An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.

A: Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code.  Otherwise I would have to agree with the other posters recommending app.config + encryption.

A: *

*Create an O/S user

*Put the password in an O/S environment variable for that user

*Run the program as that user

Advantages:

*

*Only root or that user can view that user's O/S environment variables

*Survives reboot

*You never accidentally check password in to source control

*You don't need to worry about screwing up file permissions

*You don't need to worry about where you store an encryption key

*Works x-platform


Q: Oracle Apex instance setting on Oracle Cloud I have this error while trying to upload file in my oracle apex application on oracle cloud:

The instance does not allow unauthenticated users to upload files.

I login into the admin console to allow users to upload files but I don't see the security tab?
environmment:
Host:  oracle cloud
DB  :  18c
APEX : Application Express 19.1.0.00.15

A: This document addresses issues on what you can, or rather, cannot do as Instance Administrators. You are permitted to change what you have access to the web UI and SMTP parameters using the APEX_INSTANCE_ADMIN package.


Q: How do I display a bash prompt when using SSH without a pseudo-terminal? When the connection is slow, I connect to remote computers using SSH without allocating a pseudo-terminal (e.g. ssh -T user@example.com or ssh user@example.com bash). Although I am able to use the shell, the shell does not display a prompt. Is there a way to make the shell display a prompt (e.g. $ ) when connecting via SSH without a pseudo-terminal?
I could run the bash script below on the remote computer, but I'm wondering if there is something built-in that I can use to get a prompt.
#!/bin/bash
# or #!/bin/sh

PS='$ '

prompt() {
    printf '%s' "$PS"
    read -r line
    # Exit if EOF (Ctrl-d).
    [ "$?" -ne 0 ] && echo && exit
    eval "$line"
}

# Handle Ctrl-c.
trap 'echo && prompt' INT

while :
do
    prompt
done

(Adapted based on: https://tldp.org/LDP/abs/html/intandnonint.html)
This script has the disadvantage that it is not able to handle multi-line inputs.

A: It obviously does not solve all problems which result from the missing tty but you can do this:
ssh -T user@example.com bash -i


Q: Question on meromorphic functions I'm trying to do this optative exercise from my complex analysis course:

Check if series $$\sum_{k=-\infty}^{\infty}\left(\frac{1}{z-\pi k}\right)^2$$ converges for all $z\in \mathbb{C}$ to a meromorphic function $f_1(z)$, so that if we consider the function $$f(z)=\frac{1}{\sin^2 z}$$ then $g(z)=f(z)-f_1(z)$ is an entire function.

This exercise is way harder than the previous ones I've done and don't know how to approach it. I don't know if I should find $f_1(z)$ first or there's a way to prove the result without finding it.
Thanks for the time and suggestions.

A: Sketch for the proof: you need to check two things:

*

*That $\sum_{k=-\infty}^{\infty}\frac1{(z-\pi k)^2}$ converges local uniformly in $\mathbb{C}\setminus \pi \mathbb{Z}$ and that it is differentiable (that is, you need to show that the series defines a holomorphic function in $\mathbb{C}\setminus \pi \mathbb{Z}$).

*That $\lim_{z\to w}\left(\sum_{k=-\infty}^{\infty}\frac1{(z-\pi k)^2}-\frac1{\sin ^2 z}\right)\in \mathbb{C}$ for every $w\in \pi \mathbb{Z}$.

For the first point above you can notice that
$$
\frac{d}{d z}\sum_{k=-\infty}^{\infty}\frac1{(z-\pi k)^2}=\sum_{k=-\infty}^{\infty}\frac{d}{d z}\frac1{(z-\pi k)^2}
$$
as the RHS converges locally uniformly for any chosen $z\in \mathbb{C}\setminus \pi \mathbb{Z}$. To show the second point above, as the series $\sum_{k=-\infty}^{\infty}\frac1{(z-\pi k)^2}$ defines a $\pi$-periodic function, it is enough to show that
$$
\lim_{z\to 0}\left(\frac1{z^2}-\frac1{\sin ^2 z}\right)\in \mathbb{C}
$$


Q: Do the spawn chunks stay loaded across dimensions? Do the spawn chunks stay loaded across dimensions?
If I'm in the Nether or The End for examples, do farms in the spawn chunks stay running?

A: They do stay loaded. But unfortunately farms will not work.

All entity updates and block entity ticks in a dimension are no longer processed 15 seconds after the last player leaves the dimension. Thus, while the spawn chunks remain loaded, most activity ceases when no players are in the Overworld.

Source, Minecraft wiki.


Q: Ruby on Rails friendly_id, babosa гемы, проблема с транслитерацией Использую гемы friendly_id,babosa.
Модель models/product.rb:
class Product < ActiveRecord::Base
   extend FriendlyId
   friendly_id :name, use: [:slugged, :finders]
   has_many :tags

   def normalize_friendly_id(input)
    input.to_s.to_slug.normalize(transliterations: :russian).to_s
   end

end

Запускаю консоль, чтобы заполнить slug поле уже имеющихся строк:
Product.find_each(&:save)

Проверяю последний товар:
Product.last

#<Product id: 4972, name: "ВА 47-63, 2P 2А (C) EKF", created_at: "2016-01-27 11:32:39", updated_at: "2016-01-27 11:32:39", slug: 04b4aa2d-2bb9-46f9-8d49-cbb9d0c3f872">

Как можно увидеть, слаг сгенерировался без транслитерации, плюс непонятный хвост.
Пробую вручную выполнить в консоли:
"ВА 47-63, 2P 2А (C) EKF".to_s.to_slug.normalize(transliterations: :russian).to_s
=> "va-47-63-2p-2a-c-ekf"

На выводе адекватная транслитерация соответствующая ожиданиям.
Не могу понять почему в консоли транслитерация норм, а через normalize_friendly_id кривая. Я новичок, поэтому мог что то просто не сделать, хотя делал всё по мануалам.
Таким же образом делал транслитерацю для тегов, она получилась адекватной.
models/tag.rb
class Tag < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders]
  belongs_to :product

  def normalize_friendly_id(input)
   input.to_s.to_slug.normalize(transliterations: :russian).to_s
  end
end


Q: Loading page content and its CSS dynamically - how to prevent jump because CSS is not loaded yet? On my website, I catch clicks on links to load the content of that page dynamically using AJAX. This new content may require some CSS file that isn't loaded yet. Setting the content of the target element to the response HTML will automatically load the required CSS (the <link> tags are there), but the content will look messed up for a brief period until the CSS gets loaded.
Other than loading all CSS files in advance, what can I do to prevent this? For completeness sake, here is my code:
$(document).ready(function() {

    $('a').live('click', function(event) {
        if (this.target || this.rel == 'ignore' || this.rel == 'fancybox') {
            return true;
        }

        if (/^javascript:/.test(this.href)) {
            return true;
        }

        if (this.href.indexOf('#') >= 0) {
            return false;
        }

        if (!this.href) {
            return true;
        }

        loadDynamicPage(this.href);
        event.preventDefault();
        return false;
    });
});

var currentLoader = null;
function loadDynamicPage(url) {
    if (currentLoader) {
        currentLoader.abort();
        currentLoader = null;
    }

    $('#backButton').addClass('loaderBG');
    currentLoader = $.ajax({
        context: $('#army_content'),
        dataType: 'text',
        url: url + '&format=raw',
        success: function(data) {
            currentLoader = null;
            $('#backButton').removeClass('loaderBG');
            clearRoomIntervals();

            $(this).html(data).find('[title]').tooltip({
                showURL: false,
                track: false,
                delay: 300
            });

            $(document).trigger('dynamicLoad');
        }
    });
}

A: *

*Click on the link, show "Loading.."

*Load CSS file by ajax, in callback function, create <style> tag, and then insert CSS code to <style> tag, and then start load content by ajax.

*you can optimize the flow by load CSS and content individually, but content only take place in a hidden container, once CSS file finish load, then change hidden container to be shown.
Hope it helps.


Q: Narrow TVS margin between operating and overvoltage Devices like the PIC16F18323 have an extremely narrow margin on I/O pins. The standard logic-high voltage level is 5V, but the absolute maximum is Vcc+0.3V, i.e. 5.3V.
Reading about TVS devices, in particular those offered on DigiKey, for a diode whose Vwm is 5V, the lowest clamping voltage I can find is 7.5V for the 1N6373. I can assume that by that point my I/O port will be destroyed.
So what gives? Should I be using a TVS diode with a lower Vwm and have it already in avalanche when the device is under normal conditions? Or just cross my fingers with a diode whose avalanche and clamping voltages are significantly above what the pin will tolerate?

A: The reason why the absolute maximum Vcc on the pins is Vcc+0.3V is because above that voltage, the internal clamp diode to Vcc will turn on -- as long as there's a series resistor between the I/O pin and outside world to limit that current to what the clamp diode can handle, it will not permanently harm the IC.  (Modern datasheets give an Iik, Iok, or Ik specification for this maximum current.)
So, use the higher clamping voltage TVS to absorb the bulk of the energy and a series resistor to keep the port pin's clamp diode from being burned out.

A: The usual way of protecting I/O pins with narrow margins (and pin injection currents in the order of 5mA usually) is with a resistor and perhaps an external clamp schottky:

simulate this circuit – Schematic created using CircuitLab
The reason for the 0.3V is usually that there is a schottky internally, but it cannot handle much current; adding one (or two for bidirectional protection) that can handle the current due to a voltage excursion event is a simple and effective means of protecting the pins. The resistor limits the current in the schottky and therefore maintains \$V_f\$ at a nice low voltage.
TVS devices have wide variations of turn-on voltage, full clamping voltage and those parameters are also thermally dependent, making them unsuitable for protecting I/O pins in  this particular case.
In the case of I/O pins with schottky devices and a rated pin injetion current (usually the maximum sustained current the internal schottky can handle) a simple resistor can suffice if the maximum voltage can be defined.
Typical arrays for mult-line protection can be found at some manufacturers
Note that if you expect a high voltage (too fast even for a front end TVS as JonRB alludes to - some have slow reaction times) you may want to use pulse-withstanding resistors. These maintain their resistance even after a large transient event; standard resistors may not.

A: You need to choose a TVS that has a working voltage greater or equal to the maximum normal voltage you will see.
This means performing some tolerance analysis with regards to the supply & expected IO (5V could potentially be 5.25).
Take a littelfuse part ( 1.5SMC series) a 5.8V working has a min & max breakdown of 6.45 --> 7.14V & this could RISE to 10.5V (depending on the avalanche current). All this would imply that you are unable to use these devices right on the inputs.
Except you do not need to just use a TVS.  Additional steering diodes right at the IC in question will clamp the I/O to Vcc+0.3 (schottky used). Additional input L-C will again reduce what the actual pin will see

simulate this circuit – Schematic created using CircuitLab
A strike (indirect lighting or ESD) is a short duration waveform and thus "waveform shaping" is a viable option to ensure the IC IO does not exceed its maximum rating & other components do not exceed their current or power rating


Q: OpenCV, can't release CAP_OPENCV_MJPEG VideoWriter for long records Hi stackoverflow community,
I recently had a problem with the performance of the opencv VideoWriter (see here), and I am now using cv::CAP_OPENCV_MJPEG as a backend instead of cv::CAP_FFMPEG.
Now I am running in another issue, so my code looks like this:
cv::VideoWriter videoWriter(path, cv::CAP_OPENCV_MJPEG, fourcc, fps, *size);
videoWriter.set(cv::VIDEOWRITER_PROP_QUALITY, 100);

int id = metaDataWriter.insertNow(path);

while (this->isRunning) {

    while (!this->stackFrames.empty()) {

        cv:Mat m = this->stackFrames.pop();

        videoWriter << m;
    }

}

videoWriter.release();

This loop runs in a separate thread and "isRunning" will be switched from outside. There is a stack with cv::Mat (stackFrames) which is filled by another thread that captures the images by a video capture card. This works fine, but if the file size is too big, several GB, I get the following error when the videoWriter.release() is called:

terminate called after throwing an instance of 'cv::Exception'
what():  OpenCV(4.4.0) /home/michael-gary/opencv/opencv/modules/videoio/src/container_avi.cpp:27: error: (-211:One of the arguments' values is out of range) Failed to write AVI file: chunk size is out of bounds in function 'safe_int_cast'

I tried to change the video container from .avi to .mkv, .mp4, .mpg but none of them is working, it does not even create the file. Only .avi is working, but fails by the release.
For now I will try to write multiple files, so I don't run in this problem, but I would like to face the problem itself.
Open for any suggestions
BR Michael

A: AVI files are practically limited in size.
when you force it to use OPENCV_MJPEG, it will only use OpenCV's own writing methods, which can only do AVI and MJPEG.
if you need a different container, you have to use a different backend, such as FFMPEG. you can still have MJPG for a codec (fourcc).


Q: Fastest Algorithm for NLP with linear constraints I have an minimization problem of the following form:
(Im not a mathematician, i come from the programming side, so excuse me if i have not the perfect standard of writing the formulas)
$Z(x) = \sqrt[2]{x_1^2 \cdot a_1+...+x_n^2 \cdot a_n} + x_1 \cdot b_1+...+x_n \cdot b_n$
with the constraints:
(1) $\sum_{i=1}^n{x_i} =1$
(2) $0<x_i<=c_i \ \text{with} \ c = \{c_1,..,c_n\}$
Im interested in an algorithm that finds a local minimum as fast as possible, since i want to implement it.
I have already read a lot of stuff with different approaches for different type of constraints, but they mostly didnt fit or where hard to understand, so i could not be sure if they fit.
I understand that this is a NLP with linear constraints, but since im pretty new to NLP i hope for someone with more experience who can help me.
Thank you!

A: If the $a_i$ values are negative, all bets are off; it is a non-convex problem. But if the $a_i$ values are nonnegative, this is a convex problem, and therefore it is tractable. In fact, it can easily be converted to a second-order cone program, or SOCP, which is a relatively well known modern standard form for convex optimization.
To convert to a "standard" SOCP, define $\bar{a}_i=\sqrt{a}_i$, and create a new variable $y\in\mathbb{R}$. Then this problem is equivalent to
$$\begin{array}{ll}
\text{minimize}   & \sum_i b_i x + y \\
\text{subject to} & \sqrt{\textstyle \sum_i (\bar{a}_i x_i)^2 } \leq y \\
& \sum_i x_i = 1 \\
& 0 \leq x_i \leq c_i, ~ i=1,2,\dots,n
\end{array}$$
The key here is that the objective is linear, and the constraints are composed of linear equations and inequalities, and convex constraints involving norms. No other types of nonlinearities are permitted in an SOCP other than convex $\ell_2$-norm constraints.
Here is a good online resource on convex optimization, with a section on second-order cone programming. There are a variety of solvers out there that can solve SOCPs. If you don't mind me offering my own software, the MATLAB-based modeling framework CVX can handle this quite readily; you don't even need to do the SOCP conversion. Here would be the model in CVX, that assumes the values of $a_i$, $b_i$, and $c_i$ are stored in MATLAB vectors a, b, and c:
cvx_begin
    variable x(n)
    minimize( norm(sqrt(a).*x) + b'*x )
    subject to
        sum(x) == 1;
        0 <= x <= c;
cvx_end

CVX will certainly not give you the fastest results; it is meant to make problems easy to specify. But you can worry about speed after you're satisfied with the results.

A: First, a couple minor points. I'm assuming $a_i > 0$ so the problem is convex, and $\sum_{i=1}^n c_i \ge 1$, so the problem is feasible. Also, there is no guarantee that there will be a minimum with $x_i$ strictly positive, so the constraints should be $0 \le x_i \le c_i$. If it's unacceptable in your application for the $x_i$ to be zero, then you should specify some minimum nonzero value for them.
While I'm not sure what the best algorithm for this problem would be, here's at least a partial solution. For this particular problem, you can almost find a closed form solution. That is, you can reduce it to searching over 2 parameters.
Let $C$ be the feasible region (intersection of a box and a plane):
$$
C := \{ \mathbf{x} \in \mathbb{R}^n \ \mid \ 0 \le x_i \le c_i, \ \sum_{i=1}^n x_i =1 \}
$$
In this particular case, it's relatively easy to project onto $C$. By introducing another parameter, you can see that the optimal $\mathbf{x}$ will be a (scaled) projection onto $C$. This uses the standard trick that $\sqrt{w} = \min_{s>0} \frac{s}{2} + \frac{w}{2s}$.
$$
\begin{aligned}
\min_{\mathbf{x} \in C} \sqrt{ \sum_{i=1}^n a_i x_i^2} + \sum_{i=1}^n b_i x_i
&= \min_{\mathbf{x} \in C} \min_{s > 0} \frac{s}{2}+ \frac{1}{2s}\sum_{i=1}^n a_i x_i^2 + \sum_{i=1}^n b_i x_i\\
&= \min_{s > 0} \frac{s}{2} +\frac{1}{2s} \left(\min_{\mathbf{x} \in C}\sum_{i=1}^n a_i x_i^2 +  2 s b_i x_i \right) \\
&= \min_{s > 0} \frac{s}{2}\left(1 - \sum_{i=1}^n b_i^2 a_i^{-1} \right) +\frac{1}{2s} \left(\min_{\mathbf{x} \in C}\sum_{i=1}^n a_i (x_i +   s b_i a_i^{-1})^2 \right)
\end{aligned}
$$
I'll skip the derivation of the formula for the scaled projection onto $C$, but it ends up being the following. Define $\mathbf{y}(s,t)$ by:
$$
y_i(s,t) := \max(0,\min(c_i,(t-b_i s)/a_i))
$$
Then the optimal solution to the problem is $\mathbf{x}^* = \mathbf{y}(s^*,t^*)$, where the optimal parameters $s^*$ and $t^*$ are chosen to satisfy:
$$
\begin{gathered}
\sum_{i=1}^n y_i(s^*,t^*) = 1\\
\sqrt{\sum_{i=1}^n a_i y_i(s^*,t^*)^2} = s^*
\end{gathered}
$$
So then the problem reduces to finding $s^*$ and $t^*$. For fixed $s$, you can solve for $t$ which satisfies $\sum_{i=1}^n y_i(s,t) = 1$ in $O(n)$ time. This paper has the case for the unit simplex, see the references on the linked page for the general case.
Unfortunately, I'm not sure what the best approach is for finding both $s^*$ and $t^*$, though I'd expect somewhere in the CS literature there's an algorithm with this problem as a special case which is runs in $O(n)$ or $O(n^2)$ time. If you just want to use a simple bisection approach, you can use the following bounds to get your starting iterations:
$$
\begin{gathered}
\min_i \sqrt{a_i} \le s^* \le \max_i \sqrt{a_i} \\
\min_i b_i s^* \le t^* \le \max_i b_i s^* + c_i
\end{gathered}
$$


Q: Showing Multiplicative Inverses of Polynomials of Algebraic Elements Are Also Polynomials
*

*Let $E$ be a field extension of $F$.

*Let $\alpha \in E$ be algebraic over $F$.

*Consider $a_0 + a_1 \alpha + \ldots + a_{n} \alpha^n = f(\alpha) \in F[\alpha]$.

How can I show that $\frac{1}{a_0 + a_1 \alpha + \ldots + a_{n} \alpha^n} \in F[\alpha]$?
I have tried to think about the simpler case of just showing that $1/\alpha \in F[\alpha]$ but haven't been able to come up with anything.  I feel like I'm missing something really obvious.

A: Hint:
Let $\;f(x)=a_0+a_1x+\ldots+a_{n-1}x^{n-1}+x^n\;$ be the minimal polynomial of $\;\alpha\neq 0\;$ over $\;\Bbb F\;$ . Then $\;a_0\neq 0\;$ (why?) and also
$$a_0+a_1\alpha+\ldots+\alpha^n=0\implies a_0\alpha^{-1}+a_1+\ldots+ \alpha^{n-1}=0\implies$$
$$\alpha^{-1}=-\frac1{a_0}\left(a_1+a_2\alpha+\ldots+\alpha^{n-1}\right)\in\Bbb F[\alpha]$$

A: This follows from the fact that if $F$ is a field then $F[x]$ is a Euclidean domain with respect to the degree map.
Let $\beta = a_0 + a_1\alpha + ... + a_n\alpha^n\neq 0$ be the element we are interested in finding the inverse of. Then there is a corresponding polynomial $\beta(x) = a_0 + a_1 x + ... + a_n x^n$ in $F[x]$.
Let $m(x)$ be the minimal polynomial of $\alpha$ over $F$. Now we may assume the degree of $\beta(x)$ is less than the degree of $m(x)$ since if $\beta(x)$ contained higher powers of $\alpha$ we could use the minimal polynomial to replace these powers with smaller powers of $\alpha$.
Now the fact that $F[x]$ is a Euclidean domain, along with the fact that $\beta(x)$ and $m(x)$ must be coprime ($m(x)$ is irreducible and $\beta(\alpha)\neq 0$) tells us that there exist polynomials $a(x),b(x)\in F[x]$ such that:
$a(x)\beta(x) + b(x)m(x) = 1$.
Substituting $x=\alpha$ tells us that $a(\alpha)\beta = 1$ and so we have found our multiplicative inverse $a(\alpha)\in F[\alpha]$.


Q: Correct status code to send for an HTTP POST request where the given ID does not match an object in the database Lets say I have an endpoint in my API with the following URL:
www.example.com/api/create-order-for-restaurant/

Now, in my POST request, I send the following data:
{
    "restaurant_id": 43,
    "order": {...}
}

Lets say a restaurant with the id 43 does not exist in my database. What should be the appropriate HTTP status code that should be sent back to the client?
Im confused if I should be sending back 404 or 500.

A: This is a client error because the client specified a restaurant_id that didn't exist.
The default code for any client error is 400, and it would be fitting here too.
There are slightly more specific client error codes that might work well for this case, but it's not terribly important unless there is something a client can do with this information.

*

*422 - could be considered correct. The JSON is parsable, it just contains invalid information.

*409 - could be considered correct, if the client can create the restaurant with that specific id first. I assume that the server controls id's, so for that reason it's probably not right here.

So 400, 422 is fine. 500 is not. 500 implies that there's a server-side problem, but as far as I can tell you are describing a situation where the client used an incorrect restaurant_id.


Q: Line height in textarea (IE7) I have a textarea (fixed size), which is getting populated by some text which is then resized to fit (font changed).
The code below runs fine in Chrome, Firefox, etc, but not IE (versions 7/8/9, which it also has to).

In non-IE, the text gets resized and fits in the textares nicely, but in IE there is huge gaps between each line of the textarea.
I have tried setting line-height but it doesn't seem to work. I have read that it is todo with the height of the font, which would mean wrapping each line in a span and setting a negative top margin.
Any ideas greatly appreciated.
Code sample;
html

        <textarea readonly="readonly"
            cols="10"
            rows="5"
            class="messagetext"
            style="width:400px; border:none;height:100px;overflow-y:hidden; resize:none;color: #D31245;"
            >1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>

JS
$(function() {
    var while_counter = 1;
    var txt = $('textarea.messagetext');
    var font_size = txt.css('font-size').replace(/\D/g,'');
    var scHeight = txt.get(0).scrollHeight;
    var txtHeight = txt.height();
    while ( scHeight > (txtHeight+10) ) {
        font_size = (font_size - 1);
        txtHeight = (txtHeight + 15);
        while_counter = while_counter + 1;
    }

    var lines = txt.val().split('\n');
    var total_lines = lines.length;
    var span_width = $('#inner-text').width() - 5;
    var temp_span = $('#temp');
    // now calculate line wraps
    $.each(lines, function(){
        // temp write to hidden span
        temp_span.html(String(this));
        // check width
        if (temp_span.width() > 400) {
            total_lines = total_lines + 1;
        }
    });
    txt.css('font-size', font_size+'px');
    txt.height( (total_lines * font_size) + (total_lines * 1.14) + 10);
});

A: Copy below code in one html file and check in IE

    <textarea readonly="readonly"
        cols="10"
        rows="5"
        class="messagetext"
        style="width:400px; border:none;height:100px;overflow:hidden;resize:none;color: #D31245;"
        >1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>


Q: Angular Firestore - Get document ID as a property to use it again in an other function - Typescript So here is my code :
getOutfitsCollectionData(): Promise<any> {
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = outfitsRef.snapshotChanges().pipe(
        map(actions=>{
            return actions.map(a=>{
                const id = a.payload.doc.id;
                return id
            })
        })
    )
    let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })
    return outfitsID
}
}

When I do this part
let outfitsID =  allOutfits.forEach(outID=>{
        console.log(outID)
        return outID
    })

The console is giving me this :
console perfect
It's exactly what I want, I just want to rename the array and set it as the result of my function but every console.log I put under these lines doesn't do anything so it seems that every line under isn't doing anything.
If I'm not clear, tell me guys !
What I'm trying to do is get each documents id of my collection to use it in an other function on the same tab.
I think that it might be easier to create a service but I don't really know how to do it.
Please don't make me ban one more time, I'm just trying to learn ... It won't be really smart to send me to a really general subject.
I'm not just trying to have pro that give a code that works, I want to understand and get better.
Thanks for your help guys !
( BTW sorry for my bad English, I'm French :) )
So just a little edit :
I tried this code, I don't really understand why when I console.log allOutfits, I'm not getting the good value :
async getOutfitsCollectionData(){
    let outfitsRef = this.afStore.collection('outfits');
    let allOutfits = await outfitsRef.get().toPromise().then((step)=>{
        return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }
    })
})
.catch(err=>{
    console.log('Error getting outfits', err)
})
console.log(allOutfits)
return allOutfits
}

A: Problem lies in this code:
return step.forEach(doc=>{
        if (!doc.exists){
            console.log('Zut !')
        }else{
            console.log(doc.id)
            return doc.id
        }

step is a QuerySnapshot so you should access the documents using step.docs. The function forEach does not return you the the array, but returns undefined instead.
use map which actually returns the transformed data:
return steps.docs.map(doc => doc.id);

A: I've finished my app long time ago, but I think that might interest.
I finally decided to learn typescript lol.
You can't get a value of a promise since it's not return, that was what I was trying to do.
Just call your function and .then do what you want ^^.
By the way, I needed to map my data as said by Lim Shang Yi


Q: performance advantages of using bottle for routing? I started developing a web application based on the bottle web framework a couple of years ago.  I chose Bottle at that time because it was the easiest solution to get up and running fast, and I was just working on building a prototype of an idea I had.  Now, I have several thousand lines of code, and I'm looking to move into production-level solution.
At first I thought that I should move to a full stack framework such as django or web2py.  As I was moving that direction, I started just using various parts of other frameworks as I needed them.  For example, I implemented web2py's data access layer (DAL) so that I could run my application on google-app-engine, and now I'm looking to into using web2py's scheduler to manage jobs.  Then, I began to use cherrypy as a production-level webserver.  I tried the rocket server, but I was getting more errors with it, so I preferred cherrypy over rocket.
I started looking into rewrite my code to fully use web2py's full stack solution; however, the amount of time to rewrite my routing functions to fully move into web2py seems to be significant, and I really wasn't happy with the rocket server.
I really like the simplicity of Bottle, the way that Bottle uses decorator functions to map the routes to the functions, and also the philosophy of extensibility.
I want to know if there are any specific advantages in terms of performance in using Bottle to do routing, versus any of the full stack frameworks.
I appreciate anyone's advice on this!

A: According to this benchmark and others, Bottle performs significantly faster than some of its peers, which is worth taking into account when comparing web frameworks' performance:
1. wheezy.web........52,245 req/sec or  19 μs/req (48x)
2. Falcon............30,195 req/sec or  33 μs/req (28x)
3. Bottle............11,977 req/sec or  83 μs/req (11x)
4. webpy..............6,950 req/sec or 144 μs/req (6x)
5. Werkzeug...........6,837 req/sec or 146 μs/req (6x)
6. pyramid............4,035 req/sec or 248 μs/req (4x)
7. Flask..............3,300 req/sec or 303 μs/req (3x)
8. Pecan..............2,881 req/sec or 347 μs/req (3x)
9. django.............1,882 req/sec or 531 μs/req (2x)
10. CherryPy..........1,090 req/sec or 917 μs/req (1x)

But bear in mind that your web framework may not be your bottleneck.

A: From the creator of web2py, Massimo Di Pierro:

If you have simple app with lots of models, bottle+gluino may be
  faster than web2py because models are executed only once and not at
  every request.

Reference:
groups.google.com/forum/#!topic/web2py/4gB9mVPKmho


Q: How should you TDD a Yahtzee game? Let's say you're writing a Yahtzee game TDD style. You want to test the part of the code that determines whether or not a set of five die rolls is a full house. As far as I know, when doing TDD, you follow these principles:

*

*Write tests first

*Write the simplest thing possible that works

*Refine and refactor

So an initial test might look something like this:
public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 1, 1, 2, 2);

    Assert.IsTrue(actual);
}

When following the "Write the simplest thing possible that works", you should now write the IsFullHouse method like this:
public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    if (roll1 == 1 && roll2 == 1 && roll3 == 1 && roll4 == 2 && roll5 == 2)
    {
        return true;
    }

    return false;
}

This results in a green test but the implementation is incomplete.
Should you unit test every possible valid combination (both of values and positions) for a full house? That looks like the only way to be absolutely sure that your IsFullHouse code is completely tested and correct, but it also sounds quite insane to do that.
How would you unit test something like this?
Update
Erik and Kilian point out that using literals in the initial implementation to get a green test might not be the best idea. I'd like to explain why I did that and that explanation does not fit in a comment.
My practical experience with unit testing (especially using a TDD approach) is very limited. I remember watching a recording of Roy Osherove's TDD Masterclass on Tekpub. In one of the episodes he builds a String Calculator TDD style. The full specification of the String Calculator can be found here: http://osherove.com/tdd-kata-1/
He starts with a test like this:
public void Add_with_empty_string_should_return_zero()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("");

    Assert.AreEqual(0, result);
}

This results in this first implementation of the Add method:
public int Add(string input)
{
    return 0;
}

Then this test is added:
public void Add_with_one_number_string_should_return_number()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("1");

    Assert.AreEqual(1, result);
}

And the Add method is refactored:
public int Add(string input)
{
    if (input.Length == 0)
    {
        return 0;
    }

    return 1;
}

After each step Roy says "Write the simplest thing that will work".
So I thought I would give this approach a try when trying to do a TDD-style Yahtzee game.

A: Testing for five particular literal values in a particular combination is not "simplest" to my fevered brain. If the solution to a problem really is obvious (count whether you have exactly three and exactly two of any value), then by all means go ahead and code that solution, and write some tests that would be very, very unlikely to satisfy accidentally with the amount of code you wrote (i.e. different literals and different orders of the triples and doubles).
TDD maxims really are tools, not religious beliefs. Their point is to get you to write correct, well-factored code rapidly. If a maxim obviously stands in the way of that, just jump ahead go on to the next step. There will be plenty of non-obvious bits in your project where you can apply it.

A: Erik's answer is great, but I thought I might share a trick in test writing.
Start with this test:
[Test]
public void FullHouseReturnsTrue()
{
    var pairNum = AnyDiceValue();
    var trioNum = AnyDiceValue();

    Assert.That(sut.IsFullHouse(trioNum, pairNum, trioNum, pairNum, trioNum));
}

This test gets even better if you create a Roll class instead of passing 5 params:
[Test]
public void FullHouseReturnsTrue()
{
    var roll = AnyFullHouse();

    Assert.That(sut.IsFullHouse(roll));
}

That gives this implementation:
public bool IsFullHouse(Roll toCheck)
{
    return true;
}

Then write this test:
[Test]
public void StraightReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}

Once that is passing, write this one:
[Test]
public void ThreeOfAKindReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}

After that, I bet you don't need to write any more (maybe two pairs, or maybe yahtzee, if you think it isn't a full house).
Obviously, implement your Any methods to return random Rolls that meet your critieria.
There are a few benefits to this approach:

*

*You don't need to write a test whose sole purpose is to stop you from getting stuck on specific values

*The tests communicate your intent really nicely (the code of the first test screams "any full house returns true")

*it gets you quickly to the point of working on the meat of the problem

*sometimes it will notice cases you didn't think of

A: As a disclaimer, this is TDD as I practice it and, as Kilian aptly points out, I'd be wary of anyone who suggested that there is one right way to practice it.  But maybe it will help you...
First of all, the simplest thing you could do to get your test to pass would be this:
public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    return true;
}

This is significant because not because of some TDD practice, but because hard-cording in all of those literals isn't really a good idea.  One of the most difficult things to wrap your head around with TDD is that it isn't a comprehensive testing strategy -- it's a way to guard against regressions and mark progress while keeping the code simple.  It's a development strategy and not a testing strategy.
The reason I mention this distinction is that it helps guide what tests you should write.  The answer to "what tests should I write?" is "whatever tests you need to get the code the way you want it."  Think of TDD as a way to help you tease out algorithms and reason about your code.  So given your test and my "simple green" implementation, what test comes next?  Well, you've established something that is a full house, so when isn't it a full house?
public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 2, 3, 4, 5);

    Assert.IsFalse(actual);
}

Now you have to figure out some way to differentiate between the two test cases that's meaningful.  I personally would tack on a bit of clarifying information to the "do the simplest thing to make the test pass" and say "do the simplest thing to make the test pass that furthers your implementation."  Writing failing tests is your pretext to alter the code, so when you go to write each test, you should be asking yourself "what doesn't my code do that I want it to do and how can I expose that deficiency?"  It can also help you make your code robust and handle edge cases.  What do you do if a caller inputs nonsense?
public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(-1, -2, -3, -4, -5);

    //I dunno - throw exception, return false, etc, whatever you think it should do....
}

To sum up, if you're testing every combination of values, you're almost certainly doing it wrong (and likely to wind up with a combinatorial explosion of conditionals).  When it comes to TDD, you should write the minimum amount of test cases necessary to get the algorithm you want.  Any further tests that you write will start green and thus become documentation, in essence, and not strictly part of the TDD process.  You'll only write further TDD test cases if the requirements change or a bug is exposed, in which case you'll document the deficiency with a test and then make it pass.
Update:
I started this as a comment in response to your update, but it started getting pretty long...
I'd say that the problem isn't with the existence of literals, period, but with the 'simplest' thing being a 5-part conditional.  When you think about it, a 5-part conditional is actually pretty complicated.  It will be common to use literals during the red-to-green step and then to abstract them to constants in the refactor step or else generalize them in a later test.
During my own journey with TDD, I came to realize that there is an important distinction to be made -- it's not good to confuse "simple" and "obtuse".  That is, when I started out, I watched people do TDD and I thought "they're just doing the dumbest thing possible to make the tests pass" and I mimicked that for a while, until I realized that "simple" was subtly different than "obtuse".  Sometimes they overlap, but often not.
So, apologies if I gave the impression that the existence of literals was the problem -- it isn't.  I'd say the complexity of the conditional with the 5 clauses is the problem.  Your first red-to-green can just be "return true" because that is truly simple (and obtuse, by coincidence).  The next test case, with the (1, 2, 3, 4, 5) will have to return false, and this is where you start to leave "obtuse" behind.  You have to ask yourself "why is (1, 1, 1, 2, 2) a full house and (1, 2, 3, 4, 5) isn't?"  The simplest thing you could come up with might be that one has last sequence element 5 or second sequence element 2 and the other doesn't.  Those are simple, but they're also (needlessly) obtuse.  What you're really wanting to drive at is "how many of the same number do they have?"  So you might get the second test to pass by checking to see whether or not there is a repeat.  In the one with a repeat, you have a full house, and in the other you don't.  Now the test passes, and you write another test case that has a repeat but isn't a full house to further refine your algorithm.
You may or may not do this with literals as you go, and it's fine if you do.  But the general idea is growing your algorithm 'organically' as you add more cases.

A: There are already lots of good answers to this question, and I've commented and upvoted several of them. Still, I'd like to add some thoughts.
Flexibility isn't for novices
The OP clearly states that he's not experienced with TDD, and I think a good answer must take that into account. In the terminology of the Dreyfus model of skill acquisition, he's probably a Novice. There's nothing wrong with being a novice - we are all novices when we start learning something new. However, what the Dreyfus model explains is that novices are characterized by

*

*rigid adherence to taught rules or plans

*no exercise of discretionary judgement

That's not a description of a personality deficiency, so there's no reason to be ashamed of that - it's a stage we all need to go through in order to learn something new.
This is also true for TDD.
While I agree with many of the other answers here that TDD doesn't have to be dogmatic, and that it can sometimes be more beneficial to work in an alternative way, that doesn't help anyone just starting out. How can you exercise discretionary judgement when you have no experience?
If a novice accepts the advice that sometimes it's OK not to do TDD, how can he or she determine when it's OK to skip doing TDD?
With no experience or guidance, the only thing a novice can do is to skip out of TDD every time it becomes too difficult. That's human nature, but not a good way to learn.
Listen to the tests
Skipping out of TDD any time it becomes hard is to miss out of one of the most important benefits of TDD. Tests provide early feedback about the API of the SUT. If the test is hard to write, it's an important sign that the SUT is hard to use.
This is the reason why one of the most important messages of GOOS is: listen to your tests!
In the case of this question, my first reaction when seeing the proposed API of the Yahtzee game, and the discussion about combinatorics that can be found on this page, was that this is important feedback about the API.
Does the API have to represent dice rolls as an ordered sequence of integers? To me, that smell of Primitive Obsession. That's why I was happy to see the answer from tallseth suggesting the introduction of a Roll class. I think that's an excellent suggestion.
However, I think that some of the comments to that answer get it wrong. What TDD then suggests is that once you get the idea that a Roll class would be a good idea, you suspend work on the original SUT and start working on TDD'ing the Roll class.
While I agree that TDD is more aimed at the 'happy path' than it's aimed at comprehensive testing, it still helps to break the system down into manageable units. A Roll class sounds like something you could TDD to completion much more easily.
Then, once the Roll class is sufficiently evolved, would you go back to the original SUT and flesh it out in terms of Roll inputs.
The suggestion of a Test Helper doesn't necessarily imply randomness - it's just a way to make the test more readable.
Another way to approach and model input in terms of Roll instances would be to introduce a Test Data Builder.
Red/Green/Refactor is a three-stage process
While I agree with the general sentiment that (if you are sufficiently experienced in TDD), you don't need to stick to TDD rigorously, I think it's pretty poor advice in the case of a Yahtzee exercise. Although I don't know the details of the Yahtzee rules, I see no convincing argument here that you can't stick rigorously with the Red/Green/Refactor process and still arrive at a proper result.
What most people here seem to forget is the third stage of the Red/Green/Refactor process. First you write the test. Then you write the simplest implementation that passes all tests. Then you refactor.
It's here, in this third state, that you can bring all your professional skills to bear. This is where you are allowed to reflect on the code.
However, I think it's a cop-out to state that you should only "Write the simplest thing possible that isn't completely braindead and obviously incorrect that works". If you (think you) know enough about the implementation on beforehand, then everything short of the complete solution is going to be obviously incorrect. As far as advice goes, then, this is pretty useless to a novice.
What really should happen is that if you can make all tests pass with an obviously incorrect implementation, that's feedback that you should write another test.
It's surprising how often doing that leads you towards an entirely different implementation than the one you had in mind first. Sometimes, the alternative that grows like that may turn out to be better than your original plan.
Rigour is a learning tool
It makes a lot of sense to stick with rigorous processes like Red/Green/Refactor as long as one is learning. It forces the learner to gain experience with TDD not just when it's easy, but also when it's hard.
Only when you have mastered all the hard parts are you in a position to make an informed decision on when to deviate from the 'true' path. That's when you start forming your own path.

A: I can think of two major ways I'd consider while testing this;

*

*Add "some" more test cases (~5) of valid full-house sets, and the same amount of expected falses ({1, 1, 2, 3, 3} is a good one. Remember that 5 ones for example could be recognized as "3 of the same plus a pair" by an incorrect implementation). This method assumes the developer is not just trying to pass the tests, but actually implement it correct.

*Test all possible sets of dice (there are only 252 different ones). This of course assumes you have some way to know what the expected answer is (in testing this is known as an oracle.) This could be a reference implementation of the same function, or a human being. If you want to be really rigorous it could be worth it to manually code each expected outcome.
As it happens, I've written a Yahtzee AI once, which of course had to know the rules. You can find the code for the the score-assessing part here,
please note that the implementation is for the Scandinavian version (Yatzy), and our implementation assumes the dice are given in sorted order.

A: This example really misses the point.  We're talking about a single straightforward function here not a software design.  Is it a bit complicated? yes, so you break it down.  And you absolutely do not test every possible input from 1, 1, 1, 1, 1 to 6, 6, 6, 6, 6, 6.  The function in question doesn't require order, just a combination, namely AAABB.
You don't need 200 seperate logic tests. You could use a set for example. Nearly any programming language has one built in:
Set set;
set.add(a);
set.add(b);
set.add(c);
set.add(d);
set.add(e);

if(set.size() == 2) { // means we *must* be of the form AAAAB or AAABB.
    if(a==b==c==d) // eliminate AAAAB
        return false;
    else
        return true;
}
return false;

And if you get an input that isn't a valid Yahtzee roll, you should throw like there's no tomorrow.


Q: Visual Studio package cannot be debugged in VS 2017 RC I have a VSIX package (extension) that works and can be debugged in VS 2013 and 2015. I have now adjusted the manifest to allow the package to be installed in VS 2017. However, it doesn't work there properly and I want to debug it.
I open the package project in VS 2015 and tell it to debug the package in VS 2017 RC with the usual command line switch /rootsuffix Exp. A clean VS 2017 instance starts, but the package is not installed in it so it cannot be debugged. How to fix this?

A: The only practical way to add support for VS 2017 is to open and build your extension in VS 2017: How to: Migrate Extensibility Projects to Visual Studio 2017. After the migration it should be easy to debug in VS 2017.


Q: open62541 Visual Studio 2017 error, OPCUA I am trying to build open62541, generate files for VS 2017, using Cmake.
I am having problem,
"MSB6006 'cmd.exe' exited with code 1 error " for open62541 files.
When I build the generated file from Cmake, using VS2017.

I am trying to connect my 4Diac control system to UA expert, which will be used to read and write data to JS simulator.
I am looking for answers but have not found any satisfactory answers.
I will really appreciate some solution.
Thank you.
BR,
Ahsan