text:
Q: Public Holiday Checker (UK) I need to prevent entry to a car park system during public holidays, but instead of making more classes i was hoping it could be done within my existing method. my question is, is there such thing in java that already has public holiday dates predefined and can be used within if state or some sort to prevent entry if todays date matches those list of public holiday dates.
this is my existing method.which as you can see checks if its weekend, saturday and sunday, both which are public day off. but in uk there are more days such as bank holidays, but how do i define all the rest of the dates.
public boolean checkHoliday(){
    Calendar cal = Calendar.getInstance();
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    if (dayOfWeek == 1 || dayOfWeek == 7){
        return true;
    } else {
        return false;
    }
    /*add method for further holiday date check*/

}

A: You can grab an XML from google public holiday for UK.
If you prefer ICAL format, here it is.
And if you like to check what's in it just look here.

A: It's not quite a library that you can just call locally but http://www.holidaywebservice.com/ is a web service that will give you what you need.

A: You can use this library is written in C#, but a JSON/XML Webservice is available.
https://github.com/tinohager/Nager.Date
JSON Webservice
Get the public holidays for United Kingdom for the year 2018
http://date.nager.at/api/v1/get/GB/2018
More information about the available API methods you can found here
Java Example
//https://github.com/FasterXML/jackson-databind/
ObjectMapper mapper = new ObjectMapper();
MyValue value = mapper.readValue(new URL("http://date.nager.at/api/v1/get/US/2018"), PublicHoliday[].class);

PublicHoliday.class
public class PublicHoliday
{
    public String Date;
    public String LocalName;
    public String Name;
    public String CountryCode;
    public Boolean Fixed;
    public Boolean CountyOfficialHoliday;
    public Boolean CountyAdministrationHoliday;
    public Boolean Global;
    public String[] Counties;
    public int LaunchYear;
}

Example JSON data retrieved
[
  {
    "date": "2017-01-01",
    "localName": "New Year's Day",
    "name": "New Year's Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-01-16",
    "localName": "Martin Luther King, Jr. Day",
    "name": "Martin Luther King, Jr. Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-01-20",
    "localName": "Inauguration Day",
    "name": "Inauguration Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": false,
    "counties": [
      "US-DC",
      "US-LA",
      "US-MD",
      "US-VA"
    ],
    "launchYear": null
  },
  {
    "date": "2017-02-20",
    "localName": "Washington's Birthday",
    "name": "Presidents' Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-05-29",
    "localName": "Memorial Day",
    "name": "Memorial Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-07-04",
    "localName": "Independence Day",
    "name": "Independence Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-09-04",
    "localName": "Labor Day",
    "name": "Labor Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-09-09",
    "localName": "Columbus Day",
    "name": "Columbus Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": false,
    "counties": [
      "US-AL",
      "US-AZ",
      "US-CO",
      "US-CT",
      "US-DC",
      "US-GA",
      "US-ID",
      "US-IL",
      "US-IN",
      "US-IA",
      "US-KS",
      "US-KY",
      "US-LA",
      "US-ME",
      "US-MD",
      "US-MA",
      "US-MS",
      "US-MO",
      "US-MT",
      "US-NE",
      "US-NH",
      "US-NJ",
      "US-NM",
      "US-NY",
      "US-NC",
      "US-OH",
      "US-OK",
      "US-PA",
      "US-RI",
      "US-SC",
      "US-TN",
      "US-UT",
      "US-VA",
      "US-WV"
    ],
    "launchYear": null
  },
  {
    "date": "2017-11-10",
    "localName": "Veterans Day",
    "name": "Veterans Day",
    "countryCode": "US",
    "fixed": false,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  },
  {
    "date": "2017-12-23",
    "localName": "Thanksgiving Day",
    "name": "Thanksgiving Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": 1863
  },
  {
    "date": "2017-12-25",
    "localName": "Christmas Day",
    "name": "Christmas Day",
    "countryCode": "US",
    "fixed": true,
    "countyOfficialHoliday": true,
    "countyAdministrationHoliday": true,
    "global": true,
    "counties": null,
    "launchYear": null
  }
]


text:
Q: Image not Showing in my site This IS NOT SHOWING THE PIC IN MY SITE
<img src="C:\\Users\\dave\\Desktop\\myProject\\UsersPics\\4\\1.png" />

IF I HOVER WITH THE MOUSE ON THE img IT GIVE ME AN OPTION TO DO ENCODE IN BASE 64 RESULT SOMETHIN LONG AND UGLY THAT WORKING
http://jsfiddle.net/0knayyjL/1/
My question is how i do the Conversion in razor syntax on the img path

A: You can't do a local machine path like that. Think about who's receiving the HTML. The client receives the HTML. C:\\Users\\dave\\Desktop\\myProject\\UsersPics\\4\\1.png Probably isn't on their machine. You have to host the image as part of your site (usually the Content folder) and use a relative path to that (such as /Content/1.png).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set Header and Footer with Scrolling Content in Android where footer does not sit above keypad? I am using custom header and footer with scrollable contents in my layout activity. The problem which i am facing is "Footer comes up with keypad when keypad pops up". Also, the background image shrinks. I have to keep footer at the bottom and image stretched even if keypad opens. I tried to set android:windowSoftInputMode="stateHidden|adjustPan" but my header went offscreen when the last edittext was focused. Please help. This is my main layout
main_layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/dashboard">

<include
    android:id="@+id/toolbar"
    layout="@layout/header_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" />

<include
    android:id="@+id/footer"
    layout="@layout/footer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/footer"
    android:layout_below="@+id/toolbar"
    android:fillViewport="true">

    <LinearLayout style="@style/linear_layout_inside_scrollview">

        <TextView
            style="@style/text_view_white"
            android:gravity="center"
            android:textSize="@dimen/large_text"
            android:lineSpacingExtra="@dimen/line_space"
            android:text="@string/email_check_label" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <EditText
            style="@style/edit_text_pre_login"
            android:layout_marginTop="@dimen/inputs_margin"
            android:gravity="center" />

        <Button
            android:id="@+id/goToMobileCheck"
            style="@style/pre_login_button"
            android:layout_marginTop="@dimen/inputs_margin"
            android:onClick="goToMobileCheck"
            android:text="@string/next" />
    </LinearLayout>
</ScrollView>

A: Try adding folowing to your AndroidManifest in your this activity of ypur layout
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
android:configChanges="keyboardHidden"

A: just use--
android:windowSoftInputMode="adjustPan"


text:
Q: Protect Chef config when a node is compromised Imagine that one node of a system gets compromised. If I understand correctly hacker will be able to get all configs for all servers in a system using chef's API. Is that correct? If yes, is there a way to ensure that a node only gets information required for its configuration?

A: The pem key for that server is unique to that chef organization and node.  That is how it identifies itself to the chef server and makes sure that node attributes pertain to only that node.  Which is why when you change chef-orgs, you have to re-bootstrap the server.  Additionally, when you try to execute using chef-client on a different box with the same pem key or even a rebuilt box with the old pem key, it will not work.
Encrypted data bags stored on the server still require a secret key passed to chef-client from knife.


text:
Q: Using d3js within objects - this context collision I want to use d3js within an object (Backbone.View in my case).
The problem I am facing (being both a javascript and a d3js newbie) is that in functions on selections the "this" context is set to the current Dom object. So I cant access the object methods anymore within the function. If I bind the function to the "this" of the object (via underscore for example) I loose access to the current Dom object. In case of events I found some workaround using d3.event yet I hope to get some general advice how to use d3js within objects and solving the described problem in general. (without workarounds...)
Thanks
martin
UPDATE:
As an example, within the "selection.each(function)" (see d3js API docu) the this is the current DOM element so I cant access methods of the object (this.objectMethod())


text:
Q: No boot option after installing Ubuntu I was trying to install Ubuntu 16.04 on my laptop(Asus) but NOT with windows as I erased the full drive to be just for linux. I had the problem of GRUB which is:
Unable to install GRUB in /dev/sda
Executing grub-install /dev/sda failed.
This is a fatal error.
I tried to use boot-repair but it didn't work. so next I tried to remove all the partitions and create new ones and in the boot loader installation I added the exact location where the Ubuntu should be installed eg:/sdb1
problem now is that it finish the installation, tells me to restart the device but when I do, it boots from the USB and its like no operating system is there from the first place to boot from.
I checked my BIOS and if I remove the bootable USB it says NO BOOTABLE DEVICES and when I do put it back it can only see the USB.
If anyone knows please try to elaborate your solution in the best way as I am a bit new to these fixes
Thank you

A: You probably installed with legacy mode and your computer doesn't know about legacy, it tries to boot in UEFI mode and searches for a UEFI/EFI partition. If it doesn't find a UEFI partition then it wouldn't boot like in your case.
When partitioning a disk for Ubuntu , if you want it to be UEFI then you should create a partition for UEFI. For example i have a 300mb fat32 UEFI partition and i flagged it when partitioning.
An example UEFI partitioning:

*

*200-500MB FAT32 UEFI (This must be flagged)

*--As much as you like--GB Ubuntu OS

*--Usually twice as RAM--GB swap
In your case, you should boot from live cd/usb and partition your disk with GParted. In GParted, partition your disk with the example provided above and make sure you flagged your UEFI partition to boot and you are good to go.
After partitioning turn off the live session and start the installation , if you did everything correct, you should not be selecting a mount point for bootloader.
You can get more information from here. UEFI-Community

A: In my case - my problem was WHICH USB Flash drive boot entry I would choose.
My ASRock UEFI boot selection had 2 entries:
USB - Flash drive
UEFI - USB Flash drive partition 1
Whenever I chose the first one (I guess this is what everyone is calling "LEGACY"), it would install, but then on boot, I was presented with a grub PROMPT, not even a menu of choices.  So there really wasn't anything that I could do.
However, if I choose the UEFI - USB Flash drive and then install, then everything works as expected.


text:
Q: How to change an array item value inside an object passed as state in React? I have an React application, all my components are functional and I'm using useState hook to manage the state. I'm passing the state as an single object, as showed below:
const initialState = {
  displayValue: "0",
  values: [0, 0],
  current: 0,
  operation: null,
  shouldClearDisplay: false,
};

const [state, setState] = useState({ ...initialState });

