text:
Q: What permissions and ownership should the 'static' folder have in production/ This is something I face everytime I deploy a Django app.. permissions.
Which group and user should own the static directory and what should the permissions look like?
I currently have:
drwxr-xr-x 7 www-data www-data  4096 Dec 11 05:29 static

My css files are getting a 403 response code when I visit my website so something must be wrong.

A: Try following steps,
Install whitenoise.
pip install whitenoise

Add it into dependencies i.e requirements.txt.
pip freeze > requirements.txt

Add the whitenoise.middleware.WhiteNoiseMiddleware into MIDDLEWARE list in project settings.
MIDDLEWARE = [
    ....
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

I hope this works for you after deploying the project for production.


text:
Q: Настроить заголовки для cURL дли кириллических запросов Настраиваю cURL для работы c API
Headers:
'cache-control: max-age=0',
'upgrade-insecure-requests: 1',
'user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
'sec-fetch-user: ?1',
'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'x-compress: null',
'sec-fetch-site: none',
'sec-fetch-mode: navigate',
'accept-encoding: deflate, br',
'accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',

При запросе https://api.site.ru/vacancies?text=PHP все работает.
Но на https://api.site.ru/vacancies?text=Программист результатов нет.
Ответ: {"items":[],"found":0,"pages":1,"per_page":20,"page":0,"clusters":null,"arguments":null,"alternate_url":"https://site.ru/search/vacancy?enable_snippets=true&text=%D0%A0%D1%9F%D0%A1%D0%82%D0%A0%D1%95%D0%A0%D1%96%D0%A1%D0%82%D0%A0%C2%B0%D0%A0%D1%98%D0%A0%D1%98%D0%A0%D1%91%D0%A1%D0%83%D0%A1%E2%80%9A}
Хотя, если ввести тот же запрос в строку браузера - результаты есть.

A: В общем без кода можно предположить только одно - вы пытаетесь передать напрямую кириллицу, которую по стандарту необходимо преобразовать, поскольку url может содержать только определенные символы (для информации читаем https://en.wikipedia.org/wiki/Percent-encoding)
В php это можно сделать двумя способами - стандартной функцией php urlencode или функцией библиотеки curl curl_escape
Пример:
<?php.
$ch = curl_init();
// Строки, содержащие пробелы, латиницу,спецсимволы и т.п. необходимо предварительно кодировать в escape-последовательности
$query = curl_escape($ch, 'Программист');
// Тперь из этого добра можно собрать полный uri
$url = "https://api.site.ru/vacancies?text={$query}";
echo "urlencoded строка будет такой: {$url}\n";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving $\frac{p_{n+1}^2-p_{n+1}^{-C}}{p_{n+1}^2-1}>\frac{f(n) p_n \log p_n }{p_{n+1} \log p_{n+1}},$ where $f(n)\to1$, for some constant $C>1$ Are there two constants $C_1$, $C_2>1$ such that for large enough $n$ $$\frac{p_{n+1}^2-p_{n+1}^{-C_1}}{p_{n+1}^2-1}>\frac{2 C_2 p_{n+1} \log p_{n+1}-1}{2 C_2 p_{n} \log p_{n}-1} \left(\frac{p_n \log p_n}{p_{n+1} \log p_{n+1}}\right)^n \ \prod_{k=2}^{n-1} \frac{p_k^2C_2p_{n+1}\log p_{n+1}-1}{p_k^2C_2p_{n}\log p_{n}-1} \ \ \ \ ?$$
After other attempts (failures), here's what I did to show the thruthfulness of the statement:
Let $m=p_{n+1}$ and set $$\ g(m)>\frac{2 C_2 p_{n+1} \log p_{n+1}-1}{2 C_2 p_{n} \log p_{n}-1} \left(\frac{p_n \log p_n}{p_{n+1} \log p_{n+1}}\right)^{n-1} \ \prod_{k=2}^{n-1} \frac{p_k^2C_2p_{n+1}\log p_{n+1}-1}{p_k^2C_2p_{n}\log p_{n}-1} $$ to write the stronger inequality $$\frac{m^2-m^{-C_1}}{m^2-1}>\frac{g(m) (m-2) \log (m-2)}{m \log m},$$ which, since the LHS converges to $1$ strictly from above and, provided that $g(m)\to 1$, clearly the RHS goes to $1$ as well, is implied by $$D\left(\frac{g(m) (m-2) \log (m-2)}{m \log m}\right)>0.$$ This reduces to $$\frac{g'(m)}{g(m)}>\frac{1}{m} - \frac{1}{m-2} - \frac{1}{(m-2)\log (m-2)}.$$ However I can't see what to do with this to prove the original inequality. How does one proceed? Or how does one prove it with a different approach? Thank you.

A: I have had a go at trying to prove it by simply estimating all the different terms in the equation to find the asymptotic behavior of two sides of the equation. Below $\sim$ will denote an asymptotic value.
Using $p_n\sim n\log n$ we get the following estimates
$$A_n \equiv \frac{p_n\log p_n}{p_{n+1}\log p_{n+1}} \sim 1 - \frac{1}{n}$$
$$B_n \equiv \frac{1}{p_n\log p_n}-\frac{1}{p_{n+1}\log p_{n+1}} \sim \frac{1}{n^2\log^2(n)}$$
Using this we find
$$\frac{2 C_2 p_{n+1} \log p_{n+1}-1}{2 C_2 p_{n} \log p_{n}-1} \sim 1+\frac{B_n}{2C_2} \sim 1+\frac{1}{2C_2n^2\log^2(n)}$$
$$\left(\frac{p_{n}\log p_{n}}{p_{n+1}\log p_{n+1}}\right)^{n-2}\times \prod_{k=2}^{n-1}\frac{C_2p_k^2p_{n+1}\log p_{n+1}-1}{C_2p_k^2p_{n}\log p_{n}-1} = \\\prod_{k=2}^{n-1}\left[1 + \frac{B_n}{C_2 p_k^2} + \mathcal{O}\left(\frac{1}{p_k^4n^2\log^4 n}\right)\right]\sim 1 + \frac{1}{C_2n^2\log^2 n}\sum_{k=2}^{n-1}\frac{1}{p_k^2} + \mathcal{O}\left(\frac{1}{n^2\log^4 n}\right)$$
and since $\sum_{k=2}^\infty \frac{1}{p_k^2} < \frac{\pi^2}{6}$ the prefactor to the second term is bounded by a $\mathcal{O}(1)$ constant.
Combinding the results above gives us
$$LHS = 1 + \frac{1-p_{n+1}^{-C_1}}{p_{n+1}^2-1} \sim 1 + \frac{1}{n^2\log^2(n)}$$
for $C_1>0$ and
$$RHS \sim \left(1+\frac{1}{2C_2n^2\log^2(n)}\right)\left(1-\frac{1}{n}\right)^2\left(1 + \frac{\mathcal{O}(1)}{C_2n^2\log^2 n}\right) \sim 1 - \frac{2}{n} + \frac{\mathcal{O}(1)}{C_2 n^2\log^2(n)}$$
and it follows that LHS$-$RHS $ \sim \frac{2}{n} > 0$ for large enough $n$ independent of $C_1,C_2$ (as long as $C_1>0$).
If the $(A_n)^n$ term on the RHS is replaced by $(A_n)^{n-2}$ (removing the middle term in the estimate above) it becomes more interesting as the two sides have comparable convergence to $1$, but by choosing $C_2$ large enough it still follows that LHS$ > $RHS for large enough $n$.

A: Probably I'm wrong but I hope that this answer could help you.
In this problem I interpreted:
$$1)-p_n\ is\ the\ n-th\ prime\ number$$
$$2)-f(n)\ is\ a\ generic\ sequence\ which\ converges\ to\ 1\ for\ n\ large\ enough$$
$$3)-the\ proposition\ must\ be\ true\ for\ n\ large\ enough$$
Said that,prove that:
$$\frac{p_{n+1}^2 - p_{n+1}^{-C}}{p_{n+1}^2 - 1} > f(n)\ \frac{p_{n}\ ln(p_{n})}{p_{n+1}\ ln(p_{n+1})}$$
It's equivalent to prove:
$$\frac{p_{n+1}^2 - p_{n+1}^{-C}}{p_{n+1}^2 - 1}\ \frac{p_{n+1}\ ln(p_{n+1})}{p_{n}\ ln(p_{n})} >\ f(n)$$
let's suppose:
$$s(n)\ :=\  \frac{p_{n+1}^2 - p_{n+1}^{-C}}{p_{n+1}^2 - 1}\ \frac{p_{n+1}\ ln(p_{n+1})}{p_{n}\ ln(p_{n})}$$
Then we have:$$s(n) > f(n)$$
It's not difficult to prove that: $$\lim_{n \to \infty}s(n)\ =\ 1\ for\ each\ c>1$$
Infact the Prime number theorem implies that: $$p_n\ \sim\ n\ ln(n)$$
But if we suppose: $$f(n)\ :=\ e^{s(n) - 1}$$
We can verify that:
$$\lim_{n \to \infty}f(n)\ =\ 1 $$
$$ s(n)\ <\ f(n)\ =\ e^{s(n)\ -\ 1}$$
Because: $$ x \le e^{x\ -\ 1}\ with\ x\in\mathbb{R} $$
That should be a contraddiction.
I'm sorry for the form but it's my first answer.


text:
Q: Point only homepage to GitHub pages and use GCP web server for everything else I have an Apache Web Server running on a GCP compute instance. Currently, I have a custom domain pointing to GitHub pages using CNAMEs and A Records. How can I continue with that functionality while also redirecting any subfolders to my web server?
Desired behaviour:
example.com --> xyz.github.io [currently working]
www.example.com --> xyz.github.io [currently working]

example.com/folder/item --> File on GCP webserver
www.example.com/folder/item --> File on GCP webserver

I think it might be possible with .htaccess redirects but I believe that would cause is a certificate and domain mismatch?
Also, one other roadblock is that the folder redirect should be for every folder except /images/ as that's hosted on GitHub already.


text:
Q: Horizontal drop-down menu Umbraco I'm using Umbraco and I want my drop-down menu to display horizontal like this:

Right now my drop down menu is like this:

The problem is that I don't know how to do this in Umbraco
Here is my code:
MainNavigation code:
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{ var home = CurrentPage.Site(); }

@if (home.Children.Any())
{
    @* Get the first page in the children *@
    var naviLevel = home.Children.First().Level;

    @* Add in level for a CSS hook *@

        @* For each child page under the home node *@
        @foreach (var childPage in home.Children)
        {
            if (childPage.Children.Any())
            {

                    @if (childPage.DocumentTypeAlias == "Huvudmeny")
                    {
                        @childPage.Name
                        @childPages(childPage.Children)
                    }
                    else
                    {
                        @childPage.Name
                    }

            }
            else
            {

                    @childPage.Name

            }
        }

}

@helper childPages(dynamic pages)
{
    @* Ensure that we have a collection of pages *@
    if (pages.Any())
    {
        @* Get the first page in pages and get the level *@
        var naviLevel = pages.First().Level;

        @* Add in level for a CSS hook *@

        @foreach (var page in pages)
        {

                @page.Name

                @* if the current page has any children *@
                @if (page.Children.Any())
                {
                    @* Call our helper to display the children *@
                    @childPages(page.Children)
                }

        }

    }
}

The above code is included in my master page through this code:

    @{ Html.RenderPartial("MainNavigation"); }

js
// Navigation
  $('#toggle').click(function(){
    $('.has-child').removeClass('selected');
    $('nav').toggleClass('open');
    $('.cross').toggleClass('open');
  });

  $('.has-child').click(function(){
    if ( window.innerWidth < 768 ) {
      if ( $( this ).hasClass('selected')){
        $('.has-child').removeClass('selected');
      } else {
        $('.has-child').removeClass('selected');
        $(this).toggleClass('selected');
      }
    }
  });

Can anyone give me advice on how to make the drop down menu horizontal?

A: So described in the comment. The problem can be fixed with CSS as shown in the fiddle
This is what I would call a fix. But the way I would think is the proper way, would be to create a CSS class instead of override the bootstrap CSS.
When overriding the bootstap class, you also create a problem. if you would like to use two navbar's and the one needs the horizontal dropdown menu while the other needs the default CSS. The CSS override would effect both. But if you create a class you could use it on only the one element.
Hope this makes sense. Hard to spell check it from the mobile.


text:
Q: Passing multiple arguments to a thread in C (pthread_create) I am trying to pass 2 unsigned integers to a newly created thread in C (using pthread_create()) but nor an array of 2 integers or a struct seems to work.
// In my socket file

struct dimension {
    unsigned int width;
    unsigned int height;
};

unsigned int width, height;

void setUpSocket(void* dimension) {

    struct dimension* dim = (struct dimension*) dimension;

    width = dim->width;
    height = dim->height;

    printf("\n\nWidth: %d, Height: %d\n\n", width, height);

}

// In main.cpp

// Pass a struct in pthread_create
struct dimension dim;
dim.width = w;
dim.height = h;

pthread_create(&ph, &attr, (void * (*)(void *)) setUpSocket, (void *) &dim);

Before calling pthread_create, dim.width and dim.height are correct. In my socket file, only width is set, height is 0, and I do not understand why.
Does anyone know what is wrong please and how to fix it?
Thank you very much.

A: The way you're passing the arguments should work fine, as long as dim is not allocated on the stack.  If it's on the stack, then it could become deallocated before the new thread has a chance to run, resulting in undefined behavior.  If you're only creating one thread, you can use a global variable, but the better alternative is to allocate it on the heap.
Also, you should not be casting the function pointer: that is undefined behavior (and in fact, it could crash due to speculative execution on the IA64 architecture).  You should declare your thread procedure to return void* and avoid a function pointer cast:
void *setUpSocket(void* dimension) {

    struct dimension* dim = (struct dimension*) dimension;

    width = dim->width;
    height = dim->height;
    // Don't leak the memory
    free(dim);

    printf("\n\nWidth: %d, Height: %d\n\n", width, height);

    return 0;
}

// In main.cpp

// Pass a struct in pthread_create (NOT on the stack)
struct dimension *dim = malloc(sizeof(struct dimension));
dim->width = w;
dim->height = h;

pthread_create(&ph, &attr, setUpSocket, dim);

A: How big can width and height be? If not very big, I would do something like this:
 pthread_create(&ph, &attr, setUpSocket, (void *)(65536*height+width));

A: You are passing a pointer to a variable with local scope.  If the caller function finishes before the thread has picked up the values, then that variable will go out of scope, and its contents will be undefined.

A: You creating that argument structure on the stack, which is temporary storage and is re-used by the function call chain. It's probably overwritten by the time the thread starts. You need to pass a pointer to either static or heap-allocated memory.


text:
Q: Correct way for declaring beans in spring MVC? I created a project named "Testing" using maven in eclipse j2ee. I created a web.xml file in WEB-INF folder as follows :
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Archetype Created Web Application</display-name>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And this is my dispatcher servlet that i placed withing WEB-INF folder.
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.spring.trial" />
<context:property-placeholder location="classpath:jdbc.properties" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<!-- Employee DB data source. -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.employee_db_url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
    <property name="minPoolSize" value="${jdbc.minPoolSize}" />
    <property name="maxStatements" value="${jdbc.maxStatements}" />
    <property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
    <property name="idleConnectionTestPeriod" value="200" />
    <property name="loginTimeout" value="300" />
    <property name="maxIdleTime" value="2700"></property>
    <property name="testConnectionOnCheckin" value="true" />
    <property name="maxIdleTimeExcessConnections" value="60"></property>
</bean>

<bean name="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    scope="singleton">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="categories" class="com.spring.trial.access.Categories"></bean>

I have a controller called helloworldcontroller as follows
package com.spring.trial;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.spring.trial.access.Categories;

@Controller
public class HelloWorldController {

String message = "Welcome to Spring MVC!";
@Autowired
Categories categories;

@RequestMapping("/hello")
public ModelAndView showMessage(
        @RequestParam(value = "name", required = false, defaultValue = "World") String name) {
    System.out.println("in controller");

    ModelAndView mv = new ModelAndView("helloworld");
    mv.addObject("message", message);
    mv.addObject("name", name);
    return mv;
}

}
Okay now for the triky part....
1)i went through various tutorials online and in some sites the web.xml file has context params that pass the dispatcher-servlet to the context loader class. Does this mean that all the beans in the dispatcher servlet be initialised and autowired . And does it mean that the dispatcher servlet context is now the root application context??
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

