text:
Q: Chrome extension how to force page show mobile view I use following code in crx background.js, but not enongh, google.com to mobile view but instagram.com still desktop
chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
        details.requestHeaders[i].value = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36";
        break;
      }
    }
    return {requestHeaders: details.requestHeaders};
  },
  {urls: ['<all_urls>']},
  ['blocking', 'requestHeaders']
);

I find chrome devtools > "toggle device" can force instagram show mobile view, so how to do same thing in chrome extension?

A: I find the solution:
in short
Not only change http request header "User-agent", but also change js "navigator.userAgent"
Detail
I use "Save All Resources" download all instagram js to local: https://chrome.google.com/webstore/detail/save-all-resources/abpdnfjocnmdomablahdcfnoggeeiedb?hl=en
and I use intellij idea search "mobile" and "isMobile" function(idea > navigate > symbol"
I find instagram is not used http request "User-Agent", it use js navigator.userAgent get userAgent
So I should change navigator.userAgent in crx content script and set content script document_start in crx manifest.json
following is content script, remember set content script "run_at" "document_start" in manifest.json
var actualCode =  '(' + function() {
    'use strict';
    var navigator = window.navigator;
    var modifiedNavigator;
    if ('userAgent' in Navigator.prototype) {
        // Chrome 43+ moved all properties from navigator to the prototype,
        // so we have to modify the prototype instead of navigator.
        modifiedNavigator = Navigator.prototype;
    } else {
        // Chrome 42- defined the property on navigator.
        modifiedNavigator = Object.create(navigator);
        Object.defineProperty(window, 'navigator', {
            value: modifiedNavigator,
            configurable: false,
            enumerable: false,
            writable: false
        });
    }
    // Pretend to be Windows XP
    Object.defineProperties(modifiedNavigator, {
        userAgent: {
            value: "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36",
            configurable: false,
            enumerable: true,
            writable: false
        },
        appVersion: {
            value: "5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36",
            configurable: false,
            enumerable: true,
            writable: false
        },
        platform: {
            value: "Linux x86_64",
            configurable: false,
            enumerable: true,
            writable: false
        },
    });
} + ')();';
var s = document.createElement('script');
s.textContent = actualCode;
document.documentElement.appendChild(s);
s.remove();

above code how to get mobile view "userAgent", "appVersion", "platform"? chrome devtools > toggle device, when page is in mobile view, in devtools console, navigate.userAgent, navigate.appVersion, navigate.platform
update:
I find following code is important:
 var s = document.createElement('script');
    s.textContent = actualCode;
    document.documentElement.appendChild(s);
    s.remove();

If use document.addEventListener("DOMContentLoaded" and change navigator.userAgent, userAgent cannot be changed


text:
Q: I tried Solving a recurrence by guessing then proving by induction, but something went wrong For the following recurrence I have ti find the Big-O complexity O().
T(n) = 2T(n/2) + cn
T(1)=c1
I guessed its T(n) = O(n).
Induction hypothesis : T(n)<= ak for all k < n .
T(n) = 2T(n/2) + c*n
T(n) <= 2(a*(n/2)) + c*n
<= an +cn
=O(n)
I find it completely correct but my TA graded me 0 in this , Where do you think I went wrong ?

A: The so-called Master Theorem, case 2, states that
T(n) = Theta(n log n)

for your example. Furthermore, if T(n) = O(n) would be true, Quicksort (for which the above recurrence relation is satisfied) would have a linear runtime complexity, which is also not the case.
Concerning your argument, apparently you state that there exists a constant a such that
T(n) <= a*n

holds. Consequently, the induction hypothesis should be as follows.
T(k) <= a*k for each k < n

But even if this is assumed, the induction step proves that
T(n) <= (a+c)*n

holds; however, this does not prove the desired property as it does not prove that
T(n) <= a*n

holds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: About LinearLayout and how controls resize Today I have been playing a bit with the LinearLayout and have been suprised with the results:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Big Text"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
   android:id="@+id/textView2"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:text="Medium Text"
   android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:text="Button"
   />

</LinearLayout>

This is a simple layout with a text view header, then a text view that I want it to cover all parent (but the space occupied by the bottom button) and a button that is placed at the botton side with the layout_gravity="bottom".
This produces a layout where header is shown correctly, center text view covers all remaining free space and the button does not appear. Why is this? Shouldn't the center text view just calculate its size taking into account the bottom button size?.

A: Use layout_weight="1" in your center TextView.

A: Always remember thumb rule
If you are using linear layout with vertical orientation as soon as it finds the control
with
android:layout_height="match_parent"
The layout will ignore all the controls present below it.
Hope this help
Vipul

A: In place of  this
 android:layout_width="match_parent"
 android:layout_height="match_parent"

use 'wrap_content' like this
  android:layout_width="wrap_content"/"fill_parent"
  android:layout_height="wrap_content"/"fill_parent"

A:
Shouldn't the center text view just calculate its size taking into account the bottom button size?.

No, because you tell the second TextView to match its parent's height, thus FILL_PARENT and hence it will fill up all remaining space, leaving none for the last TextView.

(...) and a button that is placed at the botton side with the layout_gravity="bottom".

Unfortunately, that's not how a LinearLayout works. If you set the orientation to vertical, basically only the left and right gravities will have effect. Vice versa, with the (default) horizontal orientation, only top and bottom work. The orientation determines in which direction the View children are dynamically positioned in order, which implies you cannot manually change the 'position' in that direction.
Now, to get the desired effect, you can give the second TextView a height of 0dp and a weight of 1, resulting in it dynamically filling up all remaining space without pushing the third TextView off the bottom. Alternatively, you can use a RelativeLayout, with which you can directly set the position, and simply instruct the middle TextView to sit below the first, but above the last.


text:
Q: unable to download video created using moviepy in django I am trying to import a video, add a watermark and then download the processed video in django using moviepy.
The problem is that I am able to save the processed video to my computer by specifying an absolute path to the computer drive. However, I have not been able to download this processed video. I have tried researching on the internet. However, no luck till now.
 below is my code:
views.py
from django.shortcuts import render
import numpy as np
from .forms import UploadFileForm
import tempfile
import os
from django.core.files.storage import default_storage
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
import sys
import moviepy.editor as mp

from .utils import CFEVideoConf, image_resize

# Create your views here.
def watermark(request):
    if request.method=="GET":
        form = UploadFileForm()
        return render(request, 'video_et.html', {'form':form})
    else:
        if request.method=="POST":
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                fs = FileSystemStorage(location='/media')
                x = bytes()
                #arr=cv2.VideoWriter()
                image = request.FILES['Watermark_Image']
                video = request.FILES['Video_File']
                print("Name of the Watermark Image: ", image.temporary_file_path())
                print("Name of the Video: ", video.name)

                file_name1 = default_storage.save(video.name, video)
                file1 = default_storage.open(file_name1)
                file_url1 = default_storage.url(file_name1)
                print("file url= ",file_url1)
                url_now1 = "http://127.0.0.1:8000/"+file_url1

                #image = request.FILES['Watermark_Image'].read()

                file_name2 = default_storage.save(image.name, image)
                file2 = default_storage.open(file_name2)
                file_url2 = default_storage.url(file_name2)
                print("file url= ",file_url2)
                url_now2 = "http://127.0.0.1:8000/"+file_url2

                video = mp.VideoFileClip(url_now1)

                logo = (mp.ImageClip(url_now2)
                          .set_duration(video.duration)
                          .resize(height=50) # if you need to resize...
                          .margin(right=8, top=8, opacity=0) # (optional) logo-border padding
                          .set_pos(("right","top")))

                final = mp.CompositeVideoClip([video, logo])
                final.write_videofile("C:\\Users\\win10\\Desktop\\experiment\\django-poc\\media\\test.mp4")
                response = HttpResponse(video, content_type="video/mp4")
                response['Content-Disposition'] = 'attachment; filename=test.mp4'
                return response

As shown, the video gets saved in the path "C:\Users\win10\Desktop\experiment\django-poc\media\test.mp4". - this I can play.
the server also produces a test.mp4 as a downloaded file. which cannot be played.
Please help in downloading the processed videofile as an attachment. Any help on this is deeply appreciated.
Thanks in advance!


text:
Q: React Native Packager with Resolve Fallback I am trying to include this library in React Native. I get errors because it's building it assuming its for NodeJS where it uses some core modules that are not present in React Native. I know it can be build for web, and I see the webpack file including all the libraries that need to be mocked for this task to succeed. React native however does not use webpack. What is the equivalent configuration in the React Native Packager?
  resolve: {
    fallback: {
      fs: false,
      crypto: require.resolve('crypto-browserify'),
      buffer: require.resolve('buffer/'),
      assert: require.resolve('assert/'),
      url: require.resolve('url/'),
      path: require.resolve('path-browserify'),
      http: require.resolve('stream-http'),
      https: require.resolve('https-browserify'),
      stream: require.resolve('stream-browserify'),
      util: require.resolve('util/'),
      os: require.resolve('os-browserify/browser'),
      zlib: require.resolve('browserify-zlib'),
      events: require.resolve('events/'),
      string_decoder: require.resolve('string_decoder/'),
    },
    extensions: ['.ts', '.js', '.json'],
  },


text:
Q: Converting code from C++ Sockets to WinINet I'm trying to make the equivalent code made using Sockets in a code using WinInet (I'm already in Windows).
This is what I've got:
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main (){
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
        return 1;
    }
    SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    struct hostent *host;
    host = gethostbyname("www.google.com");
    SOCKADDR_IN SockAddr;
    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
    cout << "Connecting...\n";
    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        system("pause");
        return 1;
    }
    cout << "Connected.\n";
    send(Socket,"GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"),0);
    char buffer[10000];
    int nDataLength;
    while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }
    closesocket(Socket);
        WSACleanup();
    system("pause");
    return 0;
}

This is what I did with WinInet:
#include "stdafx.h"
#include <Windows.h>
#include <WinInet.h>
#pragma comment (lib, "Wininet.lib")
#pragma comment (lib, "urlmon.lib")
// Defines
#define POST 1
#define GET 0