I can change the state of displayValue as showed below:
setState({...state, displayValue: "0"})

The problem is when I try to change the value of values. What I trying to do is this:
const addDigit = (digit) => {
  if (state.shouldClearDisplay) {
    setState({ ...state, values[current]: displayValue , displayValue: digit, shouldClearDisplay: false });
      return;
    }

But when I try to do this values[current]: displayValue, it gives a sintax error: SyntaxError: /path/to/component/Calculator.jsx: Unexpected token, expected "," (22:33). It seems that I can't update the value of an array inside an object that way.
How can I achieve this?
EDIT 01:
Below the entire content of Calculator.jsx:
import React, { useState } from "react";
import CalcButton from "./CalcButton";
import Display from "./Display";

const Calculator = (props) => {
  const initialState = {
    displayValue: "0",
    values: [0, 0],
    current: 0,
    operation: null,
    shouldClearDisplay: false,
  };

  const [state, setState] = useState({ ...initialState });

  const resetState = () => {
    setState({ ...initialState });
  };

  const addDigit = (digit) => {
    if (state.shouldClearDisplay) {
      setState({ ...state, values[state.current]: displayValue , displayValue: digit, shouldClearDisplay: false });
      return;
    }

    if (state.displayValue === "0") {
      setState({ ...state, displayValue: digit });
      return;
    }

    if (digit === "0" && state.displayValue === "0") {
      return;
    }

    setState({ ...state, displayValue: state.displayValue + digit });
  };

  const setOperation = (op) => {
    setState({ ...state, shouldClearDisplay: true, operation: op });
  };

  const c = {
    lightGray: "#d7d9ce",
    darkGray: "#8e9aa4",
    orange: "#fc7536",
    black: "#010f14",
  };

  return (
    <React.Fragment>
      <Display bgColor={c.black} value={state.displayValue} />

        <CalcButton
          text="AC"
          width="180px"
          passedOnClick={resetState}
          bgColor={c.lightGray}
        />
        <CalcButton text="÷" passedOnClick={setOperation} bgColor={c.orange} />

        <CalcButton text="7" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="8" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="9" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="X" passedOnClick={setOperation} bgColor={c.orange} />

        <CalcButton text="4" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="5" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="6" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="-" passedOnClick={setOperation} bgColor={c.orange} />

        <CalcButton text="1" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="2" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="3" passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="+" passedOnClick={setOperation} bgColor={c.orange} />

        <CalcButton
          text="0"
          passedOnClick={addDigit}
          width="120px"
          bgColor={c.lightGray}
        />
        <CalcButton text="." passedOnClick={addDigit} bgColor={c.lightGray} />
        <CalcButton text="=" passedOnClick={setOperation} bgColor={c.orange} />

    </React.Fragment>
  );
};

export default Calculator;

A: You should calculate your state first and then update it
  const [state, setState] = useState(initialState);

  const addDigit = (digit) => {
    if (state.shouldClearDisplay) {
      let temp = [...state.values];
      temp[state.current] = state.displayValue;
      setState({
        ...state,
        values: temp,
        displayValue: digit,
        shouldClearDisplay: false
      });
    }
  };

A: Create a new array where element at current index is displayValue. Then assign this array to values.
A simple example would be like this
const addDigit = (digit) => {
  if (state.shouldClearDisplay) {
    setState({
      ...state,
      values: state.values.map((v,i) => i===state.current ? displayValue : v),
      displayValue: digit,
      shouldClearDisplay: false
    });
    return;
  }
}


text:
Q: Trying to install Magento, get error msgs about PHP version & extensions I've downloaded and installed XAMPP.
Now I'm trying to install Magento on my Windows10 laptop.
The problem is, Magento Installer is giving me this error,

So I downloaded and extracted PHP 7.0.6. But I don't know how to install it.

Another problem is about the extension as shown in the picture below,

How to solve these problems, please help. Thank you.

A: Step 1 : Open your xampp control
Step 2 : Click config open php.ini or (install xampp location xampp\php\php.ini)
Step 3 : rename ;extension=php_xsl.dll to extension=php_xsl.dll
Step 4 : rename ;extension=php_intl.dll to extension=php_intl.dll


text:
Q: pick the first result for each parameter I have a table with account_number, account_code and code_date
I am trying to get the latest code for each account, but the group by is giving me multiple observation for each account, thus I can't even use the first/top statement.
example:
account_id  Account_Attribute_Code   current_att_date
1                579                      01.01.2005
1                254                      01.02.2006
1                366                      10.10.2018
2                748                      01.07.2008
2                766                      08.05.2009
2                205                      07.06.2014

 SELECT
       account_id,
       Account_Attribute_Code,
       Max(Account_Attribute_Update_Date) AS current_att_date
 FROM my_table
 GROUP BY Account_Id,
          Account_Attribute_Code

I want to have only 1 row for each account, with his attribute_code where the date is the most current.

A: On SQL Server, I would use:
SELECT TOP 1 WITH TIES
    account_id, Account_Attribute_Code, Account_Attribute_Update_Date
FROM my_table
ORDER BY
    ROW_NUMBER() OVER (PARTITION BY account_id
                       ORDER BY Account_Attribute_Update_Date DESC);

A: You can just use a correlated subquery:
select t.*
from t
where t.Account_Attribute_Update_Date = (select max(t2. Account_Attribute_Update_Date)
                                         from t t2
                                         where t2.account_id = t.account_id
                                        );

There are multiple approaches to this problem.  With an index on (account_id, Account_Attribute_Update_Date), then this normally has the best performance.
One caveat:  If there are duplicate maximum dates for an account, you will get multiple rows.

A: You can use row_number() function
 SELECT
       account_id,
       Account_Attribute_Code,
       Account_Attribute_Update_Date,
       ROW_NUMBER() OVER (PARTITION BY account_id
                       ORDER BY Account_Attribute_Update_Date DESC) as rn
 FROM my_table where rn=1


text:
Q: Надежная реализация автоматического подключения клиентов к серверу Есть около сотни локальных метеостанций. Основа - Raspberry Pi или иные одноплатники с UNIX. Связь с внешним миром они производят через 3G-модемы. IP адреса серые.
Стоит задача управлять этими станциями(калибровка, установка алармов, удаленное обновление ПО станции, получение данных по запросу).
Можно было бы реализовать сервис в сети, куда все станции по-умолчанию бы "стучались" и получали бы информацию или отправляли данные POSTом. Но в случае переезда сервера(из-за внезапных блокировок, привет, РКН) такая технология провалится, т.к. придется ездить по всем блокам и вручную изменять сервер, в который они стучатся. А также, я думаю, страдает оперативность управления.
Есть идея использовать VPN, организуя P2P-сеть и управлять станциями напрямую по TCP, кидаясь в нужный адрес пакетами. Но как сообщить всем устройствам новый VPN, если сервер сменится? Можно с помощью стороннего сервиса, в который будут стучаться устройства перед подключением к VPN для получение актуального адреса сервера. Но если этот сервис "кончится", то опять все сводится к объезду устройств и ручной работе.
Может кто имел подобный опыт или я прошел мимо какой-то технологии, которая полностью решает проблему?

A: Все что вам нужно - это отдельный домен для сервера. Напомню, что в отличии от IP-адресов домены не подвержены ковровым блокировкам.
Просто прописывайте на метеостанциях доменное имя вместо IP-адреса. Если IP-адрес изменится - вы просто измените DNS-запись и через какое-то время все метеостанции узнают новый адрес сервера. Временем переключения можно управлять через параметр TTL в настройках зоны DNS.

A: У нас была подобная задача, специфика немного другая, но тоже одноплатники. Был один сервер, куда они все стучались, чтобы слить данные и получить обновления. Иногда сервер был загружен, иногда недоступен, в итоге печаль.
Решили через заведение нескольких мелких промежуточных серверов у разных местечковых провайдеров по стране. Например 4. Просто 4 домена или поддомена, на который поочереди (или по длине пинга) заходит каждый одноплатник и спрашивает, куда ему лить данные. Ему отвечают (сейчас всегда один сервер, но можно и балансировать на несколько, если вам нужно), и пошла работа.
Вероятность отказа сразу всех 4 хостингов в разных регионах страны ниже, чем одного сервера в МСК, нас пока такой вариант устроил. VPN не использовали, все дела происходят внутри страны. Пока вроде работает. Если вам не нравится число 4, берите любое, за домены надо платить и за хостинг тоже. Немного, но надо.
В будущем думаем подключить репликацию БД, чтобы собирать данные сразу на всех точках и смешивать, а не на одном сервере.
Я понимаю, что это немного велосипед конечно и на полноценный ответ не тянет. Но этот велосипед решает нашу проблему, поэтому делюсь.


text:
Q: How could I use SVG icons with the  and  tags I have an Angular 1.5 application that communicate with Salesforce using REST API.
Salesforce require us to use SVG icons with the following syntax:
<svg aria-hidden="true" class="slds-icon slds-icon--large slds-icon-standard-user">
    <use xlink:href="{!URLFOR($Asset.SLDS, 'assets/icons/standard-sprite/svg/symbols.svg#user')}"></use>
</svg>

In salesforce does work well.
I'm trying to use locally in order to develop but does not work. I tried the following code:
<svg aria-hidden="true" class="slds-icon slds-icon--large slds-icon-standard-user">
    <use xlink:href="/path/to/the/icon.svg"></use>
</svg>

According to this documentation we need to add within the HTML element the following code:
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

But no luck! :(
Any idea to use SVG with those tags and refer to a local file?

A: Use <img> and set your src reference to the local path of your .svg file.

<img class="papa" src="http://s.cdpn.io/3/kiwi.svg">

More here: https://css-tricks.com/using-svg/


text:
Q: Add Genesis PHP line to post_info I have a PHP statement
<?php echo get_post_meta( $post->ID, 'jetpack-post-views', true ); ?>

This i used by a wordpress plugin called "Jetpack post views"
It asked me to place the provided code anywhere on the page to see the post views.
I want it on "genesis_entry_header" with the other post_info
I don't know how to do that, and I look everywhere for a solution before I post this.
Thank you

A: Try with this,
function wp_87978_jpv(){
    global $post;

    echo get_post_meta( $post->ID, 'jetpack-post-views', true );
}
add_action('genesis_entry_header', 'wp_87978_jpv');


text:
Q: UIVisualEffectView built in storyboard is opaque I've built an UIView in storyboard that is composed like this:
UIView (called _view)

 UIVisualEffetView (dark)

  UIVIew

   Button

I've done like this for the ability to reuse it between several Navigation Controller. So for this I've set everything and I can show my view in my main controller called "ViewController" that is embedded in a navigation controller. But the issue is that the blur is opaque, for example the blue navigation bar of my view controller is not visible under the UIVIsualAffectView !
Here is the code I use for setting up the custom view :
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    _view.backgroundColor = [UIColor clearColor];
    UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"SideMenuView" owner:self options:nil] objectAtIndex:0];

    CGRect newFrame = rootView.frame;

    newFrame.size.width = [[UIScreen mainScreen] bounds].size.width / 2;
    newFrame.size.height = [[UIScreen mainScreen] bounds].size.height;
    [rootView setFrame:newFrame];

    UIWindow* currentWindow = [UIApplication sharedApplication].keyWindow;
    currentWindow.backgroundColor = [UIColor clearColor];
    currentWindow.windowLevel = UIWindowLevelNormal;

    [currentWindow addSubview:rootView];

}