<!-- this class is responsible for auto-wiring all the beans together in
    spring -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

In some sites the web.xml file is intialised as follows:
 <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/application-context.xml
    </param-value>
</context-param>

<!-- Configurations for the DispatcherServlet application context (child context) -->
<servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-mvc-servlet.xml
        </param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/admin/*</url-pattern>
</servlet-mapping>

2) so again what is happening in this web.xml file?? is it loading 2 different contexts one for root and the other for dispatcher servlet??
and in case 2 they hace application-context.xml so on a jsp page i can easily retrieve a bean using
applicationContext context = new classpathxmlapplicationcontext("application-context.xml);
myclass mclass = (myclass)context.getbean("mclassname");

but in case I(first web.xml file that i posted on top) i dont have any application context so how am i supposed to retrive bean on my jsp page?? I just have the dispatcher and all the beans are declared in the dispatcher. please help me i am so confused ryt now.....


text:
Q: ttk.Checkbutton instate failing Using ttk.Checkbutton.instate('selected')  to get current state of a checkbutton gives me this error:
File "C:\Program Files\Python\lib\tkinter\ttk.py", line 576, in instate
 self.tk.call(self._w, "instate", ' '.join(statespec)))_tkinter.TclError: Invalid state name s

This is my code:
import tkinter as tk
from tkinter import ttk
def p(event):
    st = ck.state()
    if 'selected' in st:
        print ('got selected')
    if ck.instate('selected') :
        print('instate true')
root = tk.Tk()
root.geometry('200x200+300+200')
root.grid_rowconfigure(0, weight = 1)

ck = ttk.Checkbutton(root,text = 'tryme')
ck.grid()
root.bind('<Return>',p)
root.mainloop()

The code should work now.  ck.instate('selected) gives error and appears to only see the first character of the argument


text:
Q: Docker save issue I am on docker version 1.11.2. I am trying to docker save an image but i get
an error.
i did docker images to see the size of the image and the result is this
myimage             0.0.1-SNAPSHOT      e0f04657b1e9        10 months ago       1.373 GB
The server I am on is low on space but it has 2.2 GB available but when I run docker save myimage:0.0.1-SNAPSHOT > img.tar i get
write /dev/stdout: no space left on device
I removed all exited containers and dangling volumes in hopes of making it work but nothing helped.

A: You have no enough space left on device. So free some more space or try gzip on the fly:
docker save myimage:0.0.1-SNAPSHOT | gzip > img.tar.gz

To restore it, docker automatically realizes that is gziped:
docker load < img.tar.gz

A: In such a situation where you can't free enough space locally you might want to use storage available over a network connection. A little bit more difficult to set up are NFS or Samba.
The easiest approach could be piping the output through netcat, but keep in mind that this is at least by default unencrypted.
But as long as your production server is that low on space you are vulnerable to a bunch of other problems.
Until you can provide more free space I wouldn't create files locally, zipped or not. You could bring important services down when you run out of free space.


text:
Q: Unit testing NestJS controller with request My Controller function definition looks like that:
async login(@Req() request, @Body() loginDto: LoginDto): Promise<any> {
How I could prepare/mockup Request to provide first argument of function from Jest test?
Inside funciton I am setting headers using request.res.set. Should I somehow pass real Request object to function and then check if header is set or rather mockup whole Request object and check if set function was called?

A: I followed a different approach and instead of using node-mocks-http library I used @golevelup/ts-jest, also, instead of testing if the function returns some value, like res.json() or res.status(), I checked if the function was called with the value I wanted to.
I borrowed this approach from Kent C. Dodds's testing workshop, take a look for similar ideas. Anyway, this is what I did in order to mock the Response dependency of my Controller's route:
  // cars.controller.spec.ts
  import { createMock } from '@golevelup/ts-jest';

  const mockResponseObject = () => {
    return createMock<Response>({
      json: jest.fn().mockReturnThis(),
      status: jest.fn().mockReturnThis(),
    });
  };

  ... ommited for brevity

  it('should return an array of Cars', async () => {
    const response = mockResponseObject();

    jest
      .spyOn(carsService, 'findAll')
      .mockImplementation(jest.fn().mockResolvedValueOnce(mockedCarsList));

    await carsController.getCars(response);

    expect(response.json).toHaveBeenCalledTimes(1);
    expect(response.json).toHaveBeenCalledWith({ cars: mockedCarsList });
    expect(response.status).toHaveBeenCalledTimes(1);
    expect(response.status).toHaveBeenCalledWith(200);
  });

And that's it, I think that the implementation details aren't that important but in any case I'll leave the link to the Github repo where you can find the whole project.

A: I managed to do that mocking requests and response using node-mocks-http library.
const req = mocks.createRequest()
req.res = mocks.createResponse()

and then passing this as an argument.
const data = await authController.login(req, loginDto)
expect(req.res.get('AccessToken')).toBe(token.accessToken)


text:
Q: Attaching a Path to a userform selection I have a workbook in E:\EXPENCES. In it, a Userform with 2 comboboxes.
cmb1 lists names of workbooks that are in a different folder (E:\MLDOWNLOADS) - The Target.
cmb2 lists Sheets in the current workbook - The Destination.
I would like to copy a range from Target and paste into the destination.
How do I assign  a variable that contains full path of target attached to cmb1.value
current code:
Dim cbook As Workbook
Dim psheet As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
Dim Dpath As String

  Dpath = "E:\MLDOWNLOADS\"

  cbook = (Dpath & Frmdownloads.cmb1.Value)
  psheet = Frmdownloads.cmb2.Value

  Set wsCopy = Workbooks(cbook).Worksheets("List transactions")
  Set wsDest = ThisWorkbook.Worksheets(psheet)

  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

  lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row

  wsCopy.Range("A2:D" & lCopyLastRow).Copy wsDest.Range("A" & lDestLastRow)
End Sub


text:
Q: string comparison in php if condition is not working properly I want to compare to a string but it is not working.
First I took it in my script and stored in a variable, and after that I stored the variable in the session.
This is my code...
<?php
    $currencyName1 = "<script>document.write(data);</script>";

    $_SESSION["currencyVal"] = $currencyName1;

    $price = strip_tags($this->session->userdata('currencyVal'));
    $price1 = substr($price,14,17);

    if (strcmp($price,"SAR")) {
        echo "SAR";
    } else {
        echo "USD";
    }
?>

A: Use cookie to get proper string
Where as in $_SESSION you get value with script tags <script>document.write(data);</script>

A: Agreed with @lehmanad1, You need to perform comparison like strcmp($price1,"SAR"), and keep in mind that strcmp return result as follows.
strcmp returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2

so that in your case the if condition return 0 if strcmp($price1,"SAR")gets true, and thus else condition will be executed.
you need to try following approach.
if (strcmp($price1,"SAR")==0) {
    echo "SAR";
} else {
    echo "USD";
}


text:
Q: How do I calculate the number of consecutive columns with zero values from the right until the first non zero element occurs Suppose I have the following dataframe:
   C1 C2 C3 C4
0  1  2  3  0
1  4  0  0  0
2  0  0  0  3
3  0  3  0  0

Then I want to add another column such that it will display the number of zero valued column that occur contiguously from the right.
The new column would be:
  Cnew
0 1
1 3
2 0
3 2

A: You can use:

*

*reverse order by iloc and [::-1]

*get cumsum per row (axis=1)

*check eq and get sum of Trues

df['new'] = df.iloc[:,::-1].cumsum(axis=1).eq(0).sum(axis=1)
print (df)
   C1  C2  C3  C4  new
0   1   2   3   0    1
1   4   0   0   0    3
2   0   0   0   3    0
3   0   3   0   0    2

print (df.iloc[:,::-1])
   C4  C3  C2  C1
0   0   3   2   1
1   0   0   0   4
2   3   0   0   0
3   0   0   3   0

print (df.iloc[:,::-1].cumsum(axis=1))
   C4  C3  C2  C1
0   0   3   5   6
1   0   0   0   4
2   3   3   3   3
3   0   0   3   3

print (df.iloc[:,::-1].cumsum(axis=1).eq(0))
      C4     C3     C2     C1
0   True  False  False  False
1   True   True   True  False
2  False  False  False  False
3   True   True  False  False

A: I'd use argmax on a boolean array.  Also, if I skip straight to numpy I can make this very fast.
(df.values[:, ::-1] != 0).argmax(1)

array([1, 3, 0, 2])

Or very similarly
(df.values[:, ::-1].astype(bool)).argmax(1)

array([1, 3, 0, 2])

I can place it in a new column with assign
df.assign(new=(df.values[:, ::-1] != 0).argmax(1))

   C1  C2  C3  C4  new
0   1   2   3   0    1
1   4   0   0   0    3
2   0   0   0   3    0
3   0   3   0   0    2

Or add a new column in place
df['new'] = (df.values[:, ::-1] != 0).argmax(1)
df

   C1  C2  C3  C4  new
0   1   2   3   0    1
1   4   0   0   0    3
2   0   0   0   3    0
3   0   3   0   0    2

Timing
We reduce the time by reducing the work necessary.  We only need to find the position of the first non-zero.
# My first variant
%timeit df.assign(new=(df.values[:, ::-1] != 0).argmax(1))
# My second variant
%timeit df.assign(new=(df.values[:, ::-1].astype(bool)).argmax(1))
# jezrael's solution
%timeit df.assign(new=df.iloc[:,::-1].cumsum(1).eq(0).sum(1))
# numpy version of jezrael's solution
%timeit df.assign(new=(df.values[:,::-1].cumsum(1) == 0).sum(1))
# Scott Boston's solution
%timeit df.assign(new=df.iloc[:,::-1].eq(0).cumprod(axis=1).sum(axis=1))
# numpy version of Scott Boston's solution
%timeit df.assign(new=(df.values[:,::-1] == 0).cumprod(1).sum(1))

small data
1000 loops, best of 3: 301 µs per loop
1000 loops, best of 3: 273 µs per loop
1000 loops, best of 3: 770 µs per loop
1000 loops, best of 3: 323 µs per loop
1000 loops, best of 3: 647 µs per loop
1000 loops, best of 3: 324 µs per loop

larger data
df = pd.DataFrame(np.random.choice([0, 1], (10000, 100), p=(.7, .3)))

100 loops, best of 3: 6.03 ms per loop
100 loops, best of 3: 5.3 ms per loop
100 loops, best of 3: 16.9 ms per loop
100 loops, best of 3: 9 ms per loop
100 loops, best of 3: 10.7 ms per loop
100 loops, best of 3: 10.1 ms per loop

A: Use eq, cumprod and sum (This is very similiar to a question answered here.)
df.iloc[:,::-1].eq(0).cumprod(axis=1).sum(axis=1)

Output:
0    1
1    3
2    0
3    2
dtype: int64


text:
Q: Scrollbar - make the background move but not the forderground On a basic program (launcher) I have a scrollbar problem : they make the background-picture move but not the forderground widgets (buttons).
The GUI is built as follow :

*

*Level 0 (parent = self) : Canvas (self.c) as background with a picture + scrollbars

*Level 1 (parent = self.c) : Buttons + an invisible Frame

Here is the code :
# -*-coding:Utf-8 -*-
from __future__ import unicode_literals

import Tkinter
import ImageTk
import Image

class Interface(Tkinter.Tk) :
    def __init__(self, parent) :
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

# Creation des widgets
    def initialize(self) :
    # Fenetre principale
        self.minsize(437, 98)
        # Scrollbars working on principal Canvas self.c
        self.ascenseur_y = Tkinter.Scrollbar(self, orient=Tkinter.VERTICAL)
        self.ascenseur_x = Tkinter.Scrollbar(self, orient=Tkinter.HORIZONTAL)
        self.ascenseur_y.grid(row=0, column=1, sticky="ns")
        self.ascenseur_x.grid(row=1, column=0, sticky="ew")

        # Canvas self.c - all other widgets but the scrollbars are in self.c
        self.c = Tkinter.Canvas(self, yscrollcommand=self.ascenseur_y.set, xscrollcommand=self.ascenseur_x.set,\
                                bg="white", highlightthicknes=0)
        self.apercu_logo="Logo.png"
        self.photo = ImageTk.PhotoImage(Image.open(self.apercu_logo))
        self.c.config(height=self.photo.height(), width=self.photo.width())
        self.image_x = self.photo.height()/2
        self.image_y = self.photo.width()/2
        self.item = self.c.create_image(self.image_x, self.image_y, anchor="center", image=self.photo)
        self.c.grid(row=0, column=0, sticky="news")
        self.c.bind('<Configure>', self.dimensionner)

        self.ascenseur_y.config(command=self.c.yview)
        self.ascenseur_x.config(command=self.c.xview)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # Invisible Frame to bind Mousewheel event with vertical scrollbar
        self.fr = Tkinter.Frame(self.c)
        self.fr.bind_all("<MouseWheel>", self._on_mousewheel_haupt)

    # Button "start pdf2pptx"
        self.c.bouton_pdf2pptx = Tkinter.Button(self.c, width=13, text=u"Pdf2pptx", command=self.ButtonPdf2pptx, anchor="center", cursor="hand2", padx=0)
        self.c.bouton_pdf2pptx.grid(column=0, row=0)
        self.c.bouton_pdf2pptx.bind("<Return>", self.EnterPdf2pptx)
        self.c.bouton_pdf2pptx.focus_set()

    # Button "start xls2inp"
        self.c.bouton_xls2inp = Tkinter.Button(self.c, width=13, text=u"xls2inp", command=self.ButtonXls2inp, anchor="center", cursor="hand2", padx=0)
        self.c.bouton_xls2inp.grid(column=1, row=0)
        self.c.bouton_xls2inp.bind("<Return>", self.EnterXls2inp)

    # Button "start Zeichen ersetzer"
        self.c.bouton_ZeichenErsetzer = Tkinter.Button(self.c, width=13, text=u"Zeichen ersetzer", command=self.ButtonZeichenErsetzer, anchor="center", cursor="hand2", padx=0)
        self.c.bouton_ZeichenErsetzer.grid(column=2, row=0)
        self.c.bouton_ZeichenErsetzer.bind("<Return>", self.EnterZeichenErsetzer)

    # Configuration rows/columns
        self.c.grid_rowconfigure(0, weight=1, pad=100, minsize=300)

        self.c.grid_columnconfigure(0, weight=1, pad=30, minsize=140)
        self.c.grid_columnconfigure(1, weight=1, pad=30, minsize=140)
        self.c.grid_columnconfigure(2, weight=1, pad=30, minsize=140)

    # Logo of the main window
        self.iconbitmap("IcoKAG.ico")

# Options of the main window
        # Resizable
        self.resizable(True, True)
        # Principal Canvas and config of the scrollbars
        self.c.create_window(0, 0, window=self.fr)
        self.fr.update_idletasks()
        self.c.config(scrollregion=self.c.bbox("all"))
        # Make sure all widgets are updated
        self.update()

# Fonctions

    def dimensionner(self, event):
        """ Management of the resizement of the window:
            Centers the background-picture
            Modifies the size of rows/columns
            Resizes the scrollbars """
        self.image_y = self.winfo_height()/2
        self.image_x = self.winfo_width()/2
        self.c.delete(self.item)
        self.item = self.c.create_image(self.image_x, self.image_y, anchor="center", image=self.photo)
        if self.winfo_height() < 300 and self.winfo_height() > 100:
            self.c.grid_rowconfigure(0, weight=1, pad=100, minsize=self.winfo_height())
        elif self.winfo_height() < 100 :
            self.c.grid_rowconfigure(0, weight=1, pad=100, minsize=98)
        else :
            self.c.grid_rowconfigure(0, weight=1, pad=100, minsize=300)

    # Scrollbars options
        if self.winfo_width() < 437 :
            self.c.grid_columnconfigure(0, weight=1, pad=30, minsize=self.winfo_width()/3)
            self.c.grid_columnconfigure(1, weight=1, pad=30, minsize=self.winfo_width()/3)
            self.c.grid_columnconfigure(2, weight=1, pad=30, minsize=self.winfo_width()/3)
        else :
            self.c.grid_columnconfigure(0, weight=1, pad=30, minsize=140)
            self.c.grid_columnconfigure(1, weight=1, pad=30, minsize=140)
            self.c.grid_columnconfigure(2, weight=1, pad=30, minsize=140)

        if self.winfo_height() > 223 and self.winfo_width() > 420 :
            self.SR = self.c.bbox("all")
            self.SRL=list(self.SR)
            self.SRL[2] = self.winfo_width() - 16
            self.SRL[3] = self.winfo_height() - 16
            self.c.config(scrollregion=tuple(self.SRL))
            self.update()
        elif self.winfo_height() < 223 and self.winfo_width() > 420 :
            self.SR = self.c.bbox("all")
            self.SRL=list(self.SR)
            self.SRL[2] = self.winfo_width() - 16
            self.SRL[3] -= 16
            self.c.config(scrollregion=tuple(self.SRL))
            self.update()
        elif self.winfo_height() > 223 and self.winfo_width() < 420 :
            self.SR = self.c.bbox("all")
            self.SRL=list(self.SR)
            self.SRL[2] -= 16
            self.SRL[3] = self.winfo_height() - 16
            self.c.config(scrollregion=tuple(self.SRL))
            self.update()
        else :
            pass

    def _on_mousewheel_haupt(self, event):
        """ Bind mousewheel to y-scrollbar """
        self.c.yview_scroll(-1*(event.delta/120), "units")

    def ButtonPdf2pptx(self) :
        pass

    def EnterPdf2pptx(self, event) :
        self.ButtonPdf2pptx()

    def ButtonXls2inp(self) :
        pass

    def EnterXls2inp(self, event) :
        self.ButtonXls2inp()

    def ButtonZeichenErsetzer(self) :
        pass

    def EnterZeichenErsetzer(self, event) :
        self.ButtonZeichenErsetzer()

# Main window is build
if __name__ == "__main__" :
    appLauncher = Interface(None)
    appLauncher.title(u"Programm-launcher - Kämmerer AG")
    appLauncher.mainloop()

The scrollbars make the Canvas "self.c" move but not the buttons which are in the canvas. After a lot of tests I still don't find the mistake. Does someone have an idea about the problem?
Thanks!

A: For something to scroll with the canvas it must be part of the canvas. That means you have to use create_window rather than pack, place or grid to add child widgets to a canvas.


text:
Q: Change Data Capture cannot be enabled on a table with a clustered columnstore index. Consider dropping clustered columnstore index I am getting the below error when trying to enable CDC on a table with a clustered columnstore index:

Change Data Capture cannot be enabled on a table with a clustered columnstore index. Consider dropping clustered columnstore index

But I need to have both CDC and clustered columnstore index on the same table.
Is there any workaround to this limitation?

A: The workaround to this is to enable CDC first and then to create a clustered columnstore index.

*

*Drop a clustered columnstore index if exists.

*Enable CDC.

*Create a clustered columnstore index.

Voila! It works!


text:
Q: Abstract class to provide methods specific to extending class/object I have a large package of models which I'd like cleaning up. So basically, a model looks like;
case class ExampleModel(…) extends Model {
    …
}

object ExampleModel {
    def find = new Finder[Long, ExampleModel](classOf[Long], classOf[ExampleModel]) // very repetitive
    …
}

Now, I've been trying to define an abstract class that provides me a companion object specific find method;
abstract class Findable[T: ClassTag] {
  self: T => def find = new Finder[Long, T](classOf[Long], classOf[T])
}

But compilation fails with:
class type required but T found

What is the correct way to approach this?

A: You can't use T as self-type as it's unknown at the moment of class definition (same as you can't write class A[T] extends T), also you don't need to pass classOf when you have ClassTag, so should be enough to:
scala> class Finder[A: ClassTag, B: ClassTag](){def getA = classTag[A].runtimeClass}
defined class Finder

scala> abstract class Findable[T: ClassTag] {def find = new Finder[Long, T]}
defined class Findable

And finally:
scala> :paste
// Entering paste mode (ctrl-D to finish)

case class ExampleModel()
object ExampleModel extends Findable[ExampleModel]

// Exiting paste mode, now interpreting.

defined class ExampleModel
defined object ExampleModel

Note that T is case class ExampleModel here, but you could simply obtain the companion

A: why not just
class Findable[T](clazz: Class[T]) {
     def find(clazz: Class[T]) = new Finder(classOf[Long], clazz)
}

object ExampleModel extends Findable(classOf[ExampleModel])


text:
Q: MariaDB insert with strange results We currently have MariaDB setup version 5.5.38 on Fedora.
When we run the following statement using Java:
INSERT INTO swiped.Users (userid, password, deviceToken) VALUES( ?, ?, ?) ON DUPLICATE KEY UPDATE devicetoken = ?

We would expect it to either INSERT if the row doesn't already exist for the given key or UPDATE the existing one.
The UPDATE works fine but if we run this for a key that does not exist (say adsfadfafd4543545qefakdsf for example) in our database we get a random ID inserted. For example:
ID = 339

First of all there are only two rows in our database so there's no way ID should get a value of 339.


text:
Q: Does Lenovo IdeaPad 330s 15IKB 81F5 Support Western Digital SN Black 770 SSD I have Lenovo IdeaPad 330s, It comes with 1TB HDD, I want to know if, my laptop supports WD Black SN770. I know that my PC has a M.2 slot but not sure if it's PCIe or NVMe.
Here's the model on Lenovo official website: https://pcsupport.lenovo.com/in/en/products/laptops-and-netbooks/300-series/330s-15ikb/81f5/81f5006fus/yd04fk6k?linkTrack=Caps%3ABody_SearchProduct&searchType=6&keyWordSearch=YD04FK6K
Does my PC support, WD Black SN770 which is a NVMe SSD, I think my laptop may have SATA Slot, with M+B, does the M+B key slot support M key, I know this might not give me the rated performance, but I want to keep the SSD for future purposes too.
Can you please tell if it's Compatible

A: NVMe is PCIe x4
As per TFM (which I strongly advice you download, since it contains instructions on taking apart the laptop, and consumer grade machines are designed to be less maintainable in many cases) - it definitely supports m.2 PCIe/NVMe SSDs

There's no mentions of SATA in the hardware manual - and strangely its a little worse than some others I've seen since it dosen't actually tell you anything about slots
In theory you need to make sure yours is a 2280 drive, but frankly I've never seen one another size outside very specific applications like thin clients
So yeah, your drive should work with no issues


text:
Q: Can't change the port in Visual Studio 2015 Community Edition MSDN says there should be an option in the Properties pane to change the port.  There isn't.

How can you change the port of your local web server in Visual Studio 2015 community edition?
EDIT: I believe part of the problem may be that I'm doing a web site projet, not a web application project and those are different for how they allow you to access ports.
The bottom line is, I can't start up the server because something is using the same port.

A: The option doesn't exist in the enterprise edition either.  It seems to be stored in
[My Documents]\Visual Studio 2015\Projects[Your Web Site Name].vs\config\applicationhost.config
You should search for the current port number and replace it.

A: Bases on @levininja's comment, I managed to solve the error by following the below instructions:
Open visual studio solution file *.sln in your project folder and look for:
VWDPort = "54638"

The default port number may be different than mine. In my case it is 54638.
Change the port to the port number you want.


text:
Q: How to create a combination of features using numpy? Hello everyone I am trying to achieve this according to the docstring using chain,combinations_with_replacement from itertools.
data = np.array([[1, 2], [3, 4]])

data.uptodegree(2)

output = np.array([[1, 1, 2, 1, 2, 4], [1, 3, 4, 9, 12,16]])

Basically the calculations are 1, 1^1, 2^1, 1^2, 1^1 * 2^1, 2^2. With the first one just being included by default. I am not sure how to go about this at all. The last part is another example of how these numbers are calculated.
$$\phi_{degree}(x_i) = \begin{bmatrix} 1 & w_i & z_i & w_iz_i & w_i^2z_i & w_iz_i^2 & \dots & w_iz_i^{degree-1} & w_i^{degree} & z_i^{degree} \end{bmatrix} $$\n


text:
Q: (How) can I host a Haskell website build on Windows on CentOS / Ubuntu? I've built a website in Haskell (using Happstack) that I now want to host somewhere. I built it on Windows, using ghc to produce a file called website.exe. It's my first program in Haskell, and first website, but works very well when I run the .exe in Windows and type localhost:8000 into my browser.
I understand (from Q 51064865) that I need a VPS to host it, but what kind of OS do I need? I'd guess Windows, but that seems very expensive. Would my exe run on CentOS or Ubuntu? (tbh I'm not 100% sure what these are - but it seems a lot cheaper to get a VPS with them!) Can I make ghc compiler (running on Windows) generate an executable that would?
My objective is to host the website cheaply (I'm not expecting any income from it), and am open to any suggestions.
Sorry if the question is dumb/already answered somewhere.

A: Your .exe would not run on CentOS/Ubuntu without some kind of emulation. I would not recommend going down this path as it tends to run really slow in my experience. It has something to do with how thunks are allocated on Windows vs how thunks are allocated on Linux, and emulating one of them on the other is just asking for trouble.
If you google around, you can find people talking about cross compiling Haskell from Windows to Linux, but it seems rough.
If you want to run your website on CentOS or Ubuntu, then you should compile it on one of those distributions. If you aren't using anything that's Windows specific in your code, then you should just be able to compile your code for your target without changing anything (Haskell is much easier to work with on Linux in my experience).
Someone else suggested downloading a "live" distro, and that would probably be the easiest way to get started compiling your code for CentOS/Ubuntu.


text:
Q: Indy 9 403 error on https submission Having read all the problems with 403 errors and trying the fixes, I still get the 403 error with the following URL and code.  The two SSL DLL files are present in the directory, and the file being used, uploaddata.txt is in the working directory.  It is Delphi 7 with Indy 9.
URL:
https://mws.amazonservices.com/?AWSAccessKeyId=A*&Action=SubmitFeed&FeedType=_POST_FLAT_FILE_INVLOADER_DATA_&Merchant=A*&PurgeAndReplace=false&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-07-20T21%3A39%3A28Z&Version=2009-01-01&Signature=MRJFSuBsqdUE7SaoUFdXO5zY2YFOc4QjVxg0lOISSis%3D

    unit MWSDemo;
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, HTTPApp, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket,
  IdSSLOpenSSL, IdServerIOHandler, IdAntiFreezeBase, IdAntiFreeze,
  IdMultipartFormData;

type
  TForm1 = class(TForm)
  Button1: TButton;
  HTTPS: TIdHTTP;
  IdAntiFreeze1: TIdAntiFreeze;
  IdServerIOHandlerSSL1: TIdServerIOHandlerSSL;
  IdSSLIOHandlerSocket1: TIdSSLIOHandlerSocket;
  Memo1: TMemo;
  procedure Button1Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
uses hash, hmac, sha256, mem_util;

function GetMWSRequest : string;
var
  ctx: THMAC_Context;
   < more code here>
var
  UTC: TSystemTime;
begin
  GetSystemTime(UTC);
  AmazonTimestamp:=HTTPDecode(Format('%.2d', [UTC.wYear]) + '-'
    + Format('%.2d',         [UTC.wMonth]) + '-' +  Format('%.2d', [UTC.wDay]) + 'T'
    + Format('%.2d', [UTC.wHour]) + ':' + Format('%.2d',  [UTC.wMinute]) + ':' +
    Format('%.2d', [UTC.wSecond]) + 'Z');
  AmazonURL:='https://mws.amazonservices.com/?';
      < more code here>
  Result:=AmazonURL;
end;

procedure TForm1.Button1Click(Sender: TObject);
var URL, Response: string;
    Stream : TStringStream;
    Params: TIdMultipartFormDataStream;
begin
  URL := GetMWSRequest;
  HTTPS.Request.BasicAuthentication := true;
  HTTPS.Request.ContentType := 'text/html';
  IdSSLIOHandlerSocket1.SSLOptions.Method := TIdSSLVersion(sslvSSLv23);
  HTTPS.IOHandler := IdSSLIOHandlerSocket1;
  try
      Stream := TStringStream.Create('');
      Params := TIdMultipartFormDataStream.Create;
      Params.AddFile('File1', 'UploadData.txt','application/octet-stream');
    try
      HTTPS.Post(URL, Params, Stream);
      Memo2.Text := HTTPS.ResponseText;
    finally
      Stream.Free;
      Params.Free;
    end;
  except
       on E: Exception do
         ShowMessage('** Error: ' + e.Message);
  end;
end;

end.

Thanks for any help.  There are two of us having this problem, one in the U.S. and one in the U.K.

A: 403 means you are trying to access a URL that you do not have access to.  So either you are missing a required authentication step, or the authentication you are providing is wrong.


text:
Q: pdfinfo package for mac os x For my application I make use of the pdfinfo package on the production and test server (linux). Now I've setup a local envoirnement for developing but I need to install the same packages to make everything work fine. The only package I am currently missing is the pdfinfo package and it seems to be hard to find. Is this package somewhere available?

A: You have two choices here which will give you the information of a PDF document on OS X.
Using Xpdf
Using Xpdf most directly solves your problem. It is available via Homebrew and contains pdfinfo:
$ brew search xpdf
xpdf
$ brew install xpdf
...

You should then be able to use pdfinfo as normal:
$ pdfinfo Main.pdf
Title:          Title
Subject:        Some subject
Keywords:
Author:         Joe A. Bloggs
Creator:        LaTeX with hyperref package
Producer:       pdfTeX-1.40.16
CreationDate:   Tue Apr 12 18:59:38 2016
ModDate:        Tue Apr 12 18:59:38 2016
Tagged:         no
Form:           none
Pages:          10
Encrypted:      no
Page size:      595.276 x 841.89 pts (A4) (rotated 0 degrees)
File size:      60057 bytes
Optimized:      no
PDF version:    1.5

Using mdls
More generally, you could use mdls to list the metadata associated with any file:
$ mdls Main.pdf
kMDItemAuthors                 = (
    "Joe A. Bloggs"
)
kMDItemContentCreationDate     = 2016-04-12 17:56:08 +0000
kMDItemContentModificationDate = 2016-04-12 17:59:39 +0000
kMDItemContentType             = "com.adobe.pdf"
kMDItemContentTypeTree         = (
    "com.adobe.pdf",
    "public.data",
    "public.item",
    "public.composite-content",
    "public.content"
)

kMDItemCreator                 = "LaTeX with hyperref package"
kMDItemDateAdded               = 2016-04-12 17:56:08 +0000
kMDItemDescription             = "Some subject"
kMDItemDisplayName             = "Main.pdf"
kMDItemEncodingApplications    = (
    "pdfTeX-1.40.16"
)
kMDItemFSContentChangeDate     = 2016-04-12 17:59:39 +0000
kMDItemFSCreationDate          = 2016-04-12 17:56:08 +0000
kMDItemFSCreatorCode           = ""
kMDItemFSFinderFlags           = 0
kMDItemFSHasCustomIcon         = (null)
kMDItemFSInvisible             = 0
kMDItemFSIsExtensionHidden     = 0
kMDItemFSIsStationery          = (null)
kMDItemFSLabel                 = 0
kMDItemFSName                  = "Main.pdf"
kMDItemFSNodeCount             = (null)
kMDItemFSOwnerGroupID          = 20
kMDItemFSOwnerUserID           = 501
kMDItemFSSize                  = 60057
kMDItemFSTypeCode              = ""
kMDItemKind                    = "Portable Document Format (PDF)"
kMDItemLastUsedDate            = 2016-04-12 18:00:54 +0000
kMDItemLogicalSize             = 60057
kMDItemNumberOfPages           = 10
kMDItemPageHeight              = 841.89
kMDItemPageWidth               = 595.276
kMDItemPhysicalSize            = 61440
kMDItemSecurityMethod          = "None"
kMDItemTitle                   = "Title"
kMDItemUseCount                = 3
kMDItemUsedDates               = (
    "2016-04-11 23:00:00 +0000"
)
kMDItemVersion                 = "1.5"

You can then use the -name and -raw flags to extract a given piece of informations like this:
$ mdls -raw -name kMDItemNumberOfPages Main.pdf
10

Source


text:
Q: Hangman append progress not working properly My applyGuess method returns the user's progress after each guess, if his guess, in this case is a letter, is inside I append it (+=) to progress, and all the letters soon to be guessed are represented and printed on screen with '*' (stars). For example, the user guessed 'a' and the word has two a's; a***a* (The output) and, for second guess lets choose the letter 'n' if the user guesses 'n', we get; *n**** and not

an**a*

  public String applyGuess(char letterGuessed){
    boolean isLetterInside = hiddenWord.indexOf(letterGuessed) >= 0;
    char display;
    String progress;

    if (isLetterInside){
        for (char letter: hiddenWord.toCharArray()){
            display = '*';
            if (letter == letterGuessed){
                display = letterGuessed;
                }
            progress += display;
            }
    } else {
        misses++;
        }
    return progress;
}

Thank you!!

A: it looks like the output only displays a letter instead of an * if the letter is equal to letterGuessed.  in your second example you pass an "n" in which is not equal to "a" so it made it a * overwriting the old string.

A: This problem can be solved in several ways. One possible solution is:
Set<Character> previousGuesses = new HashSet<Character>();

public String applyGuess(char letterGuessed){
    boolean isLetterInside = hiddenWord.indexOf(letterGuessed) >= 0;
    char display;
    String progress;

    if (isLetterInside){
    previousGuesses.add(letterGuessed);
        for (char letter: hiddenWord.toCharArray()){
            display = '*';
            if (previousGuessess.contains(letter)){
                display = letter;
                }
            progress += display;
            }
    } else {
        misses++;
        }
    return progress;
}

A: What you might be able to do, is keep track of all the guesses that the user has made and build a new prompt on each successive guess.
private String hiddenWord = "banana";
private Set<Character> guesses = new HashSet<>();
private int misses;

public String applyGuess(char letterGuessed) {
    if (!guesses.contains(letterGuessed)) {
        guesses.add(letterGuessed);
        if (!hiddenWord.contains(Character.toString(letterGuessed))) {
            misses++;
        }
    }
    char[] progress = hiddenWord.toCharArray();
    for (int index = 0; index < hiddenWord.length(); index++) {
        if (!guesses.contains(hiddenWord.charAt(index))) {
            progress[index] = '*';
        }
    }
    return new String(progress);
}

What this basically does is checks to see if the user has already used this character or not (I did this so I wouldn't increment the misses count, but you're requirements might be different), adds the char to the list of guesses and then checks to see if the character is in the hiddenWord, if it isn't it increments the misses.
Because, regardless of what the user does, we need to produce a prompt, the last part of the method creates a char of the hiddenWord and loops over each character in the hiddenWord, where there isn't a matching guess in guesses, it updates the character at that position with a * character.
It then returns a String representation of the char array.
Doing something like...
System.out.println(applyGuess('n'));
System.out.println(applyGuess('a'));
System.out.println(applyGuess('b'));

Outputs
**n*n*
*anana
banana

for example


text:
Q: Selenium IDE - StoreElementPresent - Element Not found Hey guys,
I'm running a script using SELENIUM-IDE for Mozilla Firefox for web automation.
In the script, I'm searching the "next" button on the webpage and would like to know if it's available or not. If so, Click on it and go to the next page, if not restart the script.
When going on a page without the next button I get an error and a

"Test Case Failed"

Commands I Use:

    storeElementPresent
    css=a._3a693.coreSpriteRightPaginationArrow
    bool

    echo
    '${bool}'

    gotoIf
    '${bool}' == false
    STARTSCRIPT

    clickAndWait
    css=a._3a693.coreSpriteRightPaginationArrow

In the Log results I get:
[info] Executing: | storeElementPresent | css=a._3a693.coreSpriteRightPaginationArrow | bool |
[info] Executing: | echo : 'true'
[info] Executing: | gotoIf | '${bool}' == false | STARTSCRIPT |
[info] Executing: | clickAndWait | css=a._3a693.coreSpriteRightPaginationArrow |  |
[error] Element css=a._3a693.coreSpriteRightPaginationArrow not found
[info] Test case failed

Any ideas guys?

A: It is getting same css selector.Go to browser and inspect "next" button and copy xpath of this element to uniquely identify your element.


text:
Q: How to adjust the alignment of a mathematical expression in a text section? e.g. argmax I am using the following definition to generate the argmax operator:
\DeclareMathOperator*{\argmax}{\arg\!\max}

However the problem is when I use it in a part that some text exists because of the written argument under argmin the next line appears with a abnoraml distance in order to keep the distance from the argument under argmin. However when I use \frac for example, this time, the proportion adjusts itself to not to overlap with the next line. How can I change the above command to behave like the frac?
Examples:
\documentclass{article}
\usepackage{amsmath}

\DeclareMathOperator*{\argmax}{\arg\!\max}

\begin{document}
  This is a test. This is a test. $\argmax\limits_{x}{x^2}$ This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.
\end{document}

With output
As opposed to:
\documentclass{article}
\usepackage{amsmath}

\DeclareMathOperator*{\argmax}{\arg\!\max}

\begin{document}
This is a test. This is a test. $\frac{x}{x^2}$ This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.
\end{document}

With output

A: As far as I understand, you want to manually correct the vertical spacing, making it closer to this without your operator. I am afraid that the result will not be beautiful. An example of such a solution is the following (vertical spacing chosen by hand):
\documentclass{article}
\usepackage{amsmath}

%\DeclareMathOperator*{\argmax}{\arg\!\max}
\DeclareMathOperator*{\argmax}{argmax}

\begin{document}

  This is a test. This is a test. $\argmax\limits_{\raise3pt\hbox{$\scriptstyle x$}}{x^2}$ \vspace{-5pt}
 This is a test. This is a test. This is a test. This is a test. This is a test.  This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.
\end{document}


text:
Q: Web3j call contract method without credentials Already implemented the same solution in javascript(web3js) and c#(nethereum) and both of them allow to load smart contract with abi and deployed contract address. Right now I'm working in java environment(web3j) and to load smart contract I need to provide credentials.
I just want to call some static methods from contract, that doesn't require credentials. Is there any workaround to load contract without it? That way I'm not able to show contract data to user without giving credentials.
MyContract contract = MyContract.load(
    "0x32b0138BD1b9527E95f141319ECF9B2765e06C00",
    web3,
    credentials,
    new BigInteger("22000000000"),
    new BigInteger("510000")
);

A: Since the operations you want to do don't require any Eth to execute, it doesn't matter what credentials you're using to do this. So you can just generate a new keypair, and use this.
Credentials dummyCredentials = Credentials.create(Keys.createEcKeyPair());

MyContract contract = MyContract.load(
    "0x32b0138BD1b9527E95f141319ECF9B2765e06C00",
    web3,
    dummyCredentials,
    new BigInteger("22000000000"),
    new BigInteger("510000")
);


text:
Q: Bad handshake or ECONNRESET Azure Mysql Nodejs Similar issues have been reported, but I can't work around with there solutions.
I have an express.js app using KNEX to connect to a mysql database hosted in Azure.
I can connect to the DB perfectly from console command or mysql workbench.
However, no way to achieve the same from my node app.
My connection object is the same though:
config.knex = require('knex')({
    client: 'mysql',
    connection: {
        host: 'wineserver.mysql.database.azure.com',
        user: 'BurgerAndGreenBeans@wineserver',
        password: 'FromageDeChevre',
        database: 'gdpr',
        insecureAuth: true
    },
    pool: {
         min: 0
    },
    debug: ['ComQueryPacket']
});

Everytime I start the app, I get alternatively either one error or another one:
#1
Unhandled rejection Error: read ECONNRESET
at exports._errnoException (util.js:1050:11)
at TCP.onread (net.js:582:26)
--------------------
at Protocol._enqueue (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:141:48)
at Protocol.handshake (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:52:41)
at Connection.connect (C:\Projects\gdpr\node_modules\mysql\lib\Connection.js:130:18)
at C:\Projects\gdpr\node_modules\knex\lib\dialects\mysql\index.js:106:18
at Promise._execute (C:\Projects\gdpr\node_modules\bluebird\js\release\debuggability.js:300:9)
at Promise._resolveFromExecutor (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:483:18)
at new Promise (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:79:10)
at Client_MySQL.acquireRawConnection (C:\Projects\gdpr\node_modules\knex\lib\dialects\mysql\index.js:104:12)
at Object.create (C:\Projects\gdpr\node_modules\knex\lib\client.js:239:16)
at Pool._createResource (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:354:17)
at Pool.dispense [as _dispense] (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:314:10)
at Pool.acquire (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:436:8)
at C:\Projects\gdpr\node_modules\knex\lib\client.js:289:19
at Promise._execute (C:\Projects\gdpr\node_modules\bluebird\js\release\debuggability.js:300:9)
at Promise._resolveFromExecutor (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:483:18)
at new Promise (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:79:10)

Process finished with exit code 0
or
#2
Unhandled rejection Error: ER_HANDSHAKE_ERROR: Bad handshake
at Handshake.Sequence._packetToError (C:\Projects\gdpr\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
at Handshake.ErrorPacket (C:\Projects\gdpr\node_modules\mysql\lib\protocol\sequences\Handshake.js:103:18)
at Protocol._parsePacket (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:280:23)
at Parser.write (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Parser.js:75:12)
at Protocol.write (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Projects\gdpr\node_modules\mysql\lib\Connection.js:103:28)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:561:20)
--------------------
at Protocol._enqueue (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:141:48)
at Protocol.handshake (C:\Projects\gdpr\node_modules\mysql\lib\protocol\Protocol.js:52:41)
at Connection.connect (C:\Projects\gdpr\node_modules\mysql\lib\Connection.js:130:18)
at C:\Projects\gdpr\node_modules\knex\lib\dialects\mysql\index.js:106:18
at Promise._execute (C:\Projects\gdpr\node_modules\bluebird\js\release\debuggability.js:300:9)
at Promise._resolveFromExecutor (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:483:18)
at new Promise (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:79:10)
at Client_MySQL.acquireRawConnection (C:\Projects\gdpr\node_modules\knex\lib\dialects\mysql\index.js:104:12)
at Object.create (C:\Projects\gdpr\node_modules\knex\lib\client.js:239:16)
at Pool._createResource (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:354:17)
at Pool.dispense [as _dispense] (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:314:10)
at Pool.acquire (C:\Projects\gdpr\node_modules\generic-pool\lib\generic-pool.js:436:8)
at C:\Projects\gdpr\node_modules\knex\lib\client.js:289:19
at Promise._execute (C:\Projects\gdpr\node_modules\bluebird\js\release\debuggability.js:300:9)
at Promise._resolveFromExecutor (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:483:18)
at new Promise (C:\Projects\gdpr\node_modules\bluebird\js\release\promise.js:79:10)
Process finished with exit code 0

It seems to be a kind of incompatibility between Node and Azure's mysql server.
Did anyone experienced the same ?

A: The similar question: Connecting to Azure Database for MySQL in npm/mysql. As @Gary Liu pointed out, you may use pull 1730 for a workaround.
Please modify the package.json as:
"dependencies": {
    "knex": "^0.13.0",
    "mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
 }

then, run npm install to install this version.


text:
Q: I need to make a vba that will set the endDate to the last day of the month I have 2 cells that one is starting date assigned as startDate and another cell assigned endDate. Everytime I click on the cell a calendar pops out and I enter the date. I want the macro to change the endDate to the last day of the month automatically. So when the user goes in and enters a start date the macro will input the end date which is the last day of that month. Here is the code I have right now:
Function dhLastDayInMonth(Optional endDate As Date = 0) As Date
    ' Return the last day in the specified month.
    If endDate = 0 Then
        ' Did the caller pass in a date? If not, use
        ' the current date.
        dtmDate = Date
    End If
    dhLastDayInMonth = DateSerial(Year(endDate), _
     Month(dtmDate) + 1, 0)
End Function

also Here is the code for the calendar:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
     'check cells for desired format to trigger the calendarfrm.show routine
     'otherwise exit the sub
    Dim DateFormats, DF
    DateFormats = Array("m/d/yy;@", "mmmm d yyyy")
    For Each DF In DateFormats
        If DF = Target.NumberFormat Then
            If CalendarFrm.HelpLabel.Caption <> "" Then
                CalendarFrm.Height = 191 + CalendarFrm.HelpLabel.Height
            Else: CalendarFrm.Height = 191
                CalendarFrm.Show
            End If
        End If
    Next
End Sub

A: In your endDate cell, you can use this formula:
=DATE(YEAR(startDate),MONTH(startDate)+1,0)

Where startDate is a named reference to your startDate cell.

A: If you are really keen on using your own VBA function then you can create a function such as this which basically gets the first day of the next month and subtracts 1 day from it to get the last day of the month.   I think Thunderframe's answer is best though as it is simple and uses the native functions of excel.
Public Function dhLastDayInMonth(Optional endDate As Date = 0) As Date
    Dim dt As Date
    'check if we have a date
    If endDate = 0 Then
        ' Did the caller pass in a date? If not, use
        ' the current date.
        dt = DateTime.Now
    Else
        dt = endDate
    End If
    'check for December
    If DatePart("m", dt) = 12 Then
        'add one to the year and month
        dt = DateSerial(DatePart("yyyy", DateAdd("yyyy", 1, dt)), DatePart("m", DateAdd("m", 1, dt)), 1)
    Else
        'add 1 to the month
        dt = DateSerial(DatePart("yyyy", dt), DatePart("m", DateAdd("m", 1, dt)), 1)
    End If
    'subtract 1 day from the date to get the last date of the month
    dt = DateAdd("d", -1, dt)
    'return the end of the month
    dhLastDayInMonth = dt
End Function

A:  EndDate = DateSerial(Year(Date), Month(Date) + 1, 0)

This vba function will also return the last day of the month for the present month. Change the Date  if a different month is needed.


text:
Q: Use of eval in a target recipe In a Makefile I'm writing I had an interest in cleaning up some of the CC prints and centralizing some of the build preparations (like creating directories in the build tree). I figured macros would be a good fit for this task. This is effectively what im trying to do, used all over various Makefiles:
define func
    @mkdir -p $$(dir $(1))
    @printf "%-5s $(2)\n" $(3)
endef

test:
    @echo Run
    $(eval $(call func,a,b,c))

My thought was that after first expansion I'd get something like (less any tabs maybe, I'm not exactly sure how the expansion works within eval):
test:
    @echo Run
    $(eval @mkdir -p $(dir a)\n@printf "%-5s b\n" c

and of course finally the commands would be executed. However, what I get is this:
# make
Makefile:7: *** recipe commences before first target.  Stop.

I changed eval to info and got this:
        @mkdir -p $(dir a)
        @printf "%-5s b\n" c
Run

So I thought maybe my explicit tabs in the macro definition were causing trouble, so I removed them and tried again:
# make
Makefile:7: *** missing separator.  Stop.

So it still does not quite work. If it is indeed possible at all, it seems some function of indentions in the macro, or maybe I'm defining the macros incorrectly. I thought perhaps the two commands in the macro was causing trouble (since the complaint is regarding a separator), but reducing the macro to a single line did not help either.

A: You don't want eval here.  Eval is used to evaluate makefile syntax.  That is, the thing you're evaluation has to be a valid, complete makefile.  You can see that what info prints is not a valid makefile.  If you put that into a file and ran make -f <file>, you'd get a syntax error.
You are just trying to expand a variable for shell syntax.  Just remove the eval.


text:
Q: getting word from id at Tensorflow RNN sample I'm trying to modify Tensorflow's RNN sample here.
https://www.tensorflow.org/versions/r0.8/tutorials/recurrent/index.html
At ptb_word_lm.py I guess they are inputting int array of word index (m.input_data:x).
def run_epoch(session, m, data, eval_op, verbose=False):
  """Runs the model on the given data."""
  epoch_size = ((len(data) // m.batch_size) - 1) // m.num_steps
  start_time = time.time()
  costs = 0.0
  iters = 0
  state = m.initial_state.eval()
  for step, (x, y) in enumerate(reader.ptb_iterator(data, m.batch_size,
                                                    m.num_steps)):
    cost, state, _ = session.run([m.cost, m.final_state, eval_op],
                                 {m.input_data: x,
                                  m.targets: y,
                                  m.initial_state: state})

I'd like to see actual words instead of ids, how can I see them?

A: You need to retain vocabulary ( which is an index from word to id ) first.
At the top of main, retain 4th returned value from reader.ptb_raw_data() like below.
raw_data = reader.ptb_raw_data(FLAGS.data_path)
train_data, valid_data, test_data, vocabulary = raw_data

Then pass the vocabulary to run_epoch().
test_perplexity = run_epoch(session, mtest, test_data, tf.no_op(), vocabulary)

Inside of the run_epoch(), when you want to convert ids to words in first step of x,
def run_epoch(session, m, data, eval_op, vocabulary, verbose=False):

...
for step, (x, y) in enumerate(...

message ="x: "
for i in range(0, m.num_steps):
    key = vocabulary.keys()[vocabulary.values().index(x[0][i])]
    message += key + " "

print(message)

Hope it helps.


text:
Q: Word order when referring things by their names What word order must be used when referring things like functions, vectors, roads, etc. For example, for a road or a function named "A":

*

*
I'm going to take ['A' road or road 'A'].

*
See [function 'A' or 'A' function].

A: For roads you are referring to the name of the road, The word road may be part of the name, or it may not

I'm going to take Park Road.
  I'm going to take Comely Lane.
  I'm going to take the B2112.  (not B2112 road)

In a paper, the word "function" &c. precedes its name or number

See equation (1)
  Q2  (short for question two)
  Figure 4.3 shows this relationship.


text:
Q: WP7 Custom Class UI Binding Issue I have a map with a MapItemsControl in my WP7 app that contains pushpins bound to items in a collection of custom classes.  The pushpins are bound to properties of the item in the collection via a DataTemplate.
When an item is added to or removed from the collection, all pins display correctly, with properties as per bindings, but when just an items' properties are modified, the UI does not update.  The bindings just seem to get values from the source item upon loading, but I'd like them to keep the UI elements updated when the source collection items' properties are updated.
To illustrate, I'll create a similar example:
Here's a custom class:
Public Class Box
    Property CurrentColor As Color
    Property Location As GeoCoordinate
End Class

There's a collection of them:
Dim TempBoxes As ObservableCollection(Of Box)

My map control has a MapItemsControl in it:
<maps:MapItemsControl Name="BoxControl"
    ItemTemplate="{StaticResource BoxTemplate}"
    ItemsSource="{Binding TempBoxes}"/>

The item template is something like this:
<DataTemplate x:Key="BoxTemplate">
    <maps:Pushpin Location="{Binding Location}" ManipulationStarted="BoxTouched">
        <maps:Pushpin.Template>
            <ControlTemplate>
                <Ellipse Width="35" Height="35" Margin="54,148,366,584"
                    Stretch="Fill" StrokeThickness="4" Stroke="Black"
                    Fill="{Binding CurrentColor}" />
            </ControlTemplate>
        </maps:Pushpin.Template>
    </maps:Pushpin>
</DataTemplate>

The touch event handler switches the pin's color between blue and red:
Private Sub BoxTouched(ByVal sender As Object, ByVal e As RoutedEventArgs)
    With DirectCast(DirectCast(sender, Pushpin).DataContext, Box)
        If .CurrentColor = Colors.Red Then
            .CurrentColor = Colors.Blue
        Else
            .CurrentColor = Colors.Red
        End If
    End With
End Sub

Whenever I add or remove items from TempBoxes, the pins all render as they should (e.g. if I specify a color in the collection item, the pin shows the color).
Tapping on the item triggers the BoxTouched sub, which causes the item's color to change in the collection, but the UI doesn't change (pin color stays the same).
To get the UI to update the color, I have to get it to render the pins again, by adding something like this to BoxTouched:
BoxControl.ItemsSource = Nothing
BoxControl.ItemsSource = TempBoxes

I'm assuming there's a better way to do this?

A: In order for the DataTemplate to respond to changes in property values for your data object you need to implement the INotifyPropertyChanged interface on your data object so that property change notification is raised when your properties change.
Take a look at the VB samples in the MSDN documentation if you're unsure how to do this.


text:
Q: Deleting overlapping lines in QGIS I had to digitize a geologic map. I've made all the polygons for the different units. Now I want to make the contacts/line styles for each polygon. Some contacts are definite, solid line, while other are inferred, dashed line. So it requires 2 different line types. If I make dashed lines for the inferred polygons, then the polygons that have lines on top of one another may look like a solid line. I went ahead and generated another layer with the polygons and used Polygons to Lines in QGIS. Now I want to delete the overlapping lines. So far none of the processes in QGIS are working. Does anyone have a technique for doing this?
I want to have one line that is doesn't have overlapping lines underneath.


text:
Q: Trying to create grouped records with linq I have records like this in 1 list :
Id     Title     Name      Basic     Message
10     Stats2    abc       10         sldjs
10     Stats2    pqr       20         sldjs
10     Stats2    xyz       30         sldjs
10     Stats2    abc       40         sldjs

11     Stats3    aaa       0         sldjs
11     Stats3    bbb       0         sldjs
11     Stats3    ccc       0         sldjs
11     Stats3    ddd       0         sldjs

I have a variable of type List of class which hold below records:
var list = new List<Stats>();//this variable hold all above records.

Now I am trying to create records like below from list variable :
[0]:Stats2:
        abc
            10  sldjs
            40  sldjs
        pqr
            20  sldjs
        xyz
            30  sldjs

[1]:Stats3:
        aaa
            0  sldjs
        bbb
            0  sldjs
        ccc
            0  sldjs
        ddd
            0  sldjs

This is how I am trying but not getting how to create inner nested children like (2 abc records shown above):
var data =list.GroupBy(ed =>ed.Id)
               .Select
               (

               )

A: var data =list.GroupBy(p => p.Title).Select(p => new
            {
                Title = p.Key,
                Items = p.GroupBy(q => q.Name)
                         .ToDictionary(q => q, q => new { q.Basic, q.Message })
            });

A: You need to group the inner records as well. The result could be something like a Dictionary<int, Dictionary<string, List<Stats>>>. The keys of the outer dictionary would be the ID values and the inner keys the Name values and the values would be lists of the Stats having that Title and Name:
var result = list.GroupBy(rec => rec.ID)
                 .ToDictionary(
                     group => group.Key,
                     group => group.GroupBy(stat => stat.Name)
                                   .ToDictionary(g => g.Key, g => g.ToList())
                              );

You can access the values in the result like that:
result[10]["abc"]

The above example would be a list containing the Stats with Basic10 and 40.

If you only want to keep Basic and Message in the final records, you can use Select to project the Stats to an anonymous type:
var result = list.GroupBy(rec => rec.ID)
                 .ToDictionary(
                     group => group.Key,
                     group => group.GroupBy(stat => stat.Name)
                                   .ToDictionary(g => g.Key, g => g.Select(stat => new {stat.Title, stat.Basic, stat.Message}).ToList())
                              );


text:
Q: DMQL-Data Mining Query Language I'm trying to get some references about DMQL but Google keep viewing the same results no matter what I do.
So any one have some references about DMQL and it's history and syntax ?

A: This is a bit of a wild guess but there is a workshop in ECML about Languages for Data Mining and Machine Learning. If you follow the committee members, some of them will probably have some references to DMQL... sorry not to be more helpful.


text:
Q: Subject-Verb agreement in sentences with "all I see," "all he hears," etc, In sentences like "All he can think of is this moment," all is taking singular is. However, in sentences where there is more than one subject, does all still take singular is?

*

*All he can hear is the wind, the sound of the rain, and the thunder.

*All that's present at the end of the hall is the storage and another room.

Do both these sentences take "all...is"? Could this be explained with a grammatical rule? In these sentences, is all referring back to predicate nominatives?


text:
Q: Reference of an object to a Session property I have a text box in my aspx page, I created a Session property (textbox type), then:
textBoxInSession = myTextBox;
If I change the Text property in textBoxInSession, the Text property in myTextBox does not changed.
isn't textBoxInSession a reference to myTextBox?

A: In general, you should not persist UI elements/controls to the Session or Application state. When you store an object instance, you pin it and everything that holds a reference to it in memory. Because ASP.NET creates a new instance on each page execution, this can result in considerable amounts of memory being consumed by non-garbage-collectible Page and Control instances, if you make heavy use of this technique.
You should store value types, strings and serializable POCOs or business layer types instead, and rebind them to UI controls when you need them.

A: When your page serves a new Request, it's a new instance of the page, containing new instances of your controls. So that TextBox is another instance than what you stored in Session on a previous Request.

A: The testBixInSession is a copy of your page text box, not a reference.

A: Each request for a page is handled by a different thread, and a new instance of your class is created for that request. The Textbox stored in Session is the TextBox from the previous instance of your class from the previous page request.
The behavior you expect will work if it is during the same request. However that really serves no purpose since you can reference the TextBox directly.


text:
Q: Nuxt js dynamic route not work after generate in my project i am using nuxt js. I have a route looks like
service/:slug
After build and generate my all route works perfectly.Bellow code I use to generate dynamic route on generate
  generate: {

    routes(callback) {
      axios
        .get('url')
        .then(res => {
          const routes = res.data.data.map(service => {
            return '/services/' + service.slug
          })
          callback(null, routes)
        })
        .catch(callback)
      axios
        .get('https://url')
        .then(res => {
          const routes = res.data.data.map(offer => {
            return '/campaigns/' + offer.slug
          })
          callback(null, routes)
        })
        .catch(callback)
    }
  }

But problem occurs when I create another new item from admin panel after build and generate.
seems I have three route when I run nuxt generate

*

*service/cash

*service/profit

now after host my dist folder in server then I hit www.url/service/cash and its work perfectly.
Now I create a new service item in admin panel called send-money
Then when I hit on browser using www.url/service/send-money
Its not working and get 404.
now I cant understand how can I solve this situation.

A: When using SSG nuxt only generates the available pages in your project. This is how SSG works. Therefore, you need to create a custom script in your server to run yarn build && yarn generate command after creating new page.
For example, let us assume you are creating a blog. When you use yarn generate, nuxt generates the posts fetched from the database at that specific time and moves them inside dist folder. Therefore, you need to attach a custom script -which you need to somehow create in the backend- to run yarn build && yarn generate after creation of a new post.

A: If you're using something like firebase static hosting...you only need to make sure you have wildcard rewrites rules in place to prevent 404 errors. In this case this is what I have in my firebase.json files.
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]


text:
Q: Is there a way to change my file path automatically and apply a function in R? I'm looking to apply the 'multiple_sounds' function to a list of .WAV files from a folder using R. This is my current code:
##### 1 #####
setwd("E:/Audiomoth Files/Winter/Rural/Emma/_1")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "ndsi_results.csv", soundindex = "ndsi", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "adi_results.csv", soundindex = "acoustic_diversity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "aei_results.csv", soundindex = "acoustic_evenness", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "aci_results.csv", soundindex = "acoustic_complexity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "H_results.csv", soundindex = "bioacoustic_index", no_cores = "-2")

##### 2 #####
setwd("E:/Audiomoth Files/Winter/Rural/Emma/_2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "ndsi_results.csv", soundindex = "ndsi", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "adi_results.csv", soundindex = "acoustic_diversity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "aei_results.csv", soundindex = "acoustic_evenness", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "aci_results.csv", soundindex = "acoustic_complexity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "H_results.csv", soundindex = "bioacoustic_index", no_cores = "-2")

This works, but at the moment I have to copy and paste this code each time for each folder(_1, _2, _3 etc.) of which there are 623, so doing this manually is very time consuming.
Is there a way I can automate the file path to change the directory to go to _3, _4, _5 automatically and apply the function in a loop all the way to the 623rd folder?
Thank you in advance

A: I would suggest writing a utility function and using the directory as an input:
apply_wav_index = function(
  dir,
  index = c("ndsi", "acoustic_diversity", "acoustic_evenness", "acoustic_complexity", "bioacoustic_index"),
  labels = c("ndsi", "adi", "aei", "aci", "H"),
  ...
) {
  if(length(index) != length(labels)) stop("Must provide same number of labels and indexes")
  for(i in seq_along(index)) {
    multiple_sounds(
      directory = dir,
      resultfile = paste0(dir, "/", labels[i], "_results.csv"),
      soundindex = index[i],
      ...
    )
  }
}

Then you should be able to call it like this:
for(i in 1:6) {
  apply_wav_index(dir = paste0("E:/Audiomoth Files/Winter/Rural/Emma/_", i), no_cores = "-2")
}

You could also potentially generate the list of directories with list.dirs().


text:
Q: primitive roots and quadratic residues prove that if p congruent to 3 (mod 4) is a prime and g is a primitive root mod p, then p - g is not a primitive root mod p.
p-g must be congruent to g^m mod p for some m, and if i want to show p - g is not a primitive root, then gcd(m,p-1) must not be 1, but I don't know how to proceed

A: Note that $g^{(p-1)/2} \ne 1 \mod p$ since $g$ is a primitive root, but since $(g^{(p-1)/2})^2 = g^{p-1} = 1 \mod p$ we must have $g^{(p-1)/2} = -1 \mod p$.
Now we can check directly that $p-g = -1\cdot g\mod{p}$ is not a primitive root.  We have $(p-g)^{(p-1)/2} = (-1)^{(p-1)/2}g^{(p-1)/2} = (-1)(-1) = 1 \mod p$.  Here we use the fact that $(p-1)/2$ is odd since $p = 3\mod 4$.
Another way of framing this is that your hypotheses imply that neither $g$ nor $-1$ are quadratic residues (ie, there is no value squaring to them), and the produce of two quadratic non-residues will always be a quadratic residue.


text:
Q: Sorting complete pandas data frame by a column while preserving sequence order The idea follows; the whole data frame should be ordered by column 4 while keeping the exact sequence of information in every row when sorting by df_train[4] (e.g 'Table1', 'Table1', 'Table1', 'Table2','Table2', 'Table3','Table3', 'Table4)
Attempts and outputs:
import pandas as pd
from pandas import np

df_train = pd.DataFrame({1: ['1234', '4321','4321', '3241', '5432','5821', '4442', '4567', '0952','0952','7426','4422','4121','8885','4231','5932','5932','5555','0532','1111','5555','6321','6321','9955','3333','3333','3333','4132']})
df_train[2] = ['Mayo', 'Mango','Mango','Apple','Kiwi','Watermelon','Orange','Peach','Broccoli','Broccoli','Name','Surname','Location','Carrots','Salad','Water','Water','Wine','Beer','Cup','Rose','Flower','Flower','Paint','Van','Van','Van','Car']
df_train[3] = ['1','2','2','1','1','1','1','1','2','2','1','1','1','1','1','2','2','1','1','1','1','2','2','1','3','3','3','1']
df_train[4] = ['Table1','Table1','Table1','Table2','Table2','Table3','Table3','Table4','Table4','Table4','Table1','Table1','Table1','Table1','Table2','Table2','Table2','Table3','Table4','Table4','Table1','Table1','Table1','Table2','Table3','Table3','Table3','Table4']

output:
    1        2          3      4
0   1234    Mayo        1   Table1
1   4321    Mango       2   Table1
2   4321    Mango       2   Table1
3   3241    Apple       1   Table2
4   5432    Kiwi        1   Table2
5   5821    Watermelon  1   Table3
6   4442    Orange      1   Table3
7   4567    Peach       1   Table4
8   0952    Broccoli    2   Table4
9   0952    Broccoli    2   Table4
10  7426    Name        1   Table1
11  4422    Surname     1   Table1
12  4121    Location    1   Table1
13  8885    Carrots     1   Table1
14  4231    Salad       1   Table2
15  5932    Water       2   Table2
16  5932    Water       2   Table2
17  5555    Wine        1   Table3
18  0532    Beer        1   Table4
19  1111    Cup         1   Table4
20  5555    Rose        1   Table1
21  6321    Flower      2   Table1
22  6321    Flower      2   Table1
23  9955    Paint       1   Table2
24  3333    Van         3   Table3
25  3333    Van         3   Table3
26  3333    Van         3   Table3
27  4132    Car         1   Table4

Attempt 1 & 2:
df_train2 = df_train.sort_values(4, ignore_index=True) #
df_train2 = df_train.sort_values(4, ignore_index=False) #same issue

The output is ordered by all the targeted column 4 but the sequence is rather arbitrary no matter of indices:
    1        2          3     4
0   1234    Mayo        1   Table1
1   6321    Flower      2   Table1 -> should be: 4321, Mango, 2, Table1
2   6321    Flower      2   Table1 -> should be: 4321, Mango, 2, Table1
3   5555    Rose        1   Table1 -> should be: 7426, Name, 1, Table1
4   4121    Location    1   Table1 -> should be: 4422, Surname, 1, Table1
5   4422    Surname     1   Table1 -> should be: 4121, Location, 1, Table1
6   7426    Name        1   Table1 ...etc
7   8885    Carrots     1   Table1
8   4321    Mango       2   Table1
9   4321    Mango       2   Table1
10  5432    Kiwi        1   Table2
11  4231    Salad       1   Table2
12  5932    Water       2   Table2
13  5932    Water       2   Table2
14  9955    Paint       1   Table2
15  3241    Apple       1   Table2
16  5555    Wine        1   Table3
17  3333    Van         3   Table3
18  4442    Orange      1   Table3
19  5821    Watermelon  1   Table3
20  3333    Van         3   Table3
21  3333    Van         3   Table3
22  0952    Broccoli    2   Table4
23  0532    Beer        1   Table4
24  4567    Peach       1   Table4
25  0952    Broccoli    2   Table4

Attempt 3 & 4:
# Attempt 3:
df_train3 = df_train.copy()
df_train3.loc[3:] = df_train3.loc[3:].sort_values(4).set_index(df_train3.loc[3:].index)

Didn't get the desired output even when slicing from the 3rd row
# Attempt 4:
isolate_digit = []
for indx,row in df_train.iterrows():
    isolate_digit.append( int(''.join(filter(str.isdigit,row[4]))))

df_train['order'] = isolate_digit

Tried even isolating from the 4th column it's integer, thought maybe since it's a string ('Table1'..etc) that the alg doesn't preserve the order because of it, still not solving the issue.
Desired output, by slicing manually:
# Manually slicing desired output:

df_table_seq1 = df_train.iloc[0:3]  # Table1 sequence
df_table_seq2 = df_train.iloc[10:14] # Table1 seuqence
df_table_seq3 = df_train.iloc[20:23] # Table1 sequence

df_table_seq4 = df_train.iloc[3:5]  # Table2 sequence
df_table_seq5 = df_train.iloc[14:17] # Table2 seuqence
df_table_seq6 = df_train.iloc[23:24] # Table2 sequence

df_table_seq7 = df_train.iloc[5:7]  # Table3 sequence
df_table_seq8 = df_train.iloc[17:18] # Table3 seuqence
df_table_seq9 = df_train.iloc[24:27] # Table3 sequence

df_table_seq10 = df_train.iloc[7:10] # Table4 seuqence
df_table_seq11 = df_train.iloc[18:20] # Table4 sequence
df_table_seq12 = df_train.iloc[27:28] # Table4 sequence

df_final = df_table_seq1+df_table_seq2

df_final = pd.concat([df_table_seq1,df_table_seq2,df_table_seq3,df_table_seq4,df_table_seq5,df_table_seq6,df_table_seq7,df_table_seq8,df_table_seq9,df_table_seq10,df_table_seq11,df_table_seq12], sort = False)

Output and as it should be:
    1         2          3      4      order
0   1234    Mayo         1    Table1    1
1   4321    Mango        2    Table1    1
2   4321    Mango        2    Table1    1
10  7426    Name         1    Table1    1
11  4422    Surname      1    Table1    1
12  4121    Location     1    Table1    1
13  8885    Carrots      1    Table1    1
20  5555    Rose         1    Table1    1
21  6321    Flower       2    Table1    1
22  6321    Flower       2    Table1    1
3   3241    Apple        1    Table2    2
4   5432    Kiwi         1    Table2    2
14  4231    Salad        1    Table2    2
15  5932    Water        2    Table2    2
16  5932    Water        2    Table2    2
23  9955    Paint        1    Table2    2
5   5821    Watermelon   1    Table3    3
6   4442    Orange       1    Table3    3
17  5555    Wine         1    Table3    3
24  3333    Van          3    Table3    3
25  3333    Van          3    Table3    3
26  3333    Van          3    Table3    3
7   4567    Peach        1    Table4    4
8   0952    Broccoli     2    Table4    4
9   0952    Broccoli     2    Table4    4
18  0532    Beer         1    Table4    4
19  1111    Cup          1    Table4    4
27  4132    Car          1    Table4    4

A: Make a helper column that is a copy of the index then sort by column 4 and the helper column
df['sort_helper'] = df.index
df.sort_values(['4', 'sort_helper'])


text:
Q: PHP ip2long only picking up last entry if input from a text file Sorry if this has been asked before, but my search didn't yield much help. I'm having some issues incorporating the PHP built-in function 'ip2long' in my script. The input IP addresses are coming from a text file and the function is only picking up the last address on the list to do the conversion on. I'm running the script on a 32-bit machine if that gives a clue to the problem.
<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
    echo "Begin IP Convertion \n";
    while ($line = fgets($file)) {
        echo "$line = " . ip2long($line) . "\n";
    }
} else {echo "No file found \n";}

fclose($file);
?>

Here are the contents of the ip.txt file:
127.0.0.1
1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4

Result upon running the script:
# php ip.php
Begin IP Convertion
127.0.0.1
 =
1.1.1.1
 =
2.2.2.2
 =
3.3.3.3
 =
4.4.4.4 = 67372036
#

-Jon

A: You must remove the newlines from the string using something like trim
<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
    echo "Begin IP Convertion \n";
    while ($line = fgets($file)) {
        echo trim($line) . " = " . ip2long(trim($line)) . "\n";
    }
} else {echo "No file found \n";}

fclose($file);
?>


text:
Q: Printing Lists in Haskell new Brand new to haskell and I need to print out the data contained on a seperate row for each individual item
Unsure on how to
type ItemDescr = String
type ItemYear = Int
type ItemPrice = Int
type ItemSold = Int
type ItemSales = Int
type Item = (ItemRegion,ItemDescr,ItemYear,ItemPrice,ItemSold,ItemSales)
type ListItems = [Item]

rownumber x
 | x == 1  = ("Scotland","Desktop",2017,900,25,22500)
 | x == 2  = ("England","Laptop",2017,1100,75,82500)
 | x == 3  = ("Wales","Printer",2017,120,15,1800)
 | x == 4  = ("England","Printer",2017,120,60,7200)
 | x == 5  = ("England","Desktop",2017,900,50,45000)
 | x == 6  = ("Wales","Desktop",2017,900,20,18000)
 | x == 7  = ("Scotland","Printer",2017,25,25,3000)

showall
--print??

So for example on each individual line
show
"Scotland","Desktop",2017,900,25,22500
followed by the next record

A: Tip 1:
Store the data like this
items = [("Scotland","Desktop",2017,900,25,22500),
         ("England","Laptop",2017,1100,75,82500),
         ("Wales","Printer",2017,120,15,1800),
         ("England","Printer",2017,120,60,7200),
         ("England","Desktop",2017,900,50,45000),
         ("Wales","Desktop",2017,900,20,18000),
         ("Scotland","Printer",2017,25,25,3000)]

Tip 2:
Implement this function
toString :: Item -> String
toString = undefined -- do this yourselves

Tip 3:
Try to combine the following functions

*

*unlines, already in the Prelude

*toString, you just wrote it

*map, does not need any explanation

*putStrLn, not even sure if this is a real function, but you need it anyway.

*($), you can do without this one, but it will give you bonus points


text:
Q: How to re-enable Code Download from Google App Engine Is there anyway to re-enable the Code Download option from Google App Engine.  I stupidly and totally mouse-fluke clicked it and have no idea on how to re-enable that option back so that I can download it.
I was just in there looking at it.  It didnt even asks me for a confirmation!!
help

A: No, it's a one way setting. There's no way to' revert it.