void Request(int Method, LPCSTR Host, LPCSTR url, LPCSTR header, LPSTR data)
{
    try {
        //Retrieve default http user agent
        char httpUseragent[512];
        DWORD szhttpUserAgent = sizeof(httpUseragent);
        ObtainUserAgentString(0, httpUseragent, &szhttpUserAgent);

        char m[5];

        if (Method == GET)
            strcpy_s(m, "GET");
        else
            strcpy_s(m, "POST");

        //http://msdn.microsoft.com/en-us/library/windows/desktop/aa385096%28v=vs.85%29.aspx
        HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
        if (internet != NULL)
        {
            //http://msdn.microsoft.com/en-us/library/windows/desktop/aa384363%28v=vs.85%29.aspx
            HINTERNET connect = InternetConnectA(internet, Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
            if (connect != NULL)
            {
                //http://msdn.microsoft.com/en-us/library/windows/desktop/aa384233%28v=vs.85%29.aspx
                HINTERNET request = HttpOpenRequestA(connect, m, url, "HTTP/1.1", NULL, NULL,
                    INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
                    INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
                    INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
                    INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
                    INTERNET_FLAG_NO_AUTH |
                    INTERNET_FLAG_NO_CACHE_WRITE |
                    INTERNET_FLAG_NO_UI |
                    INTERNET_FLAG_PRAGMA_NOCACHE |
                    INTERNET_FLAG_RELOAD, NULL);

                if (request != NULL)
                {
                    int datalen = 0;
                    if (data != NULL) datalen = strlen(data);
                    int headerlen = 0;
                    if (header != NULL) headerlen = strlen(header);

                    //http://msdn.microsoft.com/en-us/library/windows/desktop/aa384247%28v=vs.85%29.aspx
                    HttpSendRequestA(request, header, headerlen, data, datalen);

                    //http://msdn.microsoft.com/en-us/library/windows/desktop/aa384350%28v=vs.85%29.aspx
                    InternetCloseHandle(request);
                }
            }
            InternetCloseHandle(connect);
        }
        InternetCloseHandle(internet);
    }
    catch (...) {}
}

int main()
{
    char URL[1024];
    char* geturi = ""; // string.empty ( I want to make the request to the main page )
    wsprintfA(URL, geturi, NULL, NULL);
    Request(GET, "google.com", URL, NULL, NULL);
    // How can I see if it works? I want to get the webpage html source
    getchar(); // I avoided system("pause") function as it isn't portable.
}

How can I see if it works?
Thanks in advance,
Qasim


text:
Q: WebService com interface de contrato genérica Estou tentando hospedar um Web Service em um serviço do Windows. E ao configurar o serviceModel no App.config estou recebendo o seguinte aviso de erro do editor:

O WebService está um projeto do tipo Biblioteca de Serviço do WCF e o projeto que hospedará o WebService é do tipo Windows Service.
Abaixo segue o código da interface de contrato:
using System.ServiceModel;

namespace FoxMovieStoreWebService
{
    [ServiceContract]
    public interface IDataPersistance<in T> where T : new ( )
    {
        [OperationContract]
        bool Insert ( T value );

        [OperationContract]
        bool Change ( T value );

        [OperationContract]
        bool Delete ( T value );

        // TODO: Adicione suas operações de serviço aqui
    }

    // Use um contrato de dados como ilustrado no exemplo abaixo para adicionar tipos compostos a operações de serviço.
    // Você pode adicionar arquivos XSD ao projeto. Depois de criar o projeto, use os tipos de dados definidos nele diretamente, com o namespace "FoxMovieStoreWebService.ContractType".

}

Aqui o App.config Windows Service onde eu faço a configuração do WebService:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
      <services>

        <service name="FoxMovieStoreWebService.CrudAddress" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudBooking" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudCashDesk" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudClient" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.Dependent" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudDevolution" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudFunctionary" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudGame" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudMovCashDesk" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudMovie" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

        <service name="FoxMovieStoreWebService.CrudRent" behaviorConfiguration="ServiceConfig">
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:9876"/>
              <add baseAddress="http://localhost:8766"/>
            </baseAddresses>
          </host>
          <endpoint address="srv" binding="netTcpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="srv" binding="basicHttpBinding" contract="FoxMovieStoreWebService.IDataPersistance"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceConfig">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    </system.serviceModel>
</configuration>

Tenho quase certeza que esse erro é pelo fato de eu ter criado a interface de contrato como uma Interface Genérica, pois não sei como fica no App.config nesse caso. Caso minha suspeita se confirme mudarei o título da pergunta.


text:
Q: Adding html content dynamically to the page I have the following div. That need to be added whenever i click on the button/link

                    Dependent
                Delete

Relationship to you

                    <input type="radio" value="0" name="relationship" class="dependent-relation" />
                    Partner
                    <input type="radio" value="1" name="relationship" class="dependent-relation"/>
                    Child under21
                    <input type="radio" value="2" name="relationship" class="dependent-relation"/>
                    dependent over21

Date of birth

                    <input type="text" id="dependent-dob" name="dependent-dob" datepicker/>
                    <input type="hidden" id="dependent-id" name="dependent-id" />

Initially this div will be hidden. This div has to be added dynamically every time i click on link (Add dependent), and the div id of parent div should be assigned with dependent+id(1,2,3...).
I have used following script to work this, but the data entered in dependent1 is cloned in subsequent divs.
$("body").delegate("#add", "click", function () {
        var total_length = $(".add_dependent").length
        $(".add_dependent:eq(0)").clone().prependTo("#dependent-details").css("display", "inline");

        $(".add_dependent:last-child .divcount").append(total_length)

        $(".divcount").each(function (index) {
            var increment = index + 1
            $(this).parents(".add_dependent").attr("id", "depend" + increment)
            $(this).text(increment)

        });
    })

How to add the above html elements to existing page whenever i click on the add dependent link?
Could anybody help me on this???

A: You can use the append function and take the html from a template div and inject it to another div for rendering
$("#renderDiv").append($("#templateDiv").html());

Fiddle: http://jsfiddle.net/Zz6wU/2/

A: From the comment "Whenever i click on the add dependent, this div has to be added to the existing div. How i can do this?" :
$("#baseDiv").append($("#newDiv").html());

Not sure that's what you want


text:
Q: Apache NIFI, rename compressed file without changing the name of the content file I have issues trying to rename a compressed file using the processor CompressContent.

*

*I need to rename a flowfile to content.txt, then compress it using a different file name (e.g: compressed.gz)

*To accomplish that, I'm using these processors:
ConvertRecord > UpdateAttribute > CompressContent > UpdateAttribute
Flow_diagram ,
Update_config , Compress_config

*But there is a problem, if I rename the compressed file it also affects the name of the txt file (making it unusable).
Is it possible to rename the compressed file without changing the name of the txt file?
Thanks in advance.


text:
Q: what are ember js static data best practices I have some static data which will never change, like the data behind menu items
{
  "menuItems": [{
    "name": "Shows",
    "route": "shows"
  }, {
    "name": "Podcasts",
    "route": "podcasts"
  }]
}

i created a json file in /dist folder and in the application route i'm creating a model from the file like
export default Route.extend({
  model() {
    return $.getJSON('/static/model.json')
  }
});

is there a better practice to initialize model with static data?

A: As already was said in other answer, you are not supposed to edit files in dist/ folder.
You can do the following:

*

*Create a new folder under app/. Let's say app/constants/

*In that folder create new file menu.js:
export default {
  "menuItems": [{
    "name": "Shows",
    "route": "shows"
  }, {
    "name": "Podcasts",
    "route": "podcasts"
  }]
};

*In any other file import it as import menu from 'project-name/constants/menu';. And I don't think you need a model for this, you can just use what you export.

A: You really shouldn't be editing the dist/ folder - that's where Ember sticks compiled code.
If your static data is only used in a single place, it would be more direct to put it where it's used as a const. In this specific case, that's UI code, and probably belongs in the controller.
The model hook is best for loading data that potentially changes each time you hit that route - probably from a back end.

A: *

*You can install ember-cli-json-module and then, any JSON files in either app or tests will be converted to ES6 modules that you can import like so:
import myFixture from 'my-app/tests/fixtures/my-fixture';


text:
Q: Can't install latest Angular version This is happening since there is some changes in package.json file which is not properly applied. When trying to run npm -install @angular/cli I encounter this problem

Unexpected end of JSON input while parsing near '...ent: https://openpgpj'

A: please make sure that all your changes are checkedin if you are running it in your office machine.
now we would need to clear the cache by running this commmans in admin mode in powershell npm cache clean --force
after running this command try to again run the same command npm install -g @angular/cli


text:
Q: Get key count or occurrences in List : Java I have List<Map<String, String>> that have family member details. Depending on added family member the rest details will be processed.
There can be other family member like uncle, aunt, niece... etc. These records can be single or multiple.
  | Add_Family_Member | Full_Name     | Date_Of_Birth | Gender |
  | Sibling           | Sibling name  | 12-12-1990    | Male   |
  | Sibling           | Sibling name2 | 12-12-1990    | Male   |
  | Sibling           | Sibling name2 | 12-12-1990    | Male   |
  | Child             | Child name    | 12-12-2010    | Male   |
  | Child             | Child name2   | 12-12-2000    | Female |
  | Spouse            | Spouse name   | 12-12-1990    | Male   |

So how can I count Add_Family_Member i.e. Sibling count 3, Child count 2 and spouse count 1.

A: Using Java 8 stream
You can try using stream groupingBy feature to get the count of each member type shown as below:
Logic:
Here, I have created a POJO class FamilyMember with some attributes as given in the problem statement and created a list of FamilyMember and then by using stream operation and using groupingBy, grouped the data by memberType and using Collectors.counting getting the count of each memberType.
Suggestions:
As mentioned in the problem statement, the given input is in the form of List<Map<String, String>> so instead of Map you can use a POJO class to hold the data for each member as shown in my implementation.
And moreover, how you are holding this kind of structure in the form of Map<String,String>
Code:
    public class Test {

       public static void main(String[] args) {

        FamilyMember member1 = new FamilyMember("Sibling","Sibling name",
                LocalDate.of(1990,12,12),"Male");
        FamilyMember member2 = new FamilyMember("Sibling","Sibling name2",
                LocalDate.of(1990,12,12),"Male");
        FamilyMember member3 = new FamilyMember("Sibling","Sibling name3",
                LocalDate.of(1990,12,12),"Male");
        FamilyMember member4 = new FamilyMember("Child","Child name",
                LocalDate.of(2010,12,12),"Male");
        FamilyMember member5 = new FamilyMember("Child","Child name2",
                LocalDate.of(2000,12,12),"Female");
        FamilyMember member6 = new FamilyMember("Spouse","Spouse name",
                LocalDate.of(1990,12,12),"Male");

        List<FamilyMember> listOfFamilyMember = Arrays.asList(member1,member2,
                                              member3,member4,member5,member6);

        Map<String,Long> countMembers = listOfFamilyMember.stream()
                .collect(Collectors.groupingBy(FamilyMember::getMemberType,
               Collectors.counting()));

        System.out.println(countMembers);
    }
}

FamilyMember.java
public class FamilyMember {

    private String memberType;
    private String fullName;
    private LocalDate dateOfBirth;
    private String gender;

    public FamilyMember(String memberType, String fullName,
                        LocalDate dateOfBirth, String gender) {
        this.memberType = memberType;
        this.fullName = fullName;
        this.dateOfBirth = dateOfBirth;
        this.gender = gender;
    }
    //getters and setters
}

Output:
{Spouse=1, Sibling=3, Child=2}


text:
Q: Fixed - Importing module from parent folder in child module - Python 3 I have the following folder structure.
root
   .
   .
   B.py
   test──
        ├
        A.py

I can import A.py in B.py by
from test import A

But, How to import B.py in A.py?
I tried the following code in A.py but it didn't work. I have referred to multiple links but didn't find an appropriate answer.
import os
import sys

scriptpath = "../"

sys.path.append(os.path.abspath(scriptpath))
import B

It wasn't running from VSCode terminal, not sure why. But, It ran from command prompt. Thanks for your help!


text:
Q: how to write a program I'm trying to write a program that would output of an item which is worth 10000 over a period of 15 years using this formula:
I have tried using a method like this:
a = 10000000
y = 120
n = 15
d = (n / y * 10000000)
c = (a - d)
count = 1

if count < 16:
   print(" ")

while count < 16:
    print("End of year", count, "Depression""=", (d), "Current Value""=", (c))
    count +=1

A: def main():
    print("Sum-of-the-Years'-Digits Method")

    years = 15
    sum_of_years = years * (years + 1) // 2    # = sum(1..years)
    initial_value = 10000000

    value = initial_value
    for year in range(years):
        depr = (years - year) / sum_of_years * initial_value
        value -= depr
        print("End of year {}: depreciation = {:0.2f}, new value = {:0.2f}".format(year + 1, depr, value))

if __name__=="__main__":
    main()

which gives
Sum-of-the-Years'-Digits Method
End of year 1: depreciation = 1250000.00, new value = 8750000.00
End of year 2: depreciation = 1166666.67, new value = 7583333.33
End of year 3: depreciation = 1083333.33, new value = 6500000.00
End of year 4: depreciation = 1000000.00, new value = 5500000.00
End of year 5: depreciation = 916666.67, new value = 4583333.33
End of year 6: depreciation = 833333.33, new value = 3750000.00
End of year 7: depreciation = 750000.00, new value = 3000000.00
End of year 8: depreciation = 666666.67, new value = 2333333.33
End of year 9: depreciation = 583333.33, new value = 1750000.00
End of year 10: depreciation = 500000.00, new value = 1250000.00
End of year 11: depreciation = 416666.67, new value = 833333.33
End of year 12: depreciation = 333333.33, new value = 500000.00
End of year 13: depreciation = 250000.00, new value = 250000.00
End of year 14: depreciation = 166666.67, new value = 83333.33
End of year 15: depreciation = 83333.33, new value = 0.00

A: def main():
    print("Sum-of-the-Years'-Digits Method")

    years = 15
    sum_of_years = years * (years + 1) // 2    # = sum(1..years)
    initial_value = 10000000

    value = initial_value
    for year in range(years):
        depr = (years - year) / sum_of_years * initial_value
        value -= depr
        print("End of year {}: depreciation = {:0.2f}, new value = {:0.2f}".format(year + 1, depr, value))

if __name__=="__main__":
    main()

A: print("Sum-of-the-Years'-Digits Method")

a = 10000000

y = 120

n = 16

year = 0

for n in range(15,0,-1):

    ans = ( (float(n)/y) * 10000000 )

    a = a - ans

    year = year + 1

    print "End of year %d , Depression = %f , Current value = %f"%(year,ans,a)

print ("Bye,have a nice day!")


text:
Q: Event/postback cycle in dropdown I know this might be an easy question but still:
I got a dropdown and a button on my website, autopostback is false on the dropdown and I use the "SelectedIndexChanged" event. When I pick an item from the dropdown nothing happens ofcoure, but when I click the button, the system somehow knows that the index has changed in the dropdown and it calls the SelectedIndexChanged event, where does it store this information?
Im guessing the events are being added to a list and then fired upon postback

A: The original state of the DDL is stored in viewstate. Upon postback, the new state and old state are compared and the event fired (or not) accordingly


text:
Q: Can't index parsed JSON string from backend, it returns an undefined value My frontend's supposed to take in a JSON string from the backend and use it, but when I try to index it after using JSON.parse(), it returns undefined. I checked, and it isn't inside an array either; it's just a JSON object literal.
In case any of you aren't familiar with TypeScript, the exclamation points are a TS thing, and removing them doesn't change the results I've been getting.
Here's what the console's been showing me:
console.log(document.getElementById('guestUserCredentials')!.textContent!)

"{\"EMAIL\": \"guest_user@foo.com\", \"PASSWORD\": \"foobar\"}"

console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!))