And here is the code I use to call the view from my main controller:
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.leftBarButton setTarget:self];
    [self.leftBarButton setAction: @selector(test)];
}

- (void)test {

    SideMenuView *test = [[SideMenuView alloc] init];
    [self.view addSubview:test];
    test.translatesAutoresizingMaskIntoConstraints = NO;

}

I've also tried to force the property "setOpaque" to No in my SideMenuView.m but without effect
Here is a screenshot of what it do:

Do you know guys what is wrong with my code ?
I've also added a button in the middle of the screen with a blue background but it's not visible under the blur so the issue is not navigation bar specific
Thanks in advance for your help !

A: I've resolved my issue by simply creating an UIView with clear background.
What I do for adding the blur effect is to create the UIVisualEffectView programmatically (doing this way it work perfectly !).
After that I'm adding my UIView as a subview of my UIVisualEffectView and voila :)


text:
Q: Jquery Image Slider Not Working on Mobile I have been noticing some strange behavior with a new website I've been working on.  Essentially, I have a landing page which has a large banner image as the background which fades into other images every five seconds using Jquery.  On computers, the fading sequence works brilliantly, but the images never show up when viewing it on a mobile device (iphone, ipad, etc).  I originally thought it had something to do with the screen size of the viewing device (which was causing the images not to show up on an iphone)... however, this issue appears to happen on the ipad as well, so I'm not sure if screen resolution is actually the problem.
The code I'm using is a slight modification of an online tutorial.  Basically, here is the html code:

And the Jquery code looks like this:

There is also a bit of CSS code, but I'm not entirely sure this would be causing the issue.  Nonetheless:
#slideshow_content {
  top: 50%;
  position: fixed;
}
#slideshow {
  position: absolute;
  z-index: -1;
}
#slideshow IMG {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 8;
  opacity: 0.0;
}
#slideshow IMG.active {
  z-index: 10;
  opacity: 1.0;
}
#slideshow IMG.last-active {
  z-index: 9;
}
#slideshow img {
  max-width: 100%;
  height: auto;
  width: auto;
  position: fixed;
  top: 50%;
  left: 0;
}

Also, the link to the website I'm working on which has this issue can be found at: www.liftarchitects.com


text:
Q: ¿Como agregar imágenes a un template de correo en Cake PHP 3? me encuentro con el siguiente problema, agregue un template html que yo misma cree para que sea visualizado en el correo enviado desde mi sistema pero al recibirlo me doy cuenta que no se visualizan mis logos.
Este es mi codigo del template para el correo la ruta esta src/template/layout/Email/html:
<!DOCTYPE HTML>

                            Titulo o subtitulo

                            Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor

                                    Links de referencía

                            Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor, Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor

                    <button style="border: none; font-size: 18px;border-radius: 3px;padding: 12px 25px;box-shadow: 0 2px 0 0 #1b5dab;color: #fff;background-color: #4A90E2;border-color: #3483de;" type="button">Call to action buttom</button>

Nose que este haciendo mal, alguien podría ayudarme.

A: Lo solucione de la siguiente manera, desde la funcion que tengo en UsersMaile, cargo la imagen dentro de attachments pongo un id y el id lo llamo en el html
$this
   ->from(['contacto@dgb.email' => 'Contacto Red Prepa Abierta'])
   ->to($user->email)
   ->emailFormat('both')
   ->subject(sprintf('Bienvenido %s', $user->nombre))
   ->attachments([

            'img.png'=>[
            'file'=>ROOT.DS.'webroot'.DS.'img'.DS.'img.png',
            'mimetype'=>'image/png',
            'contentId'=>'734h3r38'
            ],
          ])
          ->template('welcome', 'default');
    }

En el HTML  llamo el contentId quedo asi:


text:
Q: Bluetooth connection from an android App to Lego Mindstorm EV3 brick I am trying to create an Android App that sents small integers to my EV3 brick, so it can do Actions based on those numbers.
My Problem ist that I can not create a Bluetooth Connection to the Brick in my own App. Has anybody experience with that and knows which sockets or libarys i should use to get that working? I am using the lejos 0.8 api on my brick.


text:
Q: RTFString Containing NSASCIIStringEncoding Special Characters? I have a string in my cocoa GUI that needs to have special formatting (fonts, colors, etc.). Naturally, I'm using an attributed string. For convenience, I Init the string as an RTF:
NSString *inputString = @"This string has special characters";
NSString *rtfString = [NSString stringWithFormat:@"{@"***LENGTHY RTF FORMATTING STRING *** %@", inputString];
NSAttributedString *testString = [[NSAttributedString alloc] initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];

The problem is, the "inputString" might have special characters, which are not displayed properly due to the UTF8Encoding. They're replaced with other symbols.
é is left as Å©.
So, right now I'm doing this:
NSData* intermediateDataString=[inputString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

inputString = [[[NSString alloc] initWithData:intermediateDataString encoding:NSUTF8StringEncoding] autorelease];

This does not display the unexpected characters, but it does remove all accents and leaves in their stead the unaccented letter - é is left as e.
This is an improvement since everything can be read, but it is far from ideal.
Thoughts?

A: I would do something like this. First, create a dummy attributed string:
NSString *dummyRTFString = @"***LENGTHY RTF FORMATTING STRING *** A";
NSAttributedString *dummyAS = [[NSAttributedString alloc]
                                      initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding]
                               documentAttributes:nil];

and obtain the attributes:
NSDictionary*attributes=[dummyAS attributesAtIndex:0 effectiveRange:NULL];
[dummyAS release];

Now I will use this attribute to create another attributed string:
NSAttributedString* as=[[NSAttributedString alloc] initWithString:inputString attributes:attributes];

Another approach is to use HTML instead of RTF; then you can include non-ascii characters as unicode in it.

A: In your first line of code, I assume that's really @"This string has special characters" otherwise you'd get a compile error.  And it looks like your second line has an extra @".
If you know you're using UTF-8, why say NSASCIIStringEncoding?
Really, you should put the RTF including the string with special characters in a resource, not embedded in your code.


text:
Q: How do I free memory in a lazy_static? The documentation states that if the type has a destructor, it won't be called: https://docs.rs/lazy_static/1.4.0/lazy_static/#semantics
So how am I supposed to free the memory?

A:
So how am I supposed to free the memory?

That question isn't even wrong.
The entire point of lazy_static is that the object lives forever, that's what a static is, when would anything be freed? The note is there for non-memory Drop, to indicate that if e.g. you use lazy_static for a file or a temp they will not be flushed / deleted / … on program exit.
For memory stuff it'll be reclaimed by the system when the program exits, like all memory.

A:
So how am I supposed to free the memory?

Make your lazy_static an Option, and call take() to free the memory once you no longer need it. For example:
lazy_static! {
    static ref LARGE: Mutex<Option<String>> =
        Mutex::new(Some(iter::repeat('x').take(1_000_000).collect()));
}

fn main() {
    println!("using the string: {}", LARGE.lock().as_ref().unwrap().len());
    LARGE.lock().take();
    println!("string freed")
    assert!(LARGE.lock().is_none());
}

Playground
As others have pointed out, it is not necessary to do this kind of thing in most cases, as the point of most global variables is to last until the end of the program, at which case the memory will be reclaimed by the OS even if the destructor never runs.
The above can be useful if the global variable is associated with resources which you no longer need past a certain point in the program.


text:
Q: Exchange two elements of a vector in one call I have a vector c(9,6,3,4,2,1,5,7,8), and I want to switch the elements at index 2 and at index 5 in the vector. However, I don't want to have to create a temporary variable and would like to make the switch in one call. How would I do that?

A: If you actually want to do it without creating a temporary copy of the vector, you would need to write a short C function.
library(inline)
swap <- cfunction(c(i = "integer", j = "integer", vec="integer"),"
                  int *v = INTEGER(vec);
                  int ii = INTEGER(i)[0]-1, jj = INTEGER(j)[0]-1;
                  int tmp = v[ii];
                  v[ii] = v[jj];
                  v[jj] = tmp;
                  return R_NilValue;
                  ")

vec <- as.integer(c(9,6,3,4,2,1,5,7,8))
swap(2L, 5L, vec)

vec
# [1] 9 2 3 4 6 1 5 7 8

A: How about just x[c(i,j)] <- x[c(j,i)]? Similar to replace(...), but perhaps a bit simpler.
swtch <- function(x,i,j) {x[c(i,j)] <- x[c(j,i)]; x}
swtch(c(9,6,3,4,2,1,5,7,8) , 2,5)
# [1] 9 2 3 4 6 1 5 7 8

A: You could use replace().
x <- c(9, 6, 3, 4, 2, 1, 5, 7, 8)
replace(x, c(2, 5), x[c(5, 2)])
# [1] 9 2 3 4 6 1 5 7 8

And if you don't even want to assign x, you can use
replace(
    c(9, 6, 3, 4, 2, 1, 5, 7, 8),
    c(2, 5),
    c(9, 6, 3, 4, 2, 1, 5, 7, 8)[c(5, 2)]
)
# [1] 9 2 3 4 6 1 5 7 8

but that's a bit silly.  You will probably want x assigned to begin with.


text:
Q: How to do barrier in swift 3 I do push notifications. If there is no data in the database, they downloaded before display.  I did a time interval using Grand Central Dispatch, but it is not right because for example if the user is a weak Internet application falls.
How delay with barrier of GCD the display of the data before download data?
This code with time interval:
if equal == false {
    let url = "https://****.**/json/post/\(data)"
    self.download.getLastestNews(url)
}

let when = DispatchTime.now() + 2

DispatchQueue.main.asyncAfter(deadline: when) {
    let newsCategory = self.realm.objects(News.self).filter("newsID == \(self.id)")
    vc.titleText = (newsCategory.first?.newsTitle)!
    vc.fullText = (newsCategory.first?.newsFullText)!
    vc.imageLink = (newsCategory.first?.newsImage)!

if let tabBarController = self.window?.rootViewController {
   tabBarController.present(vc, animated: true, completion: nil)
   }
}

Platform iOS 9.*, iOS 3

A: Delaying the queue won't always work because as you said, sometimes Internet connection is too slow and there might be no data received, so the program may fail with error. While downloading anything from Internet, check for completion handling methods. Inside them use the code you gave in DispatchQueue closure.


text:
Q: Interactive GUI-like command line merging tool (like BeyondCompare or WinMerge) for Linux May be something that uses reverse-video to show the differences.

A: sdiff(1)

A: I would go for vimdiff. See this tutorial.

A: I use the Midnight Commander
It can compare folders and files (check the Command menu, F9 via keyboard)
When comparing files, use Enter to navigate to the next diff, F5 to merge the selected diff from the right to the left.
Unhappily it does not support modifying the files while merging, and it also does not support merging to the right.
To install it on Linux:
sudo apt install mc

On Mac:
brew install mc


text:
Q: Can't use include? with an instance variable in a method I am trying to use 'gets' to get input and then check to see if the instance variable includes the input inside of a method but I can't get it work. Here is the code:
class Game
    attr_accessor :available_moves

    def initialize
        @available_moves = ["0","1","2","3","4","5","6","7","8"]
    end

  def play_game
    puts ("Welcome")
    while true
        puts "Player 1, choose a square"
        player1_choice = gets
        # v this is what I can't get to work v
        if @available_moves.include?(player1_choice)
            puts "yes"
            break
        else
            puts "no"
        end
    end
end
end

game1 = Game.new
game1.play_game

No matter what I try, the 'else' condition is met and "no" is printed.

A: When the user inputs text with gets they press Enter, which sends a newline. You need to remove the newline with gets.chomp:
class Game
  attr_accessor :available_moves

  def initialize
    @available_moves = ["0","1","2","3","4","5","6","7","8"]
  end

  def play_game
    puts ("Welcome")
    while true
      puts "Player 1, choose a square"
      # Note the .chomp here to remove the newline that the user inputs
      player1_choice = gets.chomp
      # v this is what I can't get to work v
      if @available_moves.include?(player1_choice)
        puts "yes"
        break
      else
        puts "no"
      end
    end
  end
end

game1 = Game.new
game1.play_game

Now you get:
game1.play_game
Welcome
Player 1, choose a square
1
yes
=> nil

See How does gets and gets.chomp in ruby work? for a more in-depth explanation.


text:
Q: Circularly double linked list C++ I want to implement a circularly double linked list. this list just includes these chars in a passed in string object
Here is my code, but I always get seg fault. i use a dummy head for this list
#ifndef MY_LIST_H
#define MY_LIST_H
#include <string>
#include <iostream>
using namespace std;
/**------   -----------------
 * dummy |->|pred|value|next|
 * ------   -----------------
 * */

struct Node
{
 char value;
 Node *next;
 Node *pred;

 Node( char value): value(value), next(0), pred(0){};
};

class MyList
{
    private:
    Node* head;
    unsigned int count; // count number of node

    public:
    // default constructor
    MyList(): count(0)
    {
        head = new Node('P');

    }

    //Constructs a list from a passed-in string object,
    MyList(const string& str): count(0)
    {
        Node *cur = head;
        if(count == 0)
        {
            head-> pred = head;
            head-> next = head;
        }
        else
        {
            for( unsigned i =0; i< str.length(); ++i)
            {
                cur->next = new Node(str.at(i));
                Node *temp = cur->next;
                temp-> pred = cur;
                ++count;
                if(count == str.length())
                {
                    cur->next->next = head;
                    head-> pred = cur-> next->pred;
                }
            }
        }
    }
    void print() const
    {
        Node *cur = head->next;
        while( cur != head)
        {
            cout << cur-> value;
            cur = cur-> next;
        }
    }

};
#endif

A: You don't seem to understand constructors very well.
Only one constructor is called when you initialize your class. You can call a constructor from another constructor if you want, but that's not by defaut: Can I call a constructor from another constructor (do constructor chaining) in C++?.
In your instance, your second constructor should probably be something like this: MyList(const string& str): MyList() { ... }
That way head wil be properly initalized, and you won't create a segfault.
Additionnally you could run your code in debug mode, in the debugger, and find out the line your code crashes. using namespace ...; in a header is also a bad practice, as you don't know where your header will be included.

A: It's hard to say exactly what's happening without see how you're using these classes but your MyList constructor overloaded on string is broken right off the bat. It sets count to 0 so you know it will always enter the if clause and never the else.
MyList(const string& str): count(0)
{
    Node *cur = head;
    if(count == 0)
    {
        head-> pred = head;
        head-> next = head;
    }
    else . . .

inside the if statement, it tries to dereference head which has never been assigned a value. You do set it in the default constructor but that one also doesn't seem to do anything else.
The purpose of a constructor is to construct a valid object from scratch. Sometimes one constructor overload might delegate to another to avoid repeated code but I'm not sure what you're trying to do here.
Assuming the second constructor was meant to actually be a helper method, well it still doesn't work because count never goes above zero (except in the else clause but you can't get there with count==0).
I'll admit I didn't look very carefully but I'm guessing that if execution this far:
cur->next->next

is not always going to be set when you try to access it. if cur->next is nullptr then your program dies.


text:
Q: Create Class From Hybrid Interface Type First of all, I'm very new to TS, and during my reading in
http://www.typescriptlang.org/Handbook I stop at trying to understand how Hybrid Types Interface works.
In the example of the TS:
interface ICounter {
    (start: number): string;
    interval: number;
    reset(): void;
}
var c: ICounter;
c(10);
c.reset();
c.interval = 5.0;

So, the problem was when I tried to write a class using this interface, the problem was the line:
(start: number): string;

First I thought that this line represents a function so tried to create:
class Test implements ICounter {
    interval: number;

    reset(): void { }

    start(start: number): string {
        return "";
    }
}

But this keep showing that "Types Test and ICounter have incompatible signatures", so what I'm missing here? I thought that interfaces should work the same way for classes and variables.

A: ICounter represents a function that has two properties—interval and reset.
This line in the interface...
(start: number): string;

...describes a way to call the function. It's shown in the example as:
c(10)

The other lines describe the function's properties—interval and reset.
c.reset();
c.interval = 5.0;

As stated in the handbook, this is used for representing JavaScript libraries that do this. So for example, the above could represent the following JavaScript code:
function counter(start) {
    alert(start);
    return "some string";
}

counter.reset = function() { alert('reset called'); };
counter.interval = 1;

In addition to all this, note that the class you described could be represented by the following interface:
interface ITest {
    interval: number;
    reset: () => void;
    start: (start: number) => string;
}

A: class implies that you will create instances via new operator. new creates object, not function, so it is impossible to implement class, which instances can called as function. You can do something like this:
interface ICounterObject {
    interval: number;
    reset(): void;
}

interface ICounter extends ICounterObject {
    (start: number): string;
    __proto__: ICounterObject;
}

class Test implements ICounterObject {
    static createCounter(): ICounter {
        var counter = <ICounter>function (start: number): string {
            return "";
        };
        counter.__proto__ = Test.prototype;
        return counter;
    }

    interval: number;

    reset(): void { }
}

Note, __proto__ is from ES6, but de-facto is supported in ES5 browsers. If you want to use function prototype members (e.g call and apply) mix prototypes:
function mixWithFunc<T extends Function>(obj: { __proto__?}, func: T) {
    var objProto = <{ constructor }>obj.__proto__;
    var objClass = <{ __mixedProto__ }>objProto.constructor;
    var proto = <typeof obj>objClass.__mixedProto__;
    if (!proto) {
        proto = {};
        proto.__proto__ = objProto;
        ['call', 'apply', 'bind'].forEach(p => proto[p] = Function.prototype[p]);
        objClass.__mixedProto__ = proto;
    }
    (<typeof obj>func).__proto__ = proto;
    Object.getOwnPropertyNames(obj).forEach(p => func[p] = obj[p]);
    return func;
}

interface ICounter extends Counter {
    (start: number): string;
}

class Counter {
    static create() {
        var self: ICounter = mixWithFunc(
            new Counter(),
            <ICounter>function (start: number) {
                return "started with interval: " + self.interval;
            });
        return self;
    }

    interval = 1000;

    reset() { this.interval = 0; }
}

Of course you can just add members to each instance of your function instead of prototyping.


text:
Q: How to get single record if the multiple records are on single ID? In this image, 5 record are with id 80, but when i fetch them they all are coming but i want to show just one record only.

My rest code is below here
$data['query7'] = $this->ORB_Model->get_skilldash();

public function get_skilldash()
    {
        $this->load->database('orb');
        //$this->db->distinct('master_id');
        $query = $this->db->get_where('skills_tb', array('master_id' => $this->session->userdata('master_id')));
        return $query->result();
    }

A: Use $query->row() instead of $query->result();
public function get_skilldash()
{
    $this->load->database('orb');
    $master_id = $this->session->userdata('master_id');
    $query = $this->db->get_where('skills_tb', array('master_id' =>$master_id));
    return $query->row();
}

If you want a specific row returned you can submit the row number as a digit in the first parameter:
$row = $query->row(3);

Or Simply use it with  $this->db->distinct(); do like this:
$this->load->database('orb');
$this->db->distinct();
$master_id = $this->session->userdata('master_id');
$query = $this->db->get_where('skills_tb', array('master_id' => $master_id));
return $query->row();

for more : https://www.codeigniter.com/user_guide/database/results.html#result-rows


text:
Q: sapui5- How to change default action on panel icon click event? I am using sapui5 panel, and I allow to expandable that it will show default icon on toolbar ">", when I click on it, it will togglecollapse, but I want to add some action on it.
Here is the panel and there is one icon at the end.
Any idea to override function, customize function, or add some action on that icon when we click on it?
My purpose is, I want to add warning message before panel is collapsed, if I click "yes" to confirm, it can collapse, "No" it still the same, do nothing.

A: Have you tried attachExpand ?
https://sapui5.hana.ondemand.com/docs/api/symbols/sap.m.Panel.html#attachExpand
I'm still new to this ui5 :p
Here we go
        var panel = new sap.m.Panel("panel-1", {
            headerText:"Test Panel",
            expandable: true
        });
        panel.setExpanded = function (bExpanded) {
            if (bExpanded === this.getExpanded()) {
                return this;
            }
            //may need to reset this later
            this.setProperty("expanded", bExpanded, true);
            if (!this.getExpandable()) {
                return this;
            }

            //add custom logic here
            if(bExpanded){

            }
            //custom logic

            this._getIcon().$().attr("aria-expanded", this.getExpanded());
            this._toggleExpandCollapse();
            this._toggleCssClasses();

            this.fireExpand({ expand : bExpanded });
            return this;
        };


text:
Q: how to create array object in loop without extra key? I am creating a array object without loop like below :
var data = [];
var obj = {};
obj["key1"] = 'val 1';
obj["key2"] = 'val 2';
data.push(obj);

The above code produce me Array[Object], but when I am trying to create this in a loop like below:
var data = [];
for (var i = 0; i < len; i++) {
    var obj = {};
    obj["key1"] = 'val 1';
    obj["key2"] = 'val 2';
    data.push(obj);
}

It produce me Array[], in that 2nd array there is an extra index. So how can I get the array like below:
Array[Object,Object,Object]

A: If you want:-Array[Object,Object,Object] then your code is working perfectly fine
See example:-

var data = [];

var len = 3;
for (var i = 0; i < len; i++) {
    var obj = {}; // put outside
    obj["key1"] = 'val 1';
    obj["key2"] = 'val 2';
    data.push(obj);
}
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note:- I think problem is there with len variable because of which loop executed one more time and you get an extra index?
Check and try something like len = len-1; and then use it in loop

A: Your code works fine, asuming var len is 3

var data = [];
for (var i = 0; i < 3; i++) {
    var obj = {};
    obj["key1"] = 'val 1';
    obj["key2"] = 'val 2';
    data.push(obj);
}

Give back an array with 3 objects inside. Each object has 2 values.
[Object, Object, Object]


text:
Q: How to insert string to each token of a list of strings? Lets assume I have the following list:
l = ['the quick fox', 'the', 'the quick']

I would like to transform each element of the list into a url as follows:
['the', 'quick','fox', 'the','the', 'quick']

So far, I tried the following:
list_words = ['{}'.format(a, a) for a in x[0].split(' ')]

The problem is that the above list-comprehension just does the work for the first element of the list:
['the',
 'quick',
 'fox']

I also tried with a map but, it didn't work:
[map('{}'.format(a,a),x) for a in x[0].split(', ')]

Any idea of how to create such links from the tokens of a list of sentences?

A: You were close, you limited your comprehension to the contents of x[0].split, i.e you were missing one for loop through the elements of l:
list_words = ['{}'.format(a,a) for x in l for a in x.split()]

this works because "string".split() yields a one element list.
This can look way prettier if you define the format string outside the comprehension and use a positional index {0} informing format of the argument (so you don't need to do format(a, a)):
fs = '{0}'
list_words = [fs.format(a) for x in l for a in x.split()]

With map you can get an ugly little duckling too if you like:
list(map(fs.format, sum(map(str.split, l),[])))

Here we sum(it, []) to flatten the list of lists map with split produces and then map fs.format to the corresponding flattened list. Results are the same:
['the',
 'quick',
 'fox',
 'the',
 'the',
 'quick']

Go with the comprehension, obviously.

A: list_words = ['{}'.format(a,a) for item in l for a in item.split(' ')]

A: In one-liner:
list_words = ['{}'.format(a,a) for a in [i for sub in [i.split() for i in l] for i in sub]]

In steps
You can split the list:
l = [i.split() for i in l]

and then flatten it:
l = [i for sub in l for i in sub]

result:
>>> l
['the', 'quick', 'fox', 'the', 'the', 'quick']

Then:
list_words = ['{}'.format(a,a) for a in l]

You will finally take:
>>> list_words
['the', 'quick', 'fox', 'the', 'the', 'quick']


text:
Q: How to compare content of xhtml and pdf file? Latex file is the source, from which pdf and xhtml file will be created. Now I need to compare the content of both pdf and xhtml file. Just to make sure whether the PDF file contents exist in xhtml file too. how to do it?
If we want to compare two pdf files, we can use diffpdf , pdftk etc. But how about comparing content between xhtml and pdf? Or Is there any alternative way to do it?
Additional Note:
OS-linux
Language known-PHP


text:
Q: Force tomcat not to invalidate session on shutdown My project uses custom session invalidation mechanism. It requires to send notification with invalidation cause, for example - if invalidation happends by user request - invalidation cause is USER_REQUEST, if shutdown of the server - then the cause is SHUTDOWN.
All working well besides shutdown case - tomcat itself invalidates all the session(at least StandardManager does).
As far as I know - I can create my own Manager, which does'nt invalidate sessions at all:
public class HttpSessionManager extends StandardManager {

    @Override
    protected synchronized void stopInternal() throws LifecycleException {
        setState(LifecycleState.STOPPING);
        if (sessionIdGenerator instanceof Lifecycle) {
            ((Lifecycle) sessionIdGenerator).stop();
        }
    }
}

This class should be placed in some jar file and placed in tomcat/lib folder.
In fact, that solution requires to distribute additional library for tomcat together with the main solution, which is not good(delivery process getting complicated)
There should be another way to do that or my solution could be improved somehow.

A: After a long and deep googling this issue - I can say there is no other way to do such thing.


text:
Q: MongoDb (Mongoose) query docuemnt comparing two dates using $elemMatch and $and In my database, I have a table with an object storing dates like this. I have a beginning date and hour (debut in french) and a ending date and hour (fin in french).
    "disposnibilites" :
     [
...
      {
            "debut": {
                "$date": "2016-02-15T14:00:00.282Z"
            },
            "fin": {
                "$date": "2016-02-15T19:00:00.282Z"
            },
            "_id": {
                "$oid": "56d48f0bf94a4a642f4d2fc0"
            }
        },
...
       ]

My goal is to find all the document where the beginning time supplied is before the one in the DB and the end time is after the one in the DB. In Mongoose I run this query :
    { 'disponibilites' :
      {  $elemMatch :  {
          debut : { $lt : new Date("2016-02-15T15:00:00.282Z")},
          fin : { $gt : new Date("2016-02-15T18:00:00.282Z") }
    }
} };

This send back all the documents available. Mongoose logs gives this informations :
Mongoose: document.find({ disponibilites: { '$elemMatch': { debut: { '$lt': new Date("Mon, 15 Feb 2016 19:00:00 GMT") }, fin: { '$gt': new Date("Mon, 15 Feb 2016 20:00:00 GMT") } } } }) { fields: undefined }

Now if I change the day to the 17th (where there are no entries in the DB for that day), it gives the same result :
    { 'disponibilites' :
      {  $elemMatch :  {
          debut : { $lt : new Date("2016-02-17T15:00:00.282Z")},
          fin : { $gt : new Date("2016-02-17T18:00:00.282Z") }
      }
    }

Mongoose logs data :
Mongoose: document.find({ disponibilites: { '$elemMatch': { debut: { '$lt': new Date("Mon, 17 Feb 2016 19:00:00 GMT") }, fin: { '$gt': new Date("Mon, 17 Feb 2016 20:00:00 GMT") } } } }) { fields: undefined }

Eventually I will need to have something more complex like this :
{ 'disponibilites' :
   { $and : [
    {  $elemMatch :  {
        debut : { $lt : new Date("2016-02-17T15:00:00.282Z")},
        fin : { $gt : new Date("2016-02-17T18:00:00.282Z") }
    },
    {  $elemMatch :  {
        debut : { $lt : new Date("2016-02-18T15:00:00.282Z")},
        fin : { $gt : new Date("2016-02-18T18:00:00.282Z") }
    }
   ]
   }
}

For now I want to understand why MongoDb can't compare dates properly ?


text:
Q: How to keep writing in a FIFO even if there's no readers There's a service that pipes it's output to a named pipe, which I create with mkfifo name.
The service pauses if there's no reader in pipe. How to make it to keep piping the data even if there's no reader?
The reader(s) may (or may not) use the pipe later.
Edit: No buffer is needed. Readers will start reading from where they use the pipe. Data before that is lost. And that's OK. Consider it's a video stream.

A: tail -F namedpipe

might be of interest to you in this case … It should keep the pipe open and writable for your service constantly.
You can as well, if you want, discard its output to minimize used resources by redirecting it to e.g. /dev/null like so:
tail -F namedpipe > /dev/null


text:
Q: Ignoring the last value in a groupby() clause I was wondering if this was possible. I currently have a line of code that accumulatively adds all the values in my Total Time (s) column, grouped by the value contained in the column CycleNumber. Into a list called cycle_times. I'm achieving this right now as follows:
cycle_times = raw_data['Total Time (s)'].diff().fillna(0).groupby(interim_output['CycleNumber']).cumsum()

This provides an output at the end of the group by, like this:
print(interim_output['CycleNumber'][328:334])

328    1
329    1
330    1
331    2
332    2
333    2

print(cycle_times[328:334])

328    65.643
329    65.673
330    65.994
331    66.008
332       0.0
333     0.251

Which is almost what I want. However, as you can see, the first instance of number 2 in CycleNumber is adding to the total (the short time it takes for the machine to reset in its reading). Is there anyway of using groupBy, and telling it to ignore this value, or forcing it to reset at the change of CycleNumber? If I had it this way, my desired output would be this:
print(cycle_times[328:334])

328    65.643
329    65.673
330    65.994
331       0.0
332       0.0
333     0.251

Any help would be most appreciated!

A: I think there is one .groupby(df['CycleNumber']) missing to get what you want, see "cycle_times_V1". However, the resulting code is then very unreadable. I added a version which gives the same output but is much more explicit, see "cycle_times_V2"
import numpy as np
import pandas as pd

df = pd.DataFrame({"CycleNumber": [1, 1, 1, 2, 2, 2],
                   "Total Time (s)": list(range(6))})

df["cycle_times_before"]  = df['Total Time (s)'].diff().fillna(0).groupby(df['CycleNumber']).cumsum()
df["cycle_times_V1"] = df['Total Time (s)'].groupby(df['CycleNumber']).diff().fillna(0).groupby(df['CycleNumber']).cumsum()

# this gives the same, but is much more explicit
df["cycleStartTime"] = np.nan
for groupItem, df_group in df.groupby(by="CycleNumber"):
    df.loc[df_group.index,"cycleStartTime"] = df_group["Total Time (s)"].min()
df["cycle_times_V2"] = df["Total Time (s)"] - df["cycleStartTime"]


text:
Q: How do I add a List property to my greendao generator? I'm trying to generate my models using the greendao generator and I'm not quite sure how to add a property that accepts a List<String>
I know how to add a List<Model> using the addToMany but what if I need to store an ArrayList inside one of my models?
Something like this:
Entity tags = schema.addEntity("Tags");
    tags.implementsInterface("android.os.Parcelable");
    tags.addLongProperty("tagId").primaryKey().autoincrement();
    tags.addLongProperty("date");
    tags.addArrayStringProperty("array"); // something like this

I was thinking of creating another entity to store all the values of the array, and doing the ToMany like this
Entity myArray = schema.addEntity("MyArray");
    myArray.implementsInterface("android.os.Parcelable");
    myArray.addLongProperty("myArrayId").primaryKey().autoincrement();
    myArray.addLongProperty("id").notNull().getProperty();
    Property tagId = myArray.addLongProperty("tagId").getProperty();

ToMany tagToMyArray = tag.addToMany(myArray, tagId);
tagToMyArray.setName("tags");
myArray.addToOne(tag, tagId);

A: You can serialise that ArrayList and then save as a string property in greenDAO table.
String arrayString = new Gson().toJson(yourArrayList);

and then retrieve it back like this
Type listType = new TypeToken<ArrayList<String>>(){}.getType();
List<String> arrayList = new Gson().fromJson(stringFromDb, listType)

A: Another way.You can use @convert annotation.
@Entity
public class User {
@Id
private Long id;

@Convert(converter = RoleConverter.class, columnType = Integer.class)
private Role role;

public enum Role {
    DEFAULT(0), AUTHOR(1), ADMIN(2);

    final int id;

    Role(int id) {
        this.id = id;
    }
}

public static class RoleConverter implements PropertyConverter<Role, Integer> {
    @Override
    public Role convertToEntityProperty(Integer databaseValue) {
        if (databaseValue == null) {
            return null;
        }
        for (Role role : Role.values()) {
            if (role.id == databaseValue) {
                return role;
            }
        }
        return Role.DEFAULT;
    }

    @Override
    public Integer convertToDatabaseValue(Role entityProperty) {
        return entityProperty == null ? null : entityProperty.id;
    }
}
}


text:
Q: Show a new GIF on each page visit or page reload I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
  var apiKey = '';
  var url = '';
  var data;
  // console.log(position);
  $.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {

    $('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
    $('.js-current-item2').html(data.currently.summary);

    gif(data.currently.icon)
    city(position.coords.latitude + "," + position.coords.longitude)

  });
}

And here is the function for pulling images from GIPHY
function gif(status) {
  var apiKey = '';
  var url = 'http://api.giphy.com/v1/gifs/search?q=';
  var query = status;
  $.getJSON(url + query + apiKey, function(data) {
    $('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
  });
}

A: In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');

to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');


text:
Q: Remove quotes "..." from all columns with AWK I've currently been trying to create an awk script that will take my .csv and convert it into a .tsv.
I have managed to achieve this with the below script:
$ awk 'BEGIN { FS=","; OFS="\t" } {$1=$1; print}' file.csv > file.tsv

Example csv data
"visitor_date","country","browser","browser_version","id1","id2","id3","id4","true or false column"
"05/10/2019 00:55","United States","App","","692467","2163702","4117512086","format","0"
"05/10/2019 00:56","United States","SamsungBrowser","8","692467","2163702","4117512083","format","1"
"05/10/2019 01:08","United States","safari","11","692467","2163704","4117511299","format","1"
"05/10/2019 03:25","United States","SamsungBrowser","8","692467","2163704","4117511299","format",""
"05/10/2019 07:50","United States","chrome","58","692467","2163704","4117511299","format",""
"05/10/2019 09:18","United States","internet explorer","11","692467","2163702","4117512086","format","0"

However I've found that my data file tends to have all of the columns defined as a sting with the "", even when we have things that might be considered an integer.
My initial test was to try and remove the {","} from everything and then define things as strings on certain columns but I get an error when I try to quote it.
$ awk 'BEGIN { FS="",""; OFS="\t" } {$1=$1; print}' file.csv > file.tsv

Error
awk: cmd. line:1: BEGIN { FS="",""; OFS="\t" } {$1=$1; print}
awk: cmd. line:1:              ^ syntax error

From the research I've done online all I seem to find is how you can change a string value in a cell to a different integer value. Is there a way that I can transform certain columns (not cells) to be treated as "integers" and "dates" instead of all as strings? Is what I'm trying to do with my initial test even the right direction I should be taking or is there a different way with AWK to decide what my columns are?
Desired tsv Output
"visitor_date"  "country    browser"    "browser_version"   "client_transaction_id" "id1"   "id2"   "id3"   "id4"   "true or false column"
05/10/2019 00:55    "United States" "App"       null    692467  "2163702"   4117512086  "format"    0
05/10/2019 00:56    "United States" "SamsungBrowser"    8   "null"  692467  2163702 4117512083  "format"    1
05/10/2019 01:08    "United States" "safari"    11  null    "692467"    2163704 4117511299  "format"    1
05/10/2019 03:25    "United States" "SamsungBrowser"    8   "null"  692467  2163704 4117511299  "format"
05/10/2019 07:50    "United States" "chrome"    58  null    "692467"    2163704 4117511299  "format"
05/10/2019 09:18    "United States" "internet explorer" 11  "null"  692467  2163702 4117512086  "format"    0

Note: The "visitor_date" column would need to be a "date" format.
Apologies if this is something super obvious or basic. I've currently only got 2 days experience using an ubuntu interface on windows 10 and AWK so there is a lot I'm trying to take in.

A: If there are no double quotes you want to preserve, simply
awk 'BEGIN { FS=","; OFS="\t" } { gsub("\"", "") } { $1=$1 } 1' file.csv >file.tsv

Incidentally, this also demonstrates how to quote a literal double-quote character inside a double-quoted string; backslash-escape it.
If you only want to remove double quotes around some columns, you can limit the scope of the gsub. For example,
... { gsub("\"", "", $1); gsub("\"", "", $3) } 1

to only manipulate columns 1 and 3. Then you can drop the { $1 = $1 } because we are forcing Awk to recalculate its columns anyway (so the FS gets replaced with OFS).
To not manipulate the first line (which commonly contains the header, not data), add a condition:
... NR>1 { gsub(...) }1

The "replace everywhere" can be expressed quite succinctly in sed, though it tends to be more of a write-only language.
sed -e 's/,/\t/g' -e 's/"//g' file.csv >file.tsv

Not all sed dialects interpret \t as a literal tab, and some are even allergic to multiple -e options; but this should work fine on Ubuntu and generally Linux (other than possibly Busybox and other similar attempts to relive the constraints of the jolly 1970s).

A: It's not awk, but it's very easy using Miller (https://github.com/johnkerl/miller). Running
mlr --c2t cat ./input.csv >./output.csv

You will have
visitor_date    country browser browser_version id1 id2 id3 id4 true or false column
05/10/2019 00:55    United States   App     692467  2163702 4117512086  format  0
05/10/2019 00:56    United States   SamsungBrowser  8   692467  2163702 4117512083  format  1
05/10/2019 01:08    United States   safari  11  692467  2163704 4117511299  format  1
05/10/2019 03:25    United States   SamsungBrowser  8   692467  2163704 4117511299  format
05/10/2019 07:50    United States   chrome  58  692467  2163704 4117511299  format
05/10/2019 09:18    United States   internet explorer   11  692467  2163702 4117512086  format  0


text:
Q: (AsyncTask) Open a dialog when catch (Jsoup) I want the dialog to open when "AsyncTask" is "catch". I tried to call Dialogue into a "catch". But the program is crashing. How do I open a dialog when there is a catch?
My code:
public class test extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                Document doc = (Document) Jsoup.connect("(warn: here my web)").get();
                test = doc.text();

            } catch (Exception e)
//Here problem dialog open. App crash
OpenDialog();
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            Toast.makeText(MainActivity.this, test, Toast.LENGTH_LONG).show();
        }
    }

logcat error (red):
2021-12-17 07:22:10.953 17530-17564/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process, PID: 17530
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$4.done(AsyncTask.java:415)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:227)
        at android.os.Handler.<init>(Handler.java:129)
        at android.view.ViewRootImpl$ViewRootHandler.<init>(ViewRootImpl.java:5041)
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:5369)
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:763)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:399)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:111)
        at android.app.Dialog.show(Dialog.java:342)
        at Main.qaytaDialog(Main.java:130)
        at Main.access$000(Main.java:24)
        at Main$dooit.doInBackground(Main.java:95)
        at Main$dooit.doInBackground(Main.java:83)
        at android.os.AsyncTask$3.call(AsyncTask.java:394)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)