{"EMAIL": "guest_user@foo.com", "PASSWORD": "foobar"}

console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!)["EMAIL"])

undefined

Maybe it has something to do with the way my Django backend is encoding the JSON string? How do I check for that and fix it, if that's the case? I'm passing it to my React/TS frontend like this:
settings.py
...
GUEST_USER_CREDENTIALS = {
    'EMAIL': os.environ.get('GUEST_EMAIL'),
    'PASSWORD': os.environ.get('GUEST_PASSWORD'),
}
...

views.py
import json

from django.conf import settings
from django.shortcuts import render

def index(request, *args, **kwargs):

  print(settings.GUEST_USER_CREDENTIALS)
  print(json.dumps(settings.GUEST_USER_CREDENTIALS))

  return render(request, 'index.html', context={
    'GUEST_USER_CREDENTIALS': json.dumps(settings.GUEST_USER_CREDENTIALS),
  })

index.html
<!DOCTYPE html>
{% load static %}
<html>
<head>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link rel='icon' href='{% static "frontend/favicon.ico" %}' type='image/x-icon' />
  <title>foo</title>
</head>
<body>
<div id='root'>
  <!-- React goes here. -->
</div>
</body>
{{ GUEST_USER_CREDENTIALS|json_script:"guestUserCredentials" }}
<script src='{% static "frontend/index.bundle.js" %}'></script>
</html>

Maybe it has to do with the way the json_script template tag escapes certain characters in the JSON string? I can't find anything about how that might affect the output in the documentation.
Here's the output of the two print() commands in views.py:
print(settings.GUEST_USER_CREDENTIALS)

{'EMAIL': 'guest_user@foo.com', 'PASSWORD': 'foobar'}

print(json.dumps(settings.GUEST_USER_CREDENTIALS))

{"EMAIL": "guest_user@foo.com", "PASSWORD": "foobar"}

I even tried parsing the JSON string with destr instead of JSON.parse() and the result is still the same. This has been so frustrating.

A: I tried wrapping the output of JSON.parse() in another call to JSON.parse(), and I was able to index the resulting object the way I wanted to.
I'm not sure I fully understand what was going on, but I guess there was no need to run json.dumps() in my views.py file since settings.GUEST_USER_CREDENTIALS was already JSON.
Removing json.dumps() from views.py and adding settings.GUEST_USER_CREDENTIALS to context as-is removes the need for two calls to JSON.parse() in the frontend, and now everything's working as expected.


text:
Q: Bigcommerce API authentication and debugging here is my code:
<html>
    <head>
        <title>Bigcommerce API</title>
    </head>
    <body>
        <?php
        include('bigcommerce.php');

        use Bigcommerce\Api\Client as Bigcommerce;

        Bigcommerce::configure(array(
        'store_url' => 'https://xxx.mybigcommerce.com/api/v2/',
        'username'  => 'admin',
        'api_key'   => 'xxx'
        ));

        $ping = Bigcommerce::getTime();
        if ($ping) echo $ping->format('H:i:s');
        echo('hello');
        ?>
    </body>
</html>

I run this and nothing happens. I look in the browser and it shows no errors. How do I even begin to debug?
EDIT
I took out /api/v2 and now I am seeing this error:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in /Library/WebServer/Documents/bigcommerce.php:404 Stack trace: #0 /Library/WebServer/Documents/bigcommerce.php(404): DateTime->__construct('@1418752201') #1 /Library/WebServer/Documents/index.php(19): Bigcommerce\Api\Client::getTime() #2 {main} thrown in /Library/WebServer/Documents/bigcommerce.php on line 404
Thanks.
EDIT
I added the following to index.php and it works!
if( ! ini_get('date.timezone') )
{
    date_default_timezone_set('GMT');
}

A: I added the following to index.php and it works!
if( ! ini_get('date.timezone') )
{
    date_default_timezone_set('GMT');
}

– LanterneRouge