A: A bit broad but here are some tips. Displaying dialogs is foreground thing (runs on main or UI thread) so it can not be done in background method of async task (it runs on background Thread).It is only allowed from methods such as onPostExecute(), onPublishProgress().

 Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()

Please refer to this link for details
Here is a quick code snippet for your reference
    public class MyAsync extends AsyncTask<Void, Void, Void> {
    Boolean isCatched=false;

    @Override
    protected Void doInBackground(Void... voids) {

        try {
            if (!isCatched)
                throw new Exception();
            Log.i("Test", "doInBackground: ");
        } catch (Exception e){
        //Here problem dialog open. App crash
            isCatched=true;
        e.printStackTrace();
    }

        return null;

}

@Override
protected void onPostExecute(Void unused) {
    super.onPostExecute(unused);
    if (isCatched)
        OpenDialog();
    Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_LONG).show();
}

}


text:
Q: Merge aggregate group rows in Kendo UI Grid I am showing aggregate data in Kendo UI Grid. I show a grid with grouped data. However i need to add a new column which is an aggregate of another column rows of a particular group (as shown below).

Column4 shows aggregate of column3 values.
I tried Kendo UI documentation however this seems to be pretty specific and could not find anything. Do I need custom implementation for this or does Kendo UI grid have this feature?

A: Aggregate values can be accessed declaratively in the footerTemplate and groupFooterTemplate, or programmatically from the data items. The following answer demonstrates all these options:
https://stackoverflow.com/a/40139348/3086237
However, the Grid does not provide means to place aggregate values in regular data rows declaratively. Generally, this doesn't make sense, as the same value will appear in all rows from a specific group. If you really need an aggregate value inside a data row, you will have to obtain it programmatically in dataBound and then inject it in the desired table cell via DOM manipulation.


text:
Q: C++11 - templates, friends, decltype & access modifiers What's up guys,
I am trying to overload the addition operator for my math vector class.
My (seemingly logically correct) simplified code is:
template<typename T>
class Vector2
{
private:
    T       m_data[2];

    template<typename U>
    friend auto operator+(Vector2<T> a, Vector2<U> b) -> Vector2<decltype(a.m_data[0] + b.m_data[0])>
    {
        Vector2<decltype(a.m_data[0] + b.m_data[0])> ret(   a.m_data[0] + b.m_data[0],
                                                            a.m_data[1] + b.m_data[1]   );

        return ret;
    }

public:
    inline Vector2(T x, T y)
    {
        m_data[0] = x;
        m_data[1] = y;
    }
};

int main()
{
    Vector2<float>  v1(0.5f, 0.5f);
    Vector2<float>  v2(1, 2);

    v2 + v1; // Line 29

    return 0;
}

However, GCC 4.6.1 gave me this:
W:\projects\Awesome\BetterStuff\main.cpp||In function 'Vector2<decltype ((a.m_data[0] + b.m_data[0]))> operator+(Vector2<T>, Vector2<U>) [with U = float; T = float; decltype ((a.m_data[0] + b.m_data[0])) = float]':|
W:\projects\Awesome\BetterStuff\main.cpp|5|error: 'float Vector2<float>::m_data [2]' is private|
W:\projects\Awesome\BetterStuff\main.cpp|29|error: within this context|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|