text:
Q: As of 2017, how exactly does per-site meta work? I searched on this site MSE before asking this question. All search results are more than 6 years old (and I found most of them talking about things that's already changed).
In those posts I searched, people said MSO worked as a "service center" but it's clear the present center is MSE. Also I checked my MSO profile and found my rep was derived from Main SO. This blog says MSO works as a separate site but obviously it's no longer true.
So how does the way in which per-site metas work different from what it used to be in 2010? What about MSO and MSE?
Please don't mark this question as a duplicate of something too old. I'm wondering about what things are now, not before.

A: There is no difference in the way per-site metas work between 2010 and now.
What has changed is that this site used to be called Meta Stack Overflow and Stack Overflow didn't have its own child meta, but now this site is now called Meta Stack Exchange and Stack Overflow does have its own child meta.
The change was made for various reasons, not least of which was that Stack Overflow–specific questions were becoming increasingly out of place on a site that was dealing with the entire network.
So, Stack Overflow–specific questions go to Meta Stack Overflow while questions about the wider network come here. This isn't to say that network questions are off topic on child metas. They can be asked there, but they may get better answers here.


text:
Q: wrapper in Vue3 test utils fails when looking for a dedicated tag So I have this test:
  test("should emit archiveOrder event", () => {
    let wrapper = mount(OrderDetailMenu)
    const button = wrapper.get('[data-test="archive"]').trigger('archiveOrder')

    expect(button.emitted()).toHaveProperty('increment')
  });

The corresponding component looks like this:
<template>

    <MenuItem v-slot="{ active }">
      <Link data-test="details" :href="`/administration/orders/${order.id}`"
        class="text-slate-900 px-1 hover:text-fotoprosser-900 focus:outline-none group flex w-full items-center rounded px-2 py-2 text-sm" >
        <ViewListIcon
          :active="active"
          class="w-5 h-5 mr-2"
          aria-hidden="true" />
        Details
      </Link>
    </MenuItem>

    <MenuItem v-slot="{ active }">
      <button data-test="archive"
              class="text-slate-900 px-1 hover:text-fotoprosser-900 focus:outline-none group flex w-full items-center rounded px-2 py-2 text-sm"
        @click="emits('archiveOrder', order)">
        <ArchiveIcon
          :active="active"
          class="w-5 h-5 mr-2"
          aria-hidden="true"
        />
        Archivieren
      </button>
    </MenuItem>

    <MenuItem v-slot="{ active }">
      <button data-test="delete"
              class="text-slate-900 px-1 hover:text-fotoprosser-900 focus:outline-none group flex w-full items-center rounded px-2 py-2 text-sm"
        @click="emits('destroyOrder', order)">
        <MinusIcon
          :active="active"
          class="w-5 h-5 mr-2"
          aria-hidden="true"
        />
        Löschen
      </button>
    </MenuItem>

</template>

Running the test results in:
Error: Unable to get [data-test="archive"] within:

Can't see the problem really, as this is what the docs say about vue-jest.


text:
Q: bluetooth file send i'm new to bluetooth development and i found the 32netfeet . Right now i'm able to search for bluetooth devices nearby and connect to them but how do i send a file e.g SendTest.txt? I tried buttonclick event using the OBEX but i don't understand this is my example code:
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

namespace BluetoothIntheHand
{
    public partial class Form2 : Form
    {
        private Guid service = BluetoothService.DialupNetworking;
        private BluetoothClient bluetoothClient;

        public Form2()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
                BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
                lblSearch.Text = "" + myRadio.LocalAddress.ToString();

                bluetoothClient = new BluetoothClient();
                Cursor.Current = Cursors.WaitCursor;
                BluetoothDeviceInfo[] bluetoothDeviceInfo = { };
                bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
                comboBox1.DataSource = bluetoothDeviceInfo;
                comboBox1.DisplayMember = "DeviceName";
                comboBox1.ValueMember = "DeviceAddress";
                comboBox1.Focus();
                Cursor.Current = Cursors.Default;

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedValue != null)
            {
                try
                {
                    bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
                    MessageBox.Show("Connected");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

   private void btnSend_Click(object sender, EventArgs e)
        {

                    bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
                    String addr  = "112233445566";
                    Uri uri = new Uri("obex://"+@"SendTest.txt");
                    ObexWebRequest req= new ObexWebRequest(uri);

                    ObexWebResponse rsp;

        }

I found the guide but don't really know how to convert to C#
' The host part of the URI is the device address, e.g. IrDAAddress.ToString(),
' and the file part is the OBEX object name.
Dim addr As String = "112233445566"
Dim uri As New Uri("obex://" & addr & "/HelloWorld2.txt")
Dim req As New ObexWebRequest(uri)
Using content As Stream = req.GetRequestStream()
   ' Using a StreamWriter to write text to the stream...
   Using wtr As New StreamWriter(content)
      wtr.WriteLine("Hello World GetRequestStream")
      wtr.WriteLine("Hello World GetRequestStream 2")
      wtr.Flush()
      ' Set the Length header value
      req.ContentLength = content.Length
   End Using
   ' In this case closing the StreamWriter also closed the Stream, but ...
End Using
Dim rsp As ObexWebResponse = CType(req.GetResponse(),ObexWebResponse)
Console.WriteLine("Response Code: {0} (0x{0:X})", rsp.StatusCode)

A: // The host part of the URI is the device address, e.g. IrDAAddress.ToString(),
// and the file part is the OBEX object name.

{
    string addr = "112233445566";
    Uri uri = new Uri("obex://" + addr + "/HelloWorld2.txt");
    ObexWebRequest req = new ObexWebRequest(uri);
    using (Stream content = req.GetRequestStream()) {
        // Using a StreamWriter to write text to the stream...
        using (StreamWriter wtr = new StreamWriter(content)) {
            wtr.WriteLine("Hello World GetRequestStream");
            wtr.WriteLine("Hello World GetRequestStream 2");
            wtr.Flush();
            // Set the Length header value
            req.ContentLength = content.Length;
        }
    }
    // In this case closing the StreamWriter also closed the Stream, but ...
    ObexWebResponse rsp = (ObexWebResponse)req.GetResponse();
    Console.WriteLine("Response Code: {0} (0x{0:X})", rsp.StatusCode);
}

A: ans:
string fileName = @"SendTest.txt";

String adr = "0025677FB346";
Uri uri = new Uri("obex://" + adr + "/" + System.IO.Path.GetFileName(fileName));
ObexWebRequest request = new ObexWebRequest(uri);
request.ReadFile(fileName);

ObexWebResponse response = (ObexWebResponse)request.GetResponse();
MessageBox.Show(response.StatusCode.ToString());
response.Close();

A: The C4F (Coding 4 Fun Kit) has an implementation of obex - http://blogs.msdn.com/b/coding4fun/archive/2007/08/02/4192571.aspx
I've used it and found it to be quite reliable.


text:
Q: Optimize for expensive fragment shader I'm rendering multiple layers of flat triangles with a raytracer in the fragment shader. The upper layers have holes, and I'm looking for a way how I can avoid running the shader for pixels that are filled already by one of the upper layers, i.e. I want only the parts of the lower layers rendered that lie in the holes in the upper layers. Of course, if there's a hole or not is not known unless the fragment shader did his thing for a layer.
As far as I understand, I cannot use early depth testing because there, the depth values are interpolated between the vertices and do not come from the fragment shader. Is there a way to "emulate" that behavior?

A: The best way to solve this issue is to not use layers. You are only using layers because of the limitations of using a 3D texture to store your scene data. So... don't do that.
SSBOs and buffer textures (if your hardware is too old for SSBOs) can access more memory than a 3D texture. And you could even employ manual swizzling of the data to improve cache locality if that is viable.

As far as I understand, I cannot use early depth testing because there, the depth values are interpolated between the vertices and do not come from the fragment shader.

This is correct insofar as you cannot use early depth tests, but it is incorrect as to why.
The "depth" provided by the VS doesn't need to be the depth of the actual fragment. You are rendering your scene in layers, presumably with each layer being a full-screen quad. By definition, everything in one layer of rendering is beneath everything in a lower layer. So the absolute depth value doesn't matter; what matters is whether there is something from a higher layer over this fragment.
So each layer could get its own depth value, with lower layers getting a lower depth value. The exact value is arbitrary and irrelevant; what matters is that higher layers have higher values.
The reason this doesn't work is this: if your raytracing algorithm detects a miss within a layer (a "hole"), you must discard that fragment. And the use of discard at all turns off early depth testing in most hardware, since the depth testing logic is usually tied to the depth writing logic (it is an atomic read/conditional-modify/conditional-write).


text:
Q: How to build dynamic query with Where and OR using Expression I hope somebody can guide and help me with this. We have an inherited project that uses ExpressionHelper class. Basically, this Expression Helper will return an IQueryable that build a dynamic query base on the search term that the user provided.
For example, I have the below code where I pass 2 search terms.
    IQueryable<UserEntity> modifiedQuery = _uow.UserRepository.GetAll();;

    var searchTerms = new List<SearchTerm>
    {
        new SearchTerm { Name = "FirstName", Operator = "eq", Value = "Bob" },
        new SearchTerm { Name = "FirstName", Operator = "eq", Value = "John" }
    };

    foreach (var searchTerm in searchTerms)
    {
        var propertyInfo = ExpressionHelper
            .GetPropertyInfo<TEntity>(searchTerm.EntityName ?? searchTerm.Name);

        var obj = ExpressionHelper.Parameter<TEntity>();

        var left = ExpressionHelper.GetPropertyExpression(obj, propertyInfo);
        var right = searchTerm.ExpressionProvider.GetValue(searchTerm.Value);
        var comparisonExpression = searchTerm.ExpressionProvider
            .GetComparison(left, searchTerm.Operator, right);

        // x => x.Property == "Value"
        var lambdaExpression = ExpressionHelper
            .GetLambda<TEntity, bool>(obj, comparisonExpression);

        // query = query.Where...
        modifiedQuery = ExpressionHelper.CallWhere(modifiedQuery, lambdaExpression);
    }

With the code above and using the below ExpressionHelper class, this generate the below SQL query when I check using SQLProfiler. Please notice the AND in the query. What I actually what is OR.
Constructed QUERY in SQL Profiler
SELECT
    [Extent1].[FirstName] AS [FirstName],
    FROM [dbo].[tblUser] AS [Extent1]
WHERE ([Extent1].[Conatact1] = N'Bob') AND ([Extent1].[Contact2] = N'John')

ExpressionHelper.cs
public static class ExpressionHelper
{
    private static readonly MethodInfo LambdaMethod = typeof(Expression)
        .GetMethods()
        .First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2);

    private static MethodInfo[] QueryableMethods = typeof(Queryable)
        .GetMethods()
        .ToArray();

    private static MethodInfo GetLambdaFuncBuilder(Type source, Type dest)
    {
        var predicateType = typeof(Func<,>).MakeGenericType(source, dest);
        return LambdaMethod.MakeGenericMethod(predicateType);
    }

    public static PropertyInfo GetPropertyInfo<T>(string name)
        => typeof(T).GetProperties()
        .Single(p => p.Name == name);

    public static ParameterExpression Parameter<T>()
        => Expression.Parameter(typeof(T));

    public static MemberExpression GetPropertyExpression(ParameterExpression obj, PropertyInfo property)
        => Expression.Property(obj, property);

    public static LambdaExpression GetLambda<TSource, TDest>(ParameterExpression obj, Expression arg)
        => GetLambda(typeof(TSource), typeof(TDest), obj, arg);

    public static LambdaExpression GetLambda(Type source, Type dest, ParameterExpression obj, Expression arg)
    {
        var lambdaBuilder = GetLambdaFuncBuilder(source, dest);
        return (LambdaExpression)lambdaBuilder.Invoke(null, new object[] { arg, new[] { obj } });
    }

    public static IQueryable<T> CallWhere<T>(IQueryable<T> query, LambdaExpression predicate)
    {
        var whereMethodBuilder = QueryableMethods
            .First(x => x.Name == "Where" && x.GetParameters().Length == 2)
            .MakeGenericMethod(new[] { typeof(T) });

        return (IQueryable<T>)whereMethodBuilder
            .Invoke(null, new object[] { query, predicate });
    }

    public static IQueryable<TEntity> CallOrderByOrThenBy<TEntity>(
        IQueryable<TEntity> modifiedQuery,
        bool useThenBy,
        bool descending,
        Type propertyType,
        LambdaExpression keySelector)
    {
        var methodName = "OrderBy";
        if (useThenBy) methodName = "ThenBy";
        if (descending) methodName += "Descending";

        var method = QueryableMethods
            .First(x => x.Name == methodName && x.GetParameters().Length == 2)
            .MakeGenericMethod(new[] { typeof(TEntity), propertyType });

        return (IQueryable<TEntity>)method.Invoke(null, new object[] { modifiedQuery, keySelector });
    }
}

I have hard time understanding on how the query was created and how do I change it to become OR in the created query.
Hope someone can guide me and point to the right direction. Thank you!

A: Add to SearchTerm a new property (C# 6.0 syntax here):
    // This is quite wrong. We should have an enum here, but Operator is
    // done as a string, so I'm maintaining the "style"
    // Supported LogicalConnector: and, or
    public string LogicalConnector { get; set; } = "and";
}

Then:
private static IQueryable<TEntity> BuildQuery<TEntity>(IQueryable<TEntity> modifiedQuery, List<SearchTerm> searchTerms)
{
    Expression comparisonExpressions = null;

    var obj = ExpressionHelper.Parameter<TEntity>();

    foreach (var searchTerm in searchTerms)
    {
        var propertyInfo = ExpressionHelper
            .GetPropertyInfo<TEntity>(searchTerm.EntityName ?? searchTerm.Name);

        var left = ExpressionHelper.GetPropertyExpression(obj, propertyInfo);
        var right = searchTerm.ExpressionProvider.GetValue(searchTerm.Value);
        var comparisonExpression = searchTerm.ExpressionProvider.GetComparison(left, searchTerm.Operator, right);

        if (comparisonExpressions == null)
        {
            comparisonExpressions = comparisonExpression;
        }
        else if (searchTerm.LogicalConnector == "and")
        {
            comparisonExpressions = Expression.AndAlso(comparisonExpressions, comparisonExpression);
        }
        else if (searchTerm.LogicalConnector == "or")
        {
            comparisonExpressions = Expression.OrElse(comparisonExpressions, comparisonExpression);
        }
        else
        {
            throw new NotSupportedException(searchTerm.LogicalConnector);
        }
    }

    if (comparisonExpressions != null)
    {
        // x => x.Property == "Value"
        var lambdaExpression = ExpressionHelper.GetLambda<TEntity, bool>(obj, comparisonExpressions);
        // query = query.Where...
        modifiedQuery = ExpressionHelper.CallWhere(modifiedQuery, lambdaExpression);
    }

    return modifiedQuery;
}

Use it like:
var searchTerms = new List<SearchTerm>
{
    new SearchTerm { Name = "PrimaryContact", Operator = "eq", Value = "Bob" },
    new SearchTerm { Name = "SecondaryContact", Operator = "eq", Value = "Bob" },
    new SearchTerm { Name = "PrimaryContact", Operator = "eq", Value = "John", LogicalConnector = "or", }
};

IQueryable<UserEntity> query = BuildQuery<UserEntity>(modifiedQuery, searchTerms);

Note that there is no way in this code to explicitly set brackets, that will be implicitly set as:
(((A opB b) opC C) opD D)

Where A, B, C, D are the SearchTerm[0], SearchTerm[1], SearchTerm[2], SearchTerm[3] and opB, opC, opD are the operators defined in SearchTerm[1].LogicalConnector, SearchTerm[2].LogicalConnector, SearchTerm[3].LogicalConnector.
While putting brackets is easy, choosing how to "describe" them is complex, unless you change significantly your SearchTerm collection (it couldn't be a "linear" array but it would need to be a tree).
P.S. I was wrong, you don't need an ExpressionVisitor. You need an ExpressionVisitor when you are trying to "merge" multiple LambdaExpressions that have distinct ParameterExpression. In this code we are able to have a single var obj = ExpressionHelper.Parameter<TEntity>() for all the query, so no problems merging the conditions. To make it clear: if you want to "merge" x1 => x1.Foo == "Foo1" with x2 => x2.Foo == "Foo2" then you need an ExpressionVisitor that replaces x2 with x1, otherwise you would get a wrong query like x1 => x1.Foo == "Foo1" || x2.Foo == "Foo2". In the code given we have only x1 (that is var obj = ExpressionHelper.Parameter<TEntity>()), so no problem.


text:
Q: How can I make a map function inside lodash .times I'm trying to make a map function for items I get from an API response inside of _.times but it doesn't work, is that even possible, I just want to make a unique id  number for every item and compare every id with the this.state.selected in the className of every item

  {_.times(this.state.items.length, j => ({this.state.items.map(i =>{i.name})}))}

A: Works OK -
    render() {
       return (_.times(this.state.items.length, j => this.state.items.map(i =>

          {i} .

)))
    }

https://jsfiddle.net/kpcqn7wb/
Note your variable "j" isn't unique - it is the count index of the function call to the function called to _.times, so the id attr will not be unique.

A: As Win mentioned in the comment, the easiest thing would probably just be to use a normal _.map() call over this.state.items, and utilize the index of each array item to set the id. Keep in mind that lodash nearly always provides two arguments when iterating: in arrays it's (value, index) and in objects it's (value, key).
In this case, you could do something like:

  {_.map(this.state.items, (item, index) =>{
    return(
    {item.name}
    );
  });
  }

Does that help?


text:
Q: Как запустить exe и получить с него данные c# Собственно у меня уже есть код и он работает. Но на ASP.NET постоянно пустую строку выдает. Вот код:
public static async Task<string> RecognizeAudio(string path)
    {
        Process _process = new Process();

        ProcessStartInfo startInfo = new ProcessStartInfo();

        startInfo.FileName = @"C:\Users\Макс\Downloads\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp3.1\Recognizer\dist\recognizer.exe";
        startInfo.Arguments = @"C:\Users\Макс\source\repos\ITG-Server\ITG-Server\Temp\382938128.wav";
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;

        _process.StartInfo = startInfo;
        _process.EnableRaisingEvents = true;

        _process.Start();

        return await _process.StandardOutput.ReadToEndAsync(); ;
    }

И в консольном приложении все окей работает, но в ASP.NET я получаю пустую строку. Файл к которому я обращаюсь это питон код скомпилированный в exe. Как мне запустить этот код и получить инфу которую он возвращает.
public static async Task<string> Recognize(byte[] bytes)
        {
        //тут все работает
            string path = Audio.CreateFile(bytes, ".3gp");
            Audio.ToWav(path, ".3gp");
        //тут все работает

            return await Audio.RecognizeAudio(path);
        }

Contoller:
 [HttpPost]
 [Route("Verify")]
 public async Task<IActionResult> Verify([FromBody] Json json)
 {
     return Ok(await SoundModel.Recognize(json.content));
 }

Немного протестировать с другим ексе, все выводит. Видимо и правда что-то с прогой, хотя вроде все должно быть нормально. Буду пробовать дальше.


text:
Q: Spring JavaConfig equivalent of referring to beans by name In Spring XML config, I can use the ref="bean_name" syntax to refer to a bean by ID or name.
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
    <property name="accountDao" ref="accountDao"/>
</bean>

Is there an equivalent way of achieving this in Java config, using the name attribute on the @Bean annotation? I've used the @Named annotation (javax.inject.Named) and have seen @Qualifier suggested elsewhere, but is a separate annotation really necessary if we already have a name attribute on the @Bean annotation?

A: @Qualifier is the correct thing to use here.
@Autowired
@Qualifier("bean_name")
private Beantype var;

And declaring your component
@Component(value = "bean_name")
public class Beantype {...}

At least that works for me.


text:
Q: Eclipse Debugging Filter Unwanted Packages I have been using Eclipse for 2 years for development, but this filter concept I am still struggling to understand during debugging.
I usually debug in remote port mode.
Most of the times, My Eclipse catches the break point/exception in Unwanted Packages [Packages usually from other Sources like Spring, Java ThreadPool etc..] and annoys me by bringing up the debug window.
I would like to configure Eclipse to catch breakpoints in my package only. Just ignore any where else, don't halt them or notify me.

A: As far as I know we can add package filters for exception breakpoints but for the normal line breakpoints, I think a long way to manually disable one by one will work,
You can look at Eclipse Creating Expression Filter for more information.
This figure provide info ho we can open Java Exception Breakpoint,

A: I think this should help you:
Window --> Preferences --> Java --> Debug

Uncheck the following:

*

*Suspend exceution on uncaught exceptions

*Suspend exceution on compilation errors

*Open popup when suspended on exception
Click on Apply & then OK.


text:
Q: ajax- pass dropdown option values as a list i have a drop down list which allows multiple select like this:
<select id="myId" >
   <option value="1">Value 1</option>
   <option value="2">Value 2</option>
   <option value="3">Value 3</option>
   <option value="4">Value 4</option>
 </select>

now on change the option i need to make an ajax call (to my controller) which sends the value of selected options
  $("#myId").change(function(){
   var myId= $("#myId").val();
       $.ajax({
    url:"${createLink(controller:'clientTrip',action:'fillData')}",
    data: ({myId:myId}),  // i want myid to be sent as list
    dataType: "html",

    success: function(data) {

    }
});
  });

i want to get value of myId as a list (list of selected option values) in my controller..
how can i do it? what changes i should make ?

A: You should most likely use the selected selector. Something like the following should work
$("#myId").change(function(){
   var myIds = new Array();
   $("#myId option:selected").each(function(){
       myIDS.push($(this).val());
   })
       $.ajax({
            url:"${createLink(controller:'clientTrip',action:'fillData')}",
            data: ({myId:myIds}),  // i want myid to be sent as list
            dataType: "html",

            success: function(data) {

            }
        });
  });


text:
Q: Apache Reverse Proxy Issue I am trying to user mod_proxy to set up the reverse proxy for multiple web application using a single Apache web server (version 2.4).
I have two applications running on two different tomcat servers:
1. http://app.test.com:8080/app
2. http://app.test.com:8090/app

I have enabled the required modules in the httpd.conf file and added the below lines to the same:
> ProxyPass /App1/ http://app.test.com:8080/app
> ProxyPassReverse /App2/ http://app.test.com:8090/app

The issue is when I test this using below URL

http://rp.test.com:80/App1/ and http://rp.test.com:80/App2/,the apache webserver does send me to the apps hosted on tomcats but gives a 404 error on clicking any internal link of the application.

Think I am missing some configuration part here. Any suggestions?

A: You also need to configure Tomcat connectors behind the proxy. Somethink like this, containing your external server name and port.
<Connector port="8081" ...
          proxyName="www.mycompany.com"
          proxyPort="80"/>

To adjust the path in the URL, you may use the proxypassreversepath directive, see:
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassreversecookiepath
ProxyPassReverseCookiePath /App1/ /app/


text:
Q: jQuery form processing, how can I reassign a function on callback?  $(function(){

$(".mailbutton").click(function() {
  var email = $(".mailingfield").val();
  $.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
        var content = $(data).find("#mailinglistform");
        $("#box").empty().append(content);
  });
 });
});

I'm using this to process an email address. If it fails in the PHP script the form is sent back in the '.mailinglistform' with a fresh form and some text explaining the error. The problem I have is that even though the button has the '.mailbutton' class in the callback form, the button doesn't do anything on click.
Is this because the jQuery only recognises it first time round? If so, is there a way to "reload" the 'mailbutton' .click function on callback?
Thanks!

A: You're right that because you're only re-rendering a portion of the page, the previous jQuery you wrote does not register with the "new" mailbutton class that you've re-rendered.  To get around this, you should use .on(), e.g.:
$(".wrapper").on('click', '.mailbutton', function() {
  var email = $(".mailingfield").val();
  $.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
        var content = $(data).find("#mailinglistform");
        $("#box").empty().append(content);
  });
 });