And if I changed the second vector to an int vector, it would give me more (similar) errors.
The closest I came to figuring this thing out was finding this interesting page: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48884
But sadly, I couldn't use it for solving my own problem.
I tried GCC 4.6.2 and 4.7.0 but my code didn't compile either.
Changing "private" to "public" indeed solves my problem, but obviously my intention is not to expose m_data;
I just want to define an addition operator that its return type is determined by the template parameters, which from my understanding is, a compile time thing - for each instantiation of the template function, the compiler automatically figures out the return type based on the decltype() there. I mean, in which way main() is trying to access the contents of m_data for one of these vectors?
This whole thing is confusing me, any help would be greatly appreciated.
OK thanks

A: Well, GCC is right... The problem was not that Vector2(float) was trying to access Vector(int)'s private members, but that operator+ (which is only a friend of Vector2(float)) was trying to access Vector2(int)'s private members. So the updated code is:
template<typename T>
class Vector2
{
    template<typename U>
    friend class Vector2;

private:
    T       m_data[2];

    template<typename T1, typename U>
    friend auto operator+(Vector2<T1> a, Vector2<U> b) -> Vector2<decltype(a.m_data[0] + b.m_data[0])>;

public:
    inline Vector2(T x, T y)
    {
        m_data[0] = x;
        m_data[1] = y;
    }

    inline Vector2<T>& operator=(const Vector2<T>& vec)
    {
        m_data[0] = vec.m_data[0];
        m_data[1] = vec.m_data[1];
    }
};

template<typename T, typename U>
auto operator+(Vector2<T> a, Vector2<U> b) -> Vector2<decltype(a.m_data[0] + b.m_data[0])>
{
    Vector2<decltype(T() + U())> ret(   a.m_data[0] + b.m_data[0],
                                        a.m_data[1] + b.m_data[1]   );

    return ret;
}

int main()
{
    Vector2<float>  v1(0.5f, 0.5f);
    Vector2<int>    v2(1, 2);

    //Vector2<int>  a = v2 + v1; // Doesn't work
    Vector2<float>  b = v2 + v1; // Works

    return 0;
}

A: The problem is that Vector2<T> and Vector2<U> are different completely unrelated classes if T != U. What you are trying to do is the same as having a class A access the private members of an unrelated class B.
Provide proper accessors for your Vector2 (perhaps subscript operator), and implement your operators using such public interfaces.

A: Put simply: You cannot access private members of another class.  Vector2<float> and Vector2<int> are different classes.  You can fix by adding this to your class
template<typename T> friend class Vector2;

Which will friend all types of Vector2.  Then you can access the privates of another Vector2.

A: Don't use a private member in decltype as noted above.
Also, I made the addition operator public.  I don't think that's unreasonable.
I also added coodinate accessors.
This works:
template<typename T>
class Vector2
{
private:
    T       m_data[2];
public:
    template<typename U>
    friend auto operator+(Vector2<T> a, Vector2<U> b) -> Vector2<decltype(T() + U())>
    {
        Vector2<decltype(T() + U())> ret( a[0] + b[0],
                                          a[1] + b[1] );

        return ret;
    }
    inline Vector2(T x, T y)
    {
        m_data[0] = x;
        m_data[1] = y;
    }
    inline T operator[](int c) const { return m_data[c]; }
};

int main()
{
    Vector2<float>  v1(0.5f, 0.5f);
    Vector2<int>  v2(1, 2);

    v2 + v1; // Line 29

    return 0;
}

assuming T and U have default ctors.


text:
Q: Python code to return a phone number in numbers , after giving inputs in words Yesterday, I was doing one problem where I have to  complete a function which can convert a phone number in numbers after given input in words, I have used s.replace() to do that, and modifier also. Since this question was there in hackerrank problem I cant provide complete code, since test is over now and the page is no longer available. How can I use those modifiers as well,
like "two three four double two triple 3" will print 23422333?
def getPhoneNumber(s):
    s.replace("Zero" "0")
    s.replace("one" "1")
    ...

modifier = {
    "double": 2,
    "triple" : 3,
}

A: d = {'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7','eight':'8','nine':'9'}
mod = {'double':2,'triple':3}

num_word = input('Enter Number In Words').split(' ')

number = ''
m = 1
for a in num_word:
    try:
        m = mod[a.lower()]
        continue
    except KeyError:
        pass
    try:
        number+=d[a.lower()]*m
        m = 1
    except KeyError:
        number+=a.lower()*m
        m = 1
print(number)

OUTPUT
IN: double two
OUT: 22

IN: two three four double two triple 3
OUT: 23422333

A: Try this,
def getPhoneNumber(number):
  to_replace = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}
  modifiers = {"double":2, "triple":3}
  words = list(map(str.lower, number.split()))
  output = ""
  skip = None

  for index, word in enumerate(words):
    if index == skip:
      continue

    if word in modifiers:
      skip = index + 1
      try:
        output += modifiers[word] * to_replace[words[skip]]
      except:
        pass

    else:
      output += to_replace[word]

  return output

getPhoneNumber("Double One Triple Two Five")

Output -
112225

A: numbers = {'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7','eight':'8','nine':'9'}
multipliers = {'double':2,'triple':3}

def solve(sentence):
    results = []
    sentence = sentence.lower().split()
    repeat = 1
    for word in sentence:
        if word in multipliers:
            repeat = multipliers[word]
        else:
            if word in numbers:
                word = numbers[word]
            results.append(word * repeat)
            repeat = 1
    return ''.join(results)

A: I'll throw this out there as a variation on other themes:
d = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
     'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'}
mod = {'double': 2, 'triple': 3}

num_word = input('Enter Number In Words: ')

number = []
m = None
for word in map(str.lower, num_word.split()):
    if m:
        number.extend(d.get(word, '') * m)
        m = None
    else:
        if not (m := mod.get(word)):
            number.append(d.get(word))

print(''.join(filter(bool, number)))


text:
Q: Appending a div containing an image in a function Everything comes just to the following single line of code, which I probably mess up somewhere and after an hour with something of searching for error I still don't find it, so that's why I'm turning up to you.
$("red").append("

");

When .append(); is without an argument everything with the syntax is good. After I put what you see in, pops up a message "Uncaught SyntaxError: missing ) after argument list" which I can't find. Please help me to find the mysterious bracket or to fix my syntax or to write this in another way if you think this one won't ever work for me. Sorry for this dump question, I searched a lot for this but it was nowhere said about implementing two or more html tags within an append method.
P.S. The idea is to load a container holding an image by generated elsewhere coordinates.

A: $("red").append("

");

All the " should be escaped when in a string with " otherwise JS will assume the string has ended

A: Try this one
$("red").append("

");


text:
Q: Volume of cut cone I want to find the volume of the cut-cone in the picture with respect to $R, r$ and $h$. Can you check my work
The volume of the cut-cone is is the volume of the full cone minus the volume of the small cone which gone so
$V = \dfrac{\pi}{3} R^2 x - \dfrac{\pi}{3} r^2 (x-h) $
But from the similarity of the triangles we get $\dfrac{x}{R} = \dfrac{x-h}{r} \rightarrow x = \dfrac{hR}{R-r}$
$V = \dfrac{\pi}{3} \left(x(R^2 - r^2) + rh \right)=\dfrac{\pi}{3}\left(\dfrac{Rh(R^2-r^2)}{R-r} +r^2h \right)= \dfrac{\pi h}{3}(R(R+r)+ r^2) $

A: Man what's the question the cone is more like a frustum and volume of small cone =volume of original cone - volume of frustum $= 1/3πR^2x-1/3π(R^2+r^2+rR)(x-h)$. Here $h$ is height of frustum.


text:
Q: How can I determine if my sound card is working or not? My system (Windows XP) does not have any sound!
I feel that my sound card is broken, but I'm not sure.
How can I determine whether my sound card is healthy or broken?

A: Simplest way I can think of is booting from an ubuntu live cd and seeing if it works. That eliminates any software problems you may have under Windows.


text:
Q: Loop through a table in Oracle PL/SQL I have done SQL queries but have not done any procedure writing that uses loops so I am at a lost here. I'm using Oracle SQL Developer. Can be done in SQL or PL/SQL
I have a table that resemble this:
Person_ID Score Name  Game_ID
1         10    jack  1
1         20    jack  2
2         15    carl  1
2         3     carl  3
4         17    steve 1

How can I loop through this table so that I can grab a players total score for all games played. Result would be like this:
Person_ID Score Name
1         30    jack
2         18    carl
4         17    steve

Also extra credit what If i wanted to just grab say games 1 2?

EDIT: Sorry for not being clear but I do need to do this with a loop even though it can be done without it.

A: Solution after post edition
This procedure list scores for given game_id. If you omit parameter all games will be summed:
create or replace procedure player_scores(i_game_id number default null) as
begin
  for o in (select person_id, name, sum(score) score
      from games where game_id = nvl(i_game_id, game_id)
      group by person_id, name)
  loop
    dbms_output.put_line(o.person_id||' '||o.name||' '||o.score);
  end loop;
end player_scores;

Previous solution:
You don't need procedure for that, just simple query:
select person_id, name, sum(score)
  from your_table
  where game_id in (1, 2)
  group by person_id, name


text:
Q: Using Harvard Style Hi I'm using the Havard Style and want to cite a journal, not the author.
I'm using natbib and har2nat (because hyperlink didn't work with harvard.sty, and there are some problems with german citation, too).
I tried the \DeclareCiteCommand, but it didn't work because biblatex is missing.
My goal is to get something like "Guardian (2009)" in contrast to the author and the year.
Hope anyone can help me :)
EDIT 2: Thanks to the advice in the comments, I would like to have a cite like "Guardian, Author (2008)" or "Author, Guardian (2008)".
EDIT with minimal working example (the dcugerman.bst I got from this source)
\documentclass{article}
       \usepackage{hyperref}

        \usepackage{natbib}
        \setcitestyle{aysep={,}} % needed to fully emulate harvard's "dcu" citation style
        \usepackage{har2nat}
        \providecommand\harvardand{}
        \renewcommand{\harvardand}{und}

        \usepackage{filecontents}

        \begin{filecontents}{\jobname.bib}
            @article{Gua2009,
              author = {Author, A.},
              year = {2008},
              title = {Some relevant article},
              journal = {Guardian}
            }
        \end{filecontents}

\begin{document}

    This is a source from the Guardian\cite{Gua2009}

    \bibliographystyle{dcugerman}
    \bibliography{\jobname}

\end{document}

The Result is:

This is a source from the Guardian(Author, 2008)
References Author, A. (2008). Some relevant article, Guardian .

But I want someting like this:

This is a source from the Guardian(Guardian, 2008)
References Author, A. (2008). Some relevant article, Guardian .

EDIT 3 // MY SOLUTION
I just changed the author and journal entry in my bib file. (Thanks to Mico for the advice!)
If I have two newspaper articles from the same year, there will be a letter after the year so you can find the source in the bibliography.

A: You could define an "alias" for a certain entry and then cite it via \citetalias and \citepalias. For instance:

\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
    @article{Gua2009,
      author = {Author, A.},
      year = {2009},
      title = {Some relevant article},
      journal = {Guardian},
      volume  = "",
    }
\end{filecontents*}

\usepackage{natbib,har2nat}
\setcitestyle{aysep={,}}
\providecommand\harvardand{}
\renewcommand\harvardand{und}
\defcitealias{Gua2009}{Guardian, 2009} % define the alias to suit your needs
\bibliographystyle{dcugerman}

\usepackage[colorlinks=true,citecolor=blue]{hyperref}

\begin{document}
\citetalias{Gua2009}, \citepalias{Gua2009}

\bibliography{\jobname}
\end{document}


text:
Q: Pandas approach to apply functions across multiple columns with same index? I have a basic Pandas DataFrame, something like:
In [2]: print(pd
                .DataFrame({
                            'a': pd.Index([1,2,3, 1,2,3]),
                            'b': pd.Categorical(['can','foo','bar', 'can','foo','bar']),
                            'c': pd.Series([7,8,9, 10,5,60]),
                            'd': pd.Series([7,8,9, 20,40,5])
                          })
                          .set_index('a')
                          .to_markdown())

|   a | b   |   c |   d |
|----:|:----|----:|----:|
|   1 | can |   7 |   7 |
|   2 | foo |   8 |   8 |
|   3 | bar |   9 |   9 |
|   1 | can |  10 |  20 |
|   2 | foo |   5 |  40 |
|   3 | bar |  60 |   5 |

How do I do math per category per index? - To exemplify with one, say at index 2 I want to multiply can.c by foo.d and divide by can.d plus bar.c? - Now at the DataFrame level, I want a new column called result stored per index, with the result to this?


text:
Q: Как добавить панель ввода текста во фрейм вместе с JTable? В данный момент изучаю SQL, JDBC, Swing.
Как тестовый проект для отработки навыков хочу сделать простой Регистратор в базу данных. Как это должно выглядеть нарисовал в фотошопе внизу.
Возникла вопрос в том как добавить панель регистрации справа от самой таблицы JTable.
Не понимаю куда смотреть в JFrame, JPanel, SWT?
PS: Да, почти весь код в мейне, но это лишь на время изучения.
PSS: Это мой первый вопрос, если не "попал" в прочитанные мною правила вопросов - не серчайте.
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import java.awt.*;

import java.sql.*;

public class start {
    //Creating
    private static Object[][] databaseInfo = null;

    private static Object[] columns = {"Login", "Email", "Password", "Phone Number", "First Name", "Last Name", "Street", "City", "Day of Birth", "Sex", "AccountID"};

    private static DefaultTableModel defaultTableModel = new DefaultTableModel(databaseInfo, columns){
        public Class getColumnClass(int column){
            Class returnValue;
            if((column >= 0) && (column < getColumnCount())){
                returnValue = getValueAt(0, column).getClass();
            }
            else {
                returnValue = Object.class;
            }
            return returnValue;
        }
    };

    public static void main(String[] arg) {
        JFrame frame = new JFrame();

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Connection conn;

        ResultSet rows;

        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "ttipopu");

            Statement sqlState = conn.createStatement();

            String selectStuff = "SELECT * FROM accounts";

            rows = sqlState.executeQuery(selectStuff);

            Object[] tempRow;

            while (rows.next()) {
                tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3), rows.getString(4), rows.getString(5), rows.getString(6), rows.getString(7), rows.getString(8), rows.getDate(9), rows.getString(10), rows.getInt(11)};
                defaultTableModel.addRow(tempRow);
            }
        }

        catch (SQLException sqlEx){
            System.out.printf(sqlEx.getMessage());
        }
        catch (ClassNotFoundException cnfEx){
            System.out.println(cnfEx.getMessage());
        }

        JTable table = new JTable(defaultTableModel);

        table.setRowHeight(table.getRowHeight() + 10);

        table.setFont(new Font("PT Sans", Font.PLAIN, 20));

        table.setAutoCreateRowSorter(true);

        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        TableColumn col1 = table.getColumnModel().getColumn(0);
        col1.setPreferredWidth(100);

        TableColumn col2 = table.getColumnModel().getColumn(1);
        col2.setPreferredWidth(200);

        TableColumn col3 = table.getColumnModel().getColumn(2);
        col3.setPreferredWidth(150);

        TableColumn col4 = table.getColumnModel().getColumn(3);
        col4.setPreferredWidth(150);

        TableColumn col5 = table.getColumnModel().getColumn(4);
        col5.setPreferredWidth(100);

        TableColumn col6 = table.getColumnModel().getColumn(5);
        col6.setPreferredWidth(100);

        TableColumn col7 = table.getColumnModel().getColumn(6);
        col7.setPreferredWidth(100);

        TableColumn col8 = table.getColumnModel().getColumn(7);
        col8.setPreferredWidth(100);

        TableColumn col9 = table.getColumnModel().getColumn(8);
        col9.setPreferredWidth(100);

        TableColumn col10 = table.getColumnModel().getColumn(9);
        col10.setPreferredWidth(50);

        TableColumn col11 = table.getColumnModel().getColumn(10);
        col11.setPreferredWidth(100);

        TableColumn tc = table.getColumn("Sex");
        CenterTableCellRenderer centerRenderer = new CenterTableCellRenderer();
        tc.setCellRenderer(centerRenderer);

        tc = table.getColumn("AccountID");
        centerRenderer = new CenterTableCellRenderer();
        tc.setCellRenderer(centerRenderer);

        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(1080, 600);
        frame.setVisible(true);
    }
}

class CenterTableCellRenderer extends DefaultTableCellRenderer{
    CenterTableCellRenderer(){
        setHorizontalAlignment(JLabel.CENTER);
    }
}


text:
Q: What component models are available on my machine? I would like to know what component models (e.g. CORBA, D-Bus, UNO, XPCOM, ActiveX, COM, etc.) are installed on my machine.
Is there a command that I can run on the terminal to see a list of the different component models available?

A: I believe ActiveX and COM are windows only. I'm not familiar with UNO, but reading the Wikipedia article suggests that it is available on Linux. You'd have to install the LibreOffice SDK to work with it. If you've installed that SDK, you'd have UNO.

A: Short answer: No.
Full answer: There is not a system level command to list installed/available component model(s).