In this case, wrapper needs to be a class element that's outside of the re-rendered section (e.g. the 'content' class, maybe a class around your form, etc) of the page, and one that is constantly present (i.e. not re-rendered in the ajax call).  This will attach an onclick handler to any .mailbutton classes that are children of the wrapper class, whether they are present when the page is rendered, or if they are added to the DOM later.

A: Use on to bind click event. When control is render again in the callback function its events are removed. Using on instead of click could rebind the events automatically.
 $(function(){

    $(".mailbutton").on("click", function() {
    var email = $(".mailingfield").val();
    $.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
        var content = $(data).find("#mailinglistform");
        $("#box").empty().append(content);
    });
    });
});

A: For this you can use AJAX with JQuery. OR you can alos user load().
$(".mailbutton").click(function() {
        $.ajax({
              url: 'api.php', // Put your calling page path here
              data: "",
              dataType: 'json',
              success: function(data)
              {
                //do whatever you want to do on success
              }
        });
    });


text:
Q: How do I translate HandbrakeCLI options to FFmpeg options? I have a bunch of commandline settings that work for handbrake, but sometimes on some videos (I have no idea why) handbrake throws "Out of memory exception". I was wondering if I can find the same option keys and do it with FFmpeg, but it seems not so easy thing to do.
FFmpeg sometimes either doesn't have those options or does stuff by default. For example I don't know how to do custom anamorphic with FFmpeg. For me very is important that resulting videos will be as good as if they're done with handbrake. Here's the line for Handbrake:
HandBrakeCLI.exe --input "d:\input.mpg" --output "d:\output.mp4" --rate 29.97 --cfr --arate 44.1 --format mp4 --width 1920 --height 1080 --custom-anamorphic --display-width 1920 --keep-display-aspect --modulus 8 --crop 0:0:0:0 --encoder x264 --vb 5200 --aencoder faac --ab 128 --mixdown stereo -x bitrate=5200:vbv-bufsize=5200:vbv-maxrate=5200:level=42:bframes=2:min-keyint=60:keyint=60:ref=4:me=umh:merange=64:subme=7:8x8dct:cabac=1  -v3 -2 -a none

How do I turn this to an FFmpeg command?

A: Handbrake uses the x264 encoder for video conversion. There's a site with an overview of all the x264 options and their FFmpeg counterparts. However, these are a little deprecated and some of these options don't work anymore or might have been renamed. You should use the x264 profiles for most of the detail options—but we'll get there.
Many of the basic Handbrake options (e.g. frame rate) aren't specific to x264, and they are scattered across the FFmpeg online documentation.
Before we start, please check that you use a recent FFmpeg version. Their download site has static builds for all major operating systems.
Let's go:

*

*--input "d:\input.mpg" --output "d:\output.mp4"
The FFmpeg syntax is ffmpeg -i input.mpg … d:\output.mp4.

*--rate 29.97
Specify the video frame rate with -r 29.97. (Handbrake's --cfr just sets a constant frame rate. Not needed here).

*--arate 44.1
Set the audio sample rate with -ar 44100 (in Hz).

*--format mp4
Not needed because FFmpeg knows you want MP4.

*--width 1920 --height 1080 --custom-anamorphic --display-width 1920 --keep-display-aspect --modulus 8 --crop 0:0:0:0
This doesn't do anything apart from setting the size to 1920×1080. In FFmpeg, do it with -s:v 1920x1080, or if you want to use the filters, -filter:v "scale=1920:1080".

*--encoder x264 --vb 5200
Set the encoder with -c:v libx264 and the bit rate to constant with -b:v 5200K. Note that we're not there yet when it comes to quality settings.

*--aencoder faac --ab 128 --mixdown stereo
Similar to above, with -c:a libfaac -b:a 128K -ac 2. Note that FAAC is not supported in FFmpeg anymore; instead, use the built-in FFmpeg encoder with -c:a aac -b:a 128K instead.

*-x bitrate=5200:vbv-bufsize=5200:vbv-maxrate=5200
This sets the encoding mode to VBV which targets a streaming scenario instead of just a constant bitrate or constant quality. Constant quality is also called CRF, the default for x264 – it's called "Rate Factor" in Handbrake. While CRF usually gives you the best quality encodes, the VBV mode gives you a file that is better suited for streaming online or for certain devices with limited capabilities.
To set VBV, use the -maxrate 5200K and -bufsize 5200K options in ffmpeg.
To set CRF, use -crf 23 in ffmpeg.

*level=42
Use -level 42. This is the H.264 Level.

*bframes=2:min-keyint=60:keyint=60:ref=4
Set the number of B-Frames with -bf 2. The minimum keyframe interval is set with -keyint_min 60, and the maximum interval with -g 60. The number of reference pictures is set with -refs 4.

*me=umh:merange=64:subme=7:8x8dct:cabac=1
These are options that you can set in ffmpeg additionally with -x264-params me=umh:merange=64:subme=7:8x8dct:cabac=1 – like any other x264 encoder setting that is not directly mapped to ffmpeg options.
Here's the "TL;DR" version if you're lazy, don't care about the details, or if things don't work: Use -preset:v medium (or leave it out, as the medium preset is default). The x264 presets choose a set of options that trade encoding speed for compression efficiency. They're conveniently named from ultrafast, superfast, veryfast, faster, fast, medium to slow, slower and veryslow. Choose whatever you feel comfortable with.
So, to summarize, the long version:
ffmpeg -i input.mpg -c:v libx264 -r 29.97 -s:v 1920x1080 -b:v 5200K -maxrate 5200K -bufsize 5200K -level 42 -bf 2 -keyint_min 60 -g 60 -refs 4 -x264-params me=umh:merange=64:subme=7:8x8dct:cabac=1 -c:a aac -b:a 128K -ar 44100 d:\output.mp4

Or the short one I'd use (with VBV encoding and a few detail options removed):
ffmpeg -i input.mpg -c:v libx264 -r 29.97 -s:v 1920x1080 -b:v 5200K -maxrate 5200K -bufsize 5200K -c:a aac -b:a 128K -ar 44100 d:\output.mp4

Changing to constant quality encoding for an all-purpose conversion, use this and change the -crf parameter from 18 to 28, where lower means better quality and 23 is default:
ffmpeg -i input.mpg -c:v libx264 -r 29.97 -s:v 1920x1080 -crf 23 -c:a aac -b:a 128K -ar 44100 d:\output.mp4


text:
Q: Enumerating 2 combinations of dictionary keys in python I wish to enumerate over all 2 combinations of dictionary keys in python. For example if I have some dictionary like:
di = {'a': [1, 2 ,5], 'b': "haha", 'c': 34, 'd': 24}

Now, suppose each key were indexed by its order. For example a would be 1 b would be 2 and so forth.
Then we could do the familiar iteration to get all 2-combinations:
for i in range(len(di)):
    for j in range(i+1, len(di)):

However, the dictionary keys are not indexed as above. So how do I perform this iteration?

A: itertools.combinations could be of help.

A: As long as you don't want special handling to split up that list keyed to 'a':
list(itertools.combinations(di.values(),2))
Out[6]:
[([1, 2, 5], 34),
 ([1, 2, 5], 'haha'),
 ([1, 2, 5], 24),
 (34, 'haha'),
 (34, 24),
 ('haha', 24)]

(python 3 syntax)


text:
Q: PHP: cutting a string in a number of characters blocks I have a variable called $data which contains a giant string (27338 characters).
This string will be the content of a pdf file.
I need to add a footnote at the end of each page of the pdf file.
I've calculated 2642 characters per page.
How can I cut $data in chunks of 2642 characters so I can add the footnotes?
I'm trying:
$split = preg_split('/(.{0,2642})\s/',
                    $data,
                    0,
                    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

$count = count($split);
foreach ($split as $key => $page) {

    echo $page; echo "

";
}

But each $page shows much less than 2642 characters.
Thanks a lot

A: I never used it with very large amount of data but a way to split strings in elements of equal length is to use the str_split function (see http://php.net/str_split)
usage:
$array = str_split('some text', 2);

and you will get an array with elements of length 2 (except for the last one)

A: You can use the substring-function, which will create a specific substring (of a defined length) from a different string.
substr($STRING, A, B); //where $string is the original string,
                       //A is the position where to start cutting
                       //B is how long the newly created string should be (it's optional!)
$text = "ABCDEF";
echo substr($text, 2, 2); //will give you "CD"

A: this?
define("CHUNK_SIZE",2642);
$string = "big..";
$chunks = array();
for($x=0,$sz=strlen($string);$x<$sz;$x+=CHUNK_SIZE) {
   $chunks[] = substr($string,$x,$x+CHUNK_SIZE);
}
$chunks[0..n] += FOOTNOTE

then:
implode("",$chunks);


text:
Q: Clone GCP project with Terraformer\Terraform I just started playing with Inferstracture as a code in Google cloud.

*

*Installed Terraform

*Installed Terraformer

*Created a new GCP project with a virtual machine in it.

My goal is to duplicate the project, with all it's component, into a new project.
In order to do so, I using Terraformer to reverse terraform my existing project. Command:
$ terraformer import google --connect --projects=[project_id] --resources=autoscalers,backendBuckets,backendServices,bigQuery,cloudFunctions,cloudsql,dataProc,disks,dns,firewalls,forwardingRules,gcs,gke,globalAddresses,globalForwardingRules,healthChecks,httpHealthChecks,httpsHealthChecks,iam,images,instanceGroupManagers,instanceGroups,instanceTemplates,instances,interconnectAttachments,kms,memoryStore,monitoring,networkEndpointGroups,networks,nodeGroups,nodeTemplates,project,pubsub,regionAutoscalers,regionBackendServices,regionDisks,regionInstanceGroupManagers,routers,routes,schedulerJobs,securityPolicies,sslPolicies,subnetworks,targetHttpProxies,targetHttpsProxies,targetInstances,targetPools,targetSslProxies,targetTcpProxies,targetVpnGateways,urlMaps,vpnTunnels
2019/06/20 08:00:08 google importing project [project_id]
2019/06/20 08:00:08 google importing... autoscalers
2019/06/20 08:00:19 googleapi: got HTTP response code 404 with body: Not Found

Seems like I have kind of permission problem since google-api reply with Not-Found error code.
I guess Terraformer is accessing is using gcloud permissions to access my gcp environment, is this true?
If it's true, my logged in credientails are owner on this project.
What should I check? How to fix this issue?

A: You can use service account with read access to project. And set GOOGLE_CLOUD_KEYFILE_JSON to point to credentials.json of that service account.


text:
Q: Transform a colored image to a grayscale image using XAML? Using XAML preferably,
I need to dynamically apply a gray-scale filter on a colored image from bottom to top. That's to say, i would like to be able to change the offset value of the gray-scale filter applied to my image pro grammatically.
For example, I would like to programmatically set 50% of the image in color (from the bottom of the image to its middle), and the other 50% of the image in gray-scale (e.g. from the middle of the image to its top).
I have read a lot of different answers, tried a lot of different things, and thought about a lot of different ways to do this.

*

*I could have two images, one on top of the other. One would be in gray-scale and the other would be in color. I would then programmatically change the size of the gray-scale image so that the image in color below it would partially show and create a sort of half-half view to the user.

However, this solution poses an issue that I do not seem to be able to resolve. When changing the height value of the gray-scale image, the image automatically rescale itself due to the 'Stretch' property which is set to Uniform (and that I do not wish to change to None).

*

*Another way to do this would be to programmatically change the color pixels of the image. I have had some success with this in the past, however, this is too slow for what I am trying to do here (ideally, I would be changing the colors of the image from gray-scale to the original color of the image selected by the user every 50 milliseconds until a certain height is reached).

*A third method could be to apply an Opacity Mask on the image and use LinearGradientBrush to change the offset value to the desired position. This is the code I am currently using, it works but simply apply a gray color to the image without changing the original colors of the image to gray-scale (resulting in a sort of a washed out colored image):
XAML:
<Image x:Name="myImage" HorizontalAlignment="Left" VerticalAlignment="Top" Source="C:\Users\Clement\Desktop\test.png" Canvas.Left="159" Canvas.Top="81" Width="500" Height="375" >
            <Image.OpacityMask>
                <LinearGradientBrush EndPoint="0.5,0" MappingMode="RelativeToBoundingBox" StartPoint="0.5,1">
                    <GradientStop x:Name="myImageLinearGradientBrushStop" Color="Black"/>
                    <GradientStop Color="Transparent" Offset="1"/>
                </LinearGradientBrush>
            </Image.OpacityMask>
</Image>

Code-behind (in a timerEventProcessor that repeats itself every 50ms):
myImageLinearGradientBrushStop.Offset = percent * 0.01;

As mentioned previously, I have browsed a lot of different websites, read a lot of similar questions and tried a lot of different answers and still cant satisfactorily solve the problem.

A: The XAML below uses a Grid with two rows to display two Images on top of each other. The Width and Heigh of the top Image are bound to the size of the bottom Image, which spans both Grid rows. An inner Grid is used to clip the top Image.
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Image x:Name="image" Grid.RowSpan="2" Source="..."/>

    <Grid>
        <Image Width="{Binding ActualWidth, ElementName=image}"
               Height="{Binding ActualHeight, ElementName=image}"
               HorizontalAlignment="Center" VerticalAlignment="Top">
            <Image.Source>
                <FormatConvertedBitmap Source="{Binding Source, ElementName=image}"
                                       DestinationFormat="Gray8"/>
            </Image.Source>
        </Image>
    </Grid>
</Grid>

A: Thanks to Clemens' help, I was able to get a solution to my problem!
This is the final XAML code for those whom might be interested:
<Grid Width="500" Height="375">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>

            <Image x:Name="image" Grid.RowSpan="2" Source="C:\Users\Clement\Desktop\test_image.png" />

            <Grid Margin="0,0,0,166" Grid.RowSpan="2">
                <Image Width="{Binding ActualWidth, ElementName=image}"
           Height="{Binding ActualHeight, ElementName=image}"
           HorizontalAlignment="Center" VerticalAlignment="Top">
                    <Image.Source>
                        <FormatConvertedBitmap Source="{Binding Source, ElementName=image}"
                                   DestinationFormat="Gray8"/>
                    </Image.Source>
                    <Image.OpacityMask>
                        <ImageBrush ImageSource="C:\Users\Clement\Desktop\test_image.png"/>
                    </Image.OpacityMask>
                </Image>
            </Grid>
        </Grid>

Here I simply added the OpacityMask to the Gray8 image to bring back its transparency.
Happy coding!


text:
Q: Which Layout supports android:layout_gravity? I came through many examples in internet.I found that neither Relative Layout nor Linear Layout supports android:layout_gravity.By it I mean the views inside these layouts does not support android:layout_gravity attribute. So any one having idea which layout supports android:layout_gravity and how to use it in better way?

A: Children (that is, direct descendants in the View hierarchy) of LinearLayout do use layout_gravity (see LinearLayout.LayoutParams), but only on the "secondary" axis. So, in a vertical LinearLayout, center_horiztonal will work, but center_vertical will do nothing.
Children of FrameLayout also support layout_gravity (see FrameLayout.LayoutParams).
Keep in mind that the layout_* parameters set values in a LayoutParams object provided by the view parent. So a layout_* parameter will only have an effect if the parent view supports the parameter.

A: Actually if you use RelativeLayout you don't need to use layout_gravity.Better way to position your layout's elements are android. Here you can get a good explanation how to use RelativeLayout.


text:
Q: python combinators list with constraints without itertools suppose I have a list with following elements [a,b,c,d,e]
how can I generate all possible combinations in such a way that every value can be moved to right, left or at the same position. For example with the above list all possible required combinations are
(a, b, c, d, e)
(a, b, c, e, d)
(a, b, d, c, e)
(a, c, b, d, e)
(a, c, b, e, d)
(b, a, c, d, e)
(b, a, c, e, d)
(b, a, d, c, e)

One way I can think of is, find all permutations and then filter according to the conditions described above but itertools won't work when the list size is 15 for example. Any idea how can I do this for large list?

A:
every value can be moved to right, left or at the same position

In your example this excludes the first item (which can only be moved to the right) and last (only to the left). Naively, therefore, the valid moves for each of your five items looks like:
>>> moves = [(0, 1)] + [(-1, 0, 1)] * 3 + [(-1, 0)]
>>> moves
[(0, 1), (-1, 0, 1), (-1, 0, 1), (-1, 0, 1), (-1, 0)]

Where -1 is move left, 0 is keep at same position and 1 is move right. Once you have this, you can use itertools.product to generate all combinations of those moves.
However, you claim 8 outputs for 5 items, and I get:
>>> from itertools import product
>>> all_moves = list(product(*moves))
>>> len(all_moves)
108

so it looks like there are some sets of moves that entail duplicates (which is logical - for example (0, -1, 0, 0, 0) looks just like (1, 0, 0, 0, 0)) and some that maybe can't actually be applied (how would you resolve (0, -1, -1, -1, -1)?)
>>> all_moves[:5]
[(0, -1, -1, -1, -1), (0, -1, -1, -1, 0), (0, -1, -1, 0, -1), (0, -1, -1, 0, 0), (0, -1, -1, 1, -1)]

Therefore your next step is to work out how to apply each tuple of moves to your starting list - for this, you will have to know how conflicts will be resolved (if the first item is moved forwards and the third item is moved backwards, for example, with (1, 0, -1, 0, 0), what is the result?) This may reveal a way you could simplify the problem further.

A: Here's what you want:
def swap_permute(vals):
    if len(vals) < 2:
        return [vals[:]]

    r1 = swap_permute(vals[1:])
    s1 = [vals[:1] + x for x in r1]

    r2 = swap_permute(vals[2:])
    s2 = [vals[1::-1] + x for x in r2]

    return s1 + s2

When invoked with:
swap_permute(["a", "b", "c", "d", "e"])

The result is:
[['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'e', 'd'],
 ['a', 'b', 'd', 'c', 'e'],
 ['a', 'c', 'b', 'd', 'e'],
 ['a', 'c', 'b', 'e', 'd'],
 ['b', 'a', 'c', 'd', 'e'],
 ['b', 'a', 'c', 'e', 'd'],
 ['b', 'a', 'd', 'c', 'e']]

This matches the output you posted, and in fact the order matches as well.
The solution is based on the observation that, when vals has at least 2 elements, the solutions can be divided into two cases:

*

*Those where the first element is in its original position

*Those where the first two elements are swapped


text:
Q: vertical and horizontal stretch items with flexbox stretch items using flex follow this context:
flex-direction: row; & align-items: stretch; ==> vertical stretch
flex-direction: column; & align-items: stretch; ==> horizontal stretch
my problem:
i have direction is row ,but i want vertical and horizontal stretch to appear like columns. symmetrical

.inner {
  display: flex;
  align-items: stretch;
  flex-wrap: wrap;
}

.inner button {
  display: flex;
  align-items: center;
  background-color: #E3F2FD;
  color: #304FFE;
  border: 1px solid #304FFE;
  padding-block: 5px;
  padding-inline: 6px;
  border-radius: 4px;
  margin-block: 2px;
  margin-inline: 10px;
}
<div class="inner">
  <button>Brightness</button>
  <button>Contrast</button>
  <button>Grayscale</button>
  <button>Saturate</button>
  <button>Sepia</button>
  <button>Invert</button>
</div>

my output:

my purpose:

A: add flex: 1; to the <button> html element.

like so:
.inner button {
  flex: 1;
  /* other code */
}

this means if there is some space left,
CSS flexbox tries to take all the space it can have.

also flex: 1 is a shorthand that can be also:
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;

like he said @G-Cyrillus it can break your code:
so put it inside a @media so only mobile versions have this behaviur

details:
https://developer.mozilla.org/en-US/docs/Web/CSS/flex?retiredLocale=it


text:
Q: Configure a Next JS authentication using joi I am trying to do an autentification using JWT and I need joi here:
import Joi from 'joi';
@Module({
  imports: [
...
    TypeOrmModule.forRoot(),
    ConfigModule.forRoot({
      validationSchema: Joi.object({
      JWT_SECRET: Joi.string().required(),
      JWT_EXPIRATION_TIME: Joi.string().required(),
    })})
]

but I don't really know how to declare it and I have this error:
validationSchema: joi_1.default.object({
TypeError: Cannot read property 'object' of undefined

And this is where i got Joi
    "joi": {
      "version": "17.4.0",
      "resolved": "https://registry.npmjs.org/joi/-/joi-17.4.0.tgz",
      "integrity": "sha512-F4WiW2xaV6wc1jxete70Rw4V/VuMd6IN+a5ilZsxG4uYtUXWu2kq9W5P2dz30e7Gmw8RCbY/u/uk+dMPma9tAg==",
      "requires": {
        "@hapi/hoek": "^9.0.0",
        "@hapi/topo": "^5.0.0",
        "@sideway/address": "^4.1.0",
        "@sideway/formula": "^3.0.0",
        "@sideway/pinpoint": "^2.0.0"
      }

I think I am missing something, but I am new in this.

A: Instead of import Joi from 'joi'; use import * as Joi from 'joi';


text:
Q: Flink TaskManager cannot connect to JobManager in docker swarm task I cannot manage to make a TaskManager communicate with the JobManager on a docker swarm stack.
The content of the stack.yml file I use to docker stack deploy is:
version: "3"
services:
  jobmanager:
    image: affo/flink:1.1.3
    ports:
      - "48081:8081"
    command: jobmanager
    networks:
      - my-net
    deploy:
        mode: replicated
        replicas: 1
        restart_policy:
            condition: none
        placement:
            constraints:
                - node.role == manager

  taskmanager:
    image: affo/flink:1.1.3
    depends_on:
      - jobmanager
    command: taskmanager
    networks:
      - my-net
    deploy:
        mode: replicated
        replicas: 4
        restart_policy:
            condition: none
        placement:
            constraints:
                - node.role != manager

networks:
    my-net:
        external: true

Docker image affo/flink:1.1.3 is a push on dockerhub of the image built following the README @ https://github.com/apache/flink/tree/release-1.1.3-rc2/flink-contrib/docker-flink.
Network my-net is an overlay attachable network.
I tried to ping every container from others using DNS resolution and everything works correctly.
However no TaskManager can make it through to the JobManager.
I report the JobManager log: http://pastebin.com/Ai5s4Xvr
And the log of one TaskManager: http://pastebin.com/ty5pZhSp
The JM has VIP 10.0.42.7. And jobmanager.rpc.address is set to jobmanager which resolves to 10.0.42.7.
Any help or hint on where to start solving the problem would be appreciated.
Thanks a lot!
UPDATE
I add the output of docker exec <jobmanager> netstat -tulpn:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.11:40762        0.0.0.0:*               LISTEN      -
tcp        0      0 ::ffff:10.0.42.7:6123   :::*                    LISTEN      218/java
tcp        0      0 :::8081                 :::*                    LISTEN      218/java
tcp        0      0 :::34963                :::*                    LISTEN      218/java
udp        0      0 127.0.0.11:57000        0.0.0.0:*                           -

And of docker exec <a_taskmanager> telnet jobmanager 6123:
telnet: can't connect to remote host (10.0.42.7): Connection refused

I also put a link to a maybe-related issue on github: https://github.com/docker/docker/issues/28795.
Thanks again
UPDATE
I recently managed to change the jobmanager.rpc.address to 0.0.0.0 only at the JobManager's and now it is effectively listening:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.11:56218        0.0.0.0:*               LISTEN      -
tcp        0      0 :::6123                 :::*                    LISTEN      218/java
tcp        0      0 :::8081                 :::*                    LISTEN      218/java
tcp        0      0 :::55231                :::*                    LISTEN      218/java
udp        0      0 127.0.0.11:47549        0.0.0.0:*                           -

I can even nc or telnet from TaskManagers.
However, now the problem is (on the JobManager):
2017-02-09 10:31:20,794 ERROR akka.remote.EndpointWriter
- dropping message [class akka.actor.ActorSelectionMessage] for non-local recipient
[Actor[akka.tcp://flink@10.0.42.7:6123/]] arriving at [akka.tcp://flink@10.0.42.7:6123]
inbound addresses are [akka.tcp://flink@0.0.0.0:6123]

Any help would be appreciated, thank you!
UPDATE
I think I isolated the problem. Issue opened on github: https://github.com/docker/docker/issues/30874

A: If you follow the issue opened on Github, you can understand that the real problem was in swarm native networking VIP assignment. I turned it off and everything works now.
Actually, there is no way up to now to turn it off from compose file, so, I had to switch to a scripted deploy rather than an automatic docker stack deploy.


text:
Q: "Object controller", Entity mode: fetching is slow on Mavericks It takes 5 seconds to load 8425 items on the last iMac.

I don't know what else add to provide you more info. I'm loading the items for the drop down list of a NSComboBox.
I've tested on Snow Leopard and Mountain Lion and it works fine. Tried on several machines, it works fine on all osx except for Mavericks. Same build and database files.

A: My guess is that NSComboBox loads all items one by one and CoreData has to make a roundtrip to the disk each time. You should inspect this situation with Instruments to know for sure what's going on.
Try prefetching all items before showing them. You can use -[NSFetchRequest returnsObjectsAsFaults:] property set to NO during such fetch.
Here's a snippet from my project that does prefetching:
if ( ! didPrefetch)
{
    didPrefetch = YES;

    // Your fetch request that will load all items
    NSFetchRequest* fetchRequest = ... ;

    // If you need to prefetch some relationships
    fetchRequest.relationshipKeyPathsForPrefetching = @[...];

    // This forces objects to fault info row cache
    fetchRequest.returnsObjectsAsFaults = NO;

    [managedObjectContext executeFetchRequest:fetchRequest error:&error];
}


text:
Q: Lock scrolling in python console How i can lock scrolling in python console? I print several lines to console and I don't want to user can scroll window up or down. Is there any library/command that can allow me to do that?
Thanks!


text:
Q: Google Maps loading is very slow My site's Google map is very slow! When ever you do anything, zoom in or out or move the map, my loader spins for too long. I was told it is probably because everything is programmed to load before it will display. Any ideas?
Heres mine
My Map
Heres one i would love to replicate, it is very fast. Follow link below and click "Map" in top right emnu bar next to "List".
VRBO Map

A: May be your api version are old, please make sure and then use latest loading supported version....
Use this version
http://maps.google.com/maps/api/js?sensor=false&v=3.5
instead of this
https://maps.googleapis.com/maps/api/js?key=AIzaSyCONGB2LuIR6U3cT63dnC5IOzRWKWAGWAI&v=3.exp&sensor=false&libraries=places
(any...)