text:
Q: Counts and divide from two different selects with dates I have a table with this kind of structure (Sample only)
ID | STATUS | DATE |
--- -------- ------
1    OPEN    31-01-2022
2    CLOSE   15-11-2021
3    CLOSE    21-10-2021
4    OPEN    11-10-2021
5    OPEN    28-09-2021

I would like to know the counts of close vs open records by week. So it will be count(close)/count(open) where close.week = open.week
If there are no matching values, need to return 0 of course.
I got to this query below
SELECT  *
FROM
(SELECT COUNT(*) AS 'CLOSE',  DATEPART(WEEK, DATE) AS 'WEEKSA', DATEPART(YEAR, DATE) AS 'YEARA' FROM TABLE
WHERE STATUS IN ('CLOSE')
GROUP BY DATEPART(WEEK, DATE),DATEPART(YEAR, DATE)) TMPA
FULL OUTER JOIN
(SELECT COUNT(*) AS 'OPEN',  DATEPART(WEEK, DATE) AS 'WEEKSB', DATEPART(YEAR, DATE) AS 'YEARB' FROM TABLE
WHERE STATUS IN ('OPEN')
GROUP BY DATEPART(WEEK, DATE),DATEPART(YEAR, DATE)) TMPB
ON TMPA.WEEKSA = TMPB.WEEKSB AND TMPA.YEARA = TMPB.YEARB

My results are as below (sample only)
  close |   weeksa | yeara | open | weeksb | yearb |
    ------ -------- ------ ------- -------  ------
                                3   2       2021
                                1   3       2021
                                1   4       2021
        2   20      2021        2   20      2021
                                7   22      2021
                                2   23      2021
                                7   26      2021
                                7   27      2021
        2   28      2021        14  28      2021
                                2   29      2021
                                10  30
                                24  31      2021
        2   32      2021        5   32
                                4   33      2021
        1   34      2021        13  34      2021
                                6   35      2021
                                1   36      2021
        1   38      2021
                                1   39      2021
                                2   41      2021
                                4   43      2021
                                1   45      2021
        2   46      2021        25  46      2021
        1   47      2021        5   47      2021
                                4   48      2021
        1   49      2021        20  49      2021
        1   50      2021        17  50      2021
                                1   51      2021

How do I do the math now?
If I do another select the query fails. So I guess either syntax is bad or the whole concept is wrong.
The required result should look like this (Sample)
WEEK | YEAR | RATIO |
----- ------ -------
2       2021    0
3       2021    0
4       2021    0
5       2021    0.93
20      2021    0.1
22      2021    0
23      2021    0
26      2021    0
1       2022    0.75
2       2022    0.23
4       2022    0.07

Cheers!

A: I have added some test data to check the logic, adding the same in the code.
;with cte as(
select 1 ID,    'OPEN'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 10 ID,    'CLOSE'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 11 ID,    'CLOSE'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 12 ID,    'CLOSE'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 22 ID,    'CLOSE'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 32 ID,    'CLOSE'   as STATUS, cast('2021 -01-31' as DATE) DATE
union select 2,'CLOSE',cast('2021-11-28'  as DATE)
union select 3,'CLOSE',cast('2021-10-21'  as DATE)
union select 8,'CLOSE',cast('2021-10-21'  as DATE)
union select 9,'CLOSE',cast('2021-10-21'  as DATE)
union select 4,'OPEN', cast('2021-10-11'  as DATE)
union select 5,'CLOSE', cast('2021-09-28'  as DATE)
union select 6,'OPEN', cast('2021-09-27'  as DATE)
union select 7,'CLOSE', cast('2021-09-26'  as DATE) )
, cte2 as (
select DATEPART(WEEK,date) as week_number,* from cte)
,cte3 as(
select week_number,year(date) yr,count(case when status = 'open' then 1 end)open_count,count(case when status <> 'open' then 1 end) close_count from cte2 group by week_number,year(date))
select week_number as week,yr as year,
cast(case when open_count = 0 then 1.0 else open_count end /
case when close_count = 0 then 1.0 else     close_count end as numeric(3,2)) as ratio
from cte3


text:
Q: Why the Camera is not changing the position like the player does? using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Teleport : MonoBehaviour {

    public GameObject player;
    public Camera mainCamera;
    public Camera firstCam;
    public Camera camera;
    private List<GameObject> TeleportBooths;

    private void Start()
    {
        InstantiateObjects gos = GetComponent<InstantiateObjects>();

        TeleportBooths = new List<GameObject>();
        TeleportBooths = gos.PrefabsList();
        firstCam.enabled = false;
        mainCamera.enabled = false;
        camera.enabled = true;
        player.transform.position = TeleportBooths[0].transform.position;
        camera.transform.position = TeleportBooths[0].transform.position;
        for (int i = 0; i < TeleportBooths.Count; i++)
        {
            TeleportBooths[i].AddComponent<TeleportationsCore>();
        }
    }
}

I have 3 cameras in the hierarchy.
Each one position in other place.
The newest camera i added now is camera.
And in the script i want it to be position in the same place where the player is.
So first i tried with only one Camera variable in the script. And then did in the Start:
Camera.main.enabled = false;
camera.Enabled = true;
camera.transform.position = TeleportBooths[0].transform.position;

But it keep showing the Main Camera view when running the game and not the view of camera. In the Scene view i can see that camera is position now where the player is but it keep showing the Main Camera view.
So i added variables for the main camera and the firstCamera and set them both to enabled false and yet it's showing the main camera not camera.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQLite inner join - update using values from another table This is quite easy and has been asked multiple times but I can't get it to work.
The SQL query I think should work is:
    UPDATE table2
       SET dst.a = dst.a + src.a,
           dst.b = dst.b + src.b,
           dst.c = dst.c + src.c,
           dst.d = dst.d + src.d,
           dst.e = dst.e + src.e
      FROM table2 AS dst
INNER JOIN table1 AS src
        ON dst.f = src.f

A: I came up with an alternative technique using a TRIGGER and "reversing" the direction of the update, albeit at the cost of a dummy field in the source table.
In general terms, you have a Master table and an Updates table.  You want to update some/all fields of records in Master from the corresponding fields in Updates linked by a key field Key.
Instead of UPDATE Master SET ... FROM Master INNER JOIN Updates ON Mater.Key = Updates.Key you do the following:

*

*Add a dummy field TriggerField to the Updates table to act as the focus of the trigger.

*Create a trigger on this field:
CREATE TRIGGER UpdateTrigger AFTER UPDATE OF TriggerField ON Updates
BEGIN
    UPDATE Master SET
        Field1 = OLD.Field1,
        Field2 = OLD.Field2,
        ...
    WHERE Master.Key = OLD.Key
END;

*Launch the update process with the following:
UPDATE Updates SET TriggerField = NULL ;

Notes

*

*The dummy field is merely an anchor for the trigger so that any other UPDATE Updates SET ... won't trigger the update into Master.  If you only ever INSERT into Updates then you don't need it (and can remove the OF TriggerField clause when creating the trigger).

*From some rough-and-ready timings, this seems to work about the same speed as REPLACE INTO but avoids the feels-slightly-wrong technique of removing and adding rows.  It is also simpler if you are only updating a few fields in Master as you only list the ones you want to change.

*It is orders of magnitude faster than the other alternative I've seen to UPDATE ... FROM which is:
UPDATE Master SET
    Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
    Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
    ...
;

Updating six fields over 1700 records was roughly 0.05s for Tony and my methods but 2.50s for the UPDATE ... ( SELECT... ) method.

*AFTER UPDATE triggers on Master seem to fire as expected.

A: As Tony says, the solution is the replace into way but  you can use the sqlite hidden field rowid to simulate full update with join like:
replace into table2
(rowid,a, b, c, d, e, f, g)
select dest.rowid,src.a, src.b, src.c, src.d, src.e, dest.f, dest.g
from table1 src
inner join table2 dest on src.f = dest.f

With this you recreate full rows  if you don't have primary key for the replace or as standard method to do the updates with joins.

A: Using the update statement it is not possible because in sqlite joins in an update statement are not supported.  See docs:
update statement
If you only wanted to update a single column to a static value, you could use a subquery in the update statement correctly.  See this example: How do I make an UPDATE while joining tables on SQLite?
Now in your example, making an assumption that there is a unique key on "column f" - a workaround/solution I have come up with is using the replace statement:
replace into table2
(a, b, c, d, e, f, g)
select src.a, src.b, src.c, src.d, src.e, dest.f, dest.g
from table1 src
inner join table2 dest on src.f = dest.f

I also added an extra column to table2 "column g" to show how you'd "update" only some of the columns with this method.
One other thing to be cautious about is if you use "PRAGMA foreign_keys = ON;" it's possible to have issues with this as the row is effectively deleted and inserted.

A: SQLITE does not support UPDATE with INNER JOIN nor do several other DB's. Inner Joins are nice and simple however it can be accomplished using just a UPDATE and a subquery select. By using a where clause and the 'IN' with a subquery and a additional subquery for the 'SET' the same result can always be accomplished. Below is how it's done.
UPDATE table2
  SET a = a + (select a from table1 where table1.f = table2.f),
       b = b + (select b from table1 where table1.f = table2.f),
       c = c + (select c from table1 where table1.f = table2.f),
       d = d + (select d from table1 where table1.f = table2.f),
       e = e + (select e from table1 where table1.f = table2.f)
  WHERE RowId IN (Select table2.RowId from table1 where table1.f = table2.f)

A: Use below query:
UPDATE table2
SET a = Z.a,
    b = Z.b,
    c = Z.c,
    d = Z.d,
    e = Z.e
FROM (SELECT dst.id,
             dst.a + src.a AS a,
             dst.b + src.b AS b,
             dst.c + src.c AS c,
             dst.d + src.d AS d,
             dst.e + src.e AS e
      FROM table2 AS dst
      INNER JOIN table1 AS src ON dst.f = src.f
      )Z
WHERE table2.id = z.id


text:
Q: Geolocation service with AWS API Gateway and Lambda What we are trying to do
We are trying to set up a very simple Geolocation service with API Gateway and Lambda.
Very similar to https://ipstack.com/, but we don't want to use an external service as we believe it could be an issue in some jurisdictions to send a non-anonymized IP address to a service we don't control (before getting the user's consent).
Would like to have a simple api https://location.my-site.com that returns the country (for GDPR, cookies, etc purposes).
Now it seems that there is a light Cloudfront behind API Gateway that would produce the header "Cloudfront-Viewer-Country", which would be very simple and achieve what we need. i.e. lambda receives Cloudfront-Viewer-Country and just sends it back.
What we have tried
I have seen solutions such as this one: Build a Geolocation API using AWS Lambda and MaxMind, but I struggle to see why deploying an RDS and maintaining the MaxMind database would make sense for us, if it is already available from Cloudfront-Viewer-Country.
I have seen this question: Accessing cloudfront-viewer-country header in AWS API Gateway using HTTP Proxy?, and tried implementing the answer from Michael - sqlbot. But I cannot seem to access the headers.
I have also tried what is suggested in this post, but I can't seem to access the value of Cloudfront-Viewer-Country either.
What we are doing (in conjunction with 'What we have tried')
To access and check if the header is available I am using the following python lambda function
import json

def lambda_handler(event, context):

    response = {
        'status': '200',
        'statusDescription': 'Found',
        'headers': {
            'location' : [ {
                'event': json.dumps(event)
            } ]
        }
    }

    return response

What the problem is
but the event json dump doesn't contain Cloudfront-Viewer-Country.
I suspect I'm doing something wrong but I really can't figure it out. Any pointer would be very much appreciated.
Thank you

A: I was able to get access to Cloudfront-Viewer-Country by setting a Endpoint Type = Edge optimized.
I could not get it to work with Endpoint Type = Regional or with http api gateway.


text:
Q: VSCode - show character length of selected text Is it possible to show the character length of your selected text in the status bar?  For example, in PyCharm as well as many other editors, it shows the line and column position. Then when you have some text selected, it shows the char count.

However in VSCode, it just shows the line and column position.

But when I select a piece of text, it disappears.

Is this a bug in my installation, or is it something I have to enable?

A: This should be shown by default:

I notice that your space between "Live Share" and "Spaces: 4" is quite small. Maybe the longer string on a selection does not fit in there. Have you tried expanding the Window or hide some of the status bar elements by right-clicking on it?


text:
Q: Part of surface plot missing I have created the following plot using pgfplots

I'd like to remove the white patches (marked in red). Here's my code
\begin{tikzpicture}
  \begin{axis}[grid = major, grid style={dotted},
zticklabel style={/pgf/number format/fixed}, xlabel = $x_{1}$, ylabel
= $x_{2}$, zlabel=$\Delta F$]
        \addplot3[surf, shader = faceted, color = blue, opacity = 1, faceted color = white]
    table [col sep=comma]{Inhalt/Abbildungen/LaTeX/dat3.csv};
  \end{axis}
\end{tikzpicture}

I can provide the data file if necessary.


text:
Q: swift ios tabBar didSelectItem present login screen I am trying to display a login screen if the user clicks on tab 2 or tab 3.
I tried adding:
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

        if item.tag == 1 || item.tag == 2 {
            if LocalStore.getToken() == nil {
                self.performSegueWithIdentifier("loginSegue", sender: self)
                return
            }
        }
}

This will show the modal VC/login screen that I have as a segue from the rootVC. But the tab bar still segues to the clicked tab.
What I want to do is to stop the tab bar form fire a segue to the selected VC/clicked tab and instead only display the modal VC/login screen

A: If you are using UITabBarController, you could override shouldSelectViewController method of its delegate (UITabBarControllerDelegate). It is there for you to dynamically decide if you want to switch to a particular view controller or not:
func tabBarController(tabBarController: UITabBarController,
shouldSelectViewController viewController: UIViewController) -> Bool {
    guard
        let tab = tabBarController.viewControllers?.indexOf(viewController)
        where [1, 2].contains(tab)
        else { return true }
    if LocalStore.getToken() == nil {

        /// Present the login screen here

        return false
    }
    return true
}


text:
Q: Select Inner JSON fields with TypeORM I have a table in my PostgreSQL database, This table has a json field named data and in this data column I have stored something like this:
{"info":{"title":"test"}}

How can I select just the title from this column with TypeORM. I used the code below but I get an error:
return await this.myRepository.findAndCount({
      select:['data -> "info" -> "tile" AS title']
      take: 10,
      skip: 10,
    });


text:
Q: Why it works: BigDecimal Sum with Reduce and BigDecimal::add I can understand why Total1 is calculated, but as Total2 is calculated I have no idea!
How can a BigDecimal::add be used in a BiFunction? Signatures are not the same !!!
package br.com.jorge.java8.streams.bigdecimal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class BigDecimalSumTest {
    public static void main(String[] args) {

        List<BigDecimal> list = new ArrayList<>();

        list.add(new BigDecimal("1"));
        list.add(new BigDecimal("2"));

        BigDecimal total1 = list.stream().reduce(BigDecimal.ZERO, (t, v) -> t.add(v));

        BigDecimal total2 = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println("Total 1: " + total1);
        System.out.println("Total 2: " + total2);
    }
}

A: Its used as a BinaryOperator<T> in your current context.
Its equivalent lambda representation:
(bigDecimal, augend) -> bigDecimal.add(augend) // same as in your previous line of code

and anonymous class representation:
new BinaryOperator<BigDecimal>() {
    @Override
    public BigDecimal apply(BigDecimal bigDecimal, BigDecimal augend) {
        return bigDecimal.add(augend);
    }
}

where BinaryOperator<T> extends BiFunction<T,T,T>, meaning its a specialization of BiFunction for the case where the operands and the result are all of the same type.
Added to that, your code is actually using one of the overloaded implementations of reduce method i.e. Stream.reduce(T identity, BinaryOperator<T> accumulator).

How can a BigDecimal::add be used in a BiFunction

Just a step further and only for explanation, there is also an overloaded implementation that uses combiner as in Stream.reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) which would look like :
BigDecimal total = list.stream()
                       .reduce(BigDecimal.ZERO, BigDecimal::add, BigDecimal::add);
//                                                   ^^                ^^
//                                              BiFunction here    BinaryOperator here

A: Given BigDecimal::add is being used as a BiFunction<BigDecimal, BigDecimal, BigDecimal>, the compiler will look for one of two eligible signatures.
The first possible signature, as you have picked up on, would be a two-argument static method. The relevant lambda would be (a, b) -> BigDecimal.add(a, b). Of course, you are correct to recognise that this doesn't exist.
The second possible signature would be a one-argument instance method. The equivalent lambda here would be (a, b) -> a.add(b). As this one exists and the other does not, this is how the compiler would interpret it.


text:
Q: How to make a method run in the "background" (threading?) I currently have some code that cycles through a text file looking for a specific phrase. However, when this method runs, the whole application locks up. I assume because it's looping, which is what I want.
I would like this to happen in the background, so normal methods and user interaction with the application can still be done.
How can this be done/improved?
private void CheckLog()
{
    while (true)
    {
        // lets get a break
        Thread.Sleep(5000);

        if (!File.Exists("Command.bat"))
        {
            continue;
        }

        using (StreamReader sr = File.OpenText("Command.bat"))
        {
            string s = "";

            while ((s = sr.ReadLine()) != null)
            {
                if (s.Contains("mp4:production/"))
                {
                    // output it
                    MessageBox.Show(s);
                }
            }
        }
    }
}

A: Use
class Foo {
    private Thread thread;
    private void CheckLog() {...}
    private void StartObserving() {
        thread = new Thread(this.CheckLog);
        thread.Start();
    }
}

or the backgroundworker component from the palette.


text:
Q: JSON data calculation and re-formate using Angular I have a JSON file and I am trying to calculate the JSON file key based on the value and reformating it. My JSON file looks like below:
data=[
    {
        pet:'Cat',
        fruit:'Apple',
        fish:'Hilsha'
    },
    {
        pet:'Dog',
        fish:'Carp'
    },
    {
        pet:'Cat',
        fruit:'Orange',
        fish:'Lobster'
    }
];

I do like to calculate and formate it like below:
data=[
    {
        label:'Pet',
        total:3,
        list:[
            {
                name:'Cat',
                value: 2,
            },
            {
                name:'Dog',
                value: 1,
            }
        ]
    },
    {
        label:'Fruit',
        total:2,
        list:[
            {
                name:'Apple',
                value: 1,
            },
            {
                name:'Orange',
                value: 1,
            }
        ]
    },
    {
        label:'Fish',
        total:3,
        list:[
            {
                name:'Hilsha',
                value: 1,
            },
            {
                name:'Carp',
                value: 1,
            },
            {
                name:'Lobster',
                value: 1,
            }
        ]
    },
];

If anybody can help me, it will be very help for me and will save a day.

A: I have fixed this task myself. If I have any wrong, you can put your comment fill-free :)
``
ngOnInit(): void {
      this.dataService.$data.subscribe(data => {
         // Create new object and calculation according to category
         let petObj: any = {}
         let fruitObj: any = {}
         let fishObj: any = {}
         data.forEach((el: any) => {
            if (el.pet != undefined) {
               petObj[el.pet] = (petObj[el.pet] || 0) + 1;
            }
            if (el.fruit != undefined) {
               fruitObj[el.fruit] = (fruitObj[el.fruit] || 0) + 1;
            }
            if (el.fish != undefined) {
               fishObj[el.fish] = (fishObj[el.fish] || 0) + 1;
            }
         });

         // Create list according to category
         let pet_list: any = [];
         let fruit_list: any = [];
         let fish_list: any = [];
         for (var key in petObj) {
            let pet = {
               label: key,
               value: petObj[key]
            }
            pet_list.push(pet)
         }
         for (var key in fruitObj) {
            let fruit = {
               label: key,
               value: fruitObj[key]
            }
            fruit_list.push(fruit)
         }
         for (var key in fishObj) {
            let fish = {
               label: key,
               value: fishObj[key]
            }
            fish_list.push(fish)
         }

         // Calculate total sum according to category
         var totalPet = pet_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
         var totalFruit = fruit_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
         var totalFish = fish_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);

         // Rearrange the JSON
         this.rearrangeData = [
            {
               label: 'Pet',
               total: totalPet,
               list: pet_list
            },
            {
               label: 'Fruit',
               total: totalFruit,
               list: fruit_list
            },
            {
               label: 'Fish',
               total: totalFish,
               list: fish_list
            }
         ]
         console.log(this.rearrangeData)
         // End rearrange the JSON
      });
   }

``

A: You can simplify your function. Take a look this one
  group(oldData) {
    const data = [];  //declare an empty array

    oldData.forEach((x) => {
                           //x will be {pet: 'Cat',fruit: 'Apple',fish: 'Hilsha'},
                          //          {pet: 'Dog',fish: 'Carp'}
                         //            ...
      Object.keys(x).forEach((key) => {

                            //key will be 'pet','fruit',...

        const item = data.find((d) => d.label == key); //search in the "data array"

        if (item) {      //if find it

          item.total++;  //add 1 to the property total of the element find it

                        // and search in the item.list the 'Cat'
          const list = item.list.find((l) => l.name == x[key]);

                       //if find it add 1 to the property value of the list
          if (list)
               list.value++;
          else
                      //if not, add to the list
                      //an object with property "name" and "value" equal 1

             item.list.push({ name: x[key], value: 1 });
        } else
                 //if the element is not in the "array data"
                 //add an object with properties label, total and list
                 //see that list is an array with an unique element

          data.push({
            label: key,
            total: 1,
            list: [{ name: x[key], value: 1 }],
          });
      });
    });
    return data;
  }

You can use like
this.dataService.$data.subscribe(data => {
     this.rearrangeData=this.group(data)
}

NOTE: this function the labels are 'pet','fruit' and 'fish' not 'Pet', 'Fruit' and 'Fish'

A: Did you try reading the text leading up to this exercise? That'd be my first approach. After that, I'd use reduce. You can do pretty much anything with reduce.


text:
Q: How should C++ objects be serialized? We are doing a project on high performance computing, which using MPI as parallel computing framework. There are just a few algorithms already implemented on legacy platform. What we do is rewriten the original serial algorithm to parallel version based on MPI.
I encounter this performance problem: When running parallel algorithm based on MPI, there are a lot of comunication overhead between multiple process. The inter-process comunication is consist of three steps:

*

*Process A serialize some C++ objects into binary format.

*Process A send binary format data to Process B by MPI.

*Process B deserialize binary format data into C++ objects.

We found these comunication steps, especially serialize/deserialize steps, cost huge amount of time. How could we hand this performance issue?
By the Way, in our C++ code, We use a lot of STL, which is more complex then C-like struct.
P.S. I am doing this(serialization) now by written code traversing all fields of the objects and copy them sequentially into a byte array.
To demonstrate what I doing, there is a code snippet. Note that this is just a single feature construction process:
sic::GeometryFeature *ptFeature =
    (GeometryFeature *) outLayer->getFeature(iFeature);
sic::Geometry* geom = ptFeature->getGeometry();
std::string geomClassName = geom->getClassName();

sic::Geometry* ptGeom = geom;
unsigned char *wkbBuffer = NULL;
OGRGeometry * gtGeom = NULL;
if (geomClassName == "Point") {
    ptGeom = new sic::MultiPoint();
    ((sic::MultiPoint *) ptGeom)->insert(geom);
    gtGeom = new OGRMultiPoint();
    int wkbSize = ((sic::MultiPoint *) ptGeom)->WkbSize();
    wkbBuffer = (unsigned char *) malloc(wkbSize);
    ((sic::GeometryCollection *) ptGeom)->exportToWkb(sic::wkbNDR,
        wkbBuffer, wkbMultiPoint);
}
} else if (...) {
    ......
}
gtGeom->importFromWkb(wkbBuffer);
free(wkbBuffer);
assert(gtGeom);
OGRFeature * poFeature = OGRFeature::CreateFeature(
     poLayer->GetLayerDefn());
poFeature->SetGeometry(gtGeom);

And more about What I am doing serializing objects:
unsigned char *bytes = (unsigned char *) malloc(size);
    size_t offset = 0;

    size_t type_size = sizeof(OGRwkbGeometryType);
    OGRwkbGeometryType type = layer->GetGeomType();
    memcpy(bytes + offset, &type, type_size);
    offset += type_size;

    size_t count_size = sizeof(int);
    int count = layer->GetFeatureCount();
    memcpy(bytes + offset, &count, count_size);
    offset += count_size;

    layer->ResetReading();
    for (OGRFeature *feature = layer->GetNextFeature(); feature != NULL;
            feature = layer->GetNextFeature()) {
        OGRGeometry *geometry = feature->GetGeometryRef();
        if (geometry) {
            geometry->exportToWkb(wkbNDR, bytes + offset);
            offset += geometry->WkbSize();
        } else {
            (*(int *) (bytes + type_size))--;
        }
        OGRFeature::DestroyFeature(feature);
    }

    return bytes;

Any Comment will be appreciated. Thanks!

A: (Brian's answer's offering to help you use a library... he's a very experienced programmer - sounds like it could be worth a go.)
Separately, I looked at your code - there's lots of temporary buffers, new/malloc allocation, use of sizeof etc.. so I thought I'd illustrate a "quick, simple but nice" approach to cleaning that up - enough to hopefully get you started...
First create a binary stream type that factors and hides a lot of the low-level work:
#include <arpa/inet.h> // for htonl/s, ntoh/s
#include <endian.h> // for htonbe64, if you have it...

#include <iostream>
#include <string>
#include <map>

// support routines - use C++ overloading to polymorphically dispatch htonl/s

// uint64_t hton(uint64_t n) { return htonbe64(n); }
uint32_t hton(uint32_t n) { return htonl(n); }
uint16_t hton(uint16_t n) { return htons(n); }

// there are no "int" versions - this is ugly but effective...
uint32_t hton(int32_t n) { return htonl(n); }
uint16_t hton(int16_t n) { return htons(n); }

// uint64_t ntoh(uint64_t n) { return betoh64(n); }
uint32_t ntoh(uint32_t n) { return ntohl(n); }
uint16_t ntoh(uint16_t n) { return ntohl(n); }

template <typename OStream>
class Binary_OStream : public OStream
{
  public:
    typedef Binary_OStream This;

    This& write(const char* s, std::streamsize n)
    {
        OStream::write(s, n);
        return *this;
    }

    template <typename T>
    This& rawwrite(const T& t)
    {
        static_cast<OStream&>(*this) << '[' << sizeof t << ']';
        return write((const char*)&t, sizeof t);
    }

    template <typename T>
    This& hton(T h)
    {
        T n = ::hton(h);
        return rawwrite(n);
    }

    // conversions for inbuilt & Standard-library types...

    friend This& operator<<(This& bs, bool x) { return bs << (x ? 'T' : 'F'); }
    friend This& operator<<(This& bs, int8_t x) { return bs << x; }
    friend This& operator<<(This& bs, uint8_t x) { return bs << x; }
    friend This& operator<<(This& bs, int16_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, uint16_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, int32_t x) { return bs.hton(x); }
    friend This& operator<<(This& bs, uint32_t x) { return bs.hton(x); }

    friend This& operator<<(This& bs, double d) { return bs.rawwrite(d); }

    friend This& operator<<(This& bs, const std::string& x)
    {
        bs << x.size();
        return bs.write(x.data(), x.size());
    }

    template <typename K, typename V, typename A>
    friend This& operator<<(This& bs, const std::map<K, V, A>& m)
    {
        typedef typename std::map<K, V, A>::const_iterator It;

        bs << m.size();

        for (It it = m.begin(); it != m.end(); ++it)
            bs << it->first << it->second;

        return bs;
    }

    // add any others you want...
};

Creating a user-defined binary-serialisable type...
// for your own objects...
struct Object
{
    Object(const std::string& s, double x) : s_(s), x_(x) { }

    std::string s_;
    double x_;

    // specify how you want binary serialisation performed (which fields/order etc)
    template <typename T>
    friend Binary_OStream<T>& operator<<(Binary_OStream<T>& os, const Object& o)
    {
        return os << o.s_ << o.x_;
    }
};

Example usage:
#include <iomanip>
#include <sstream>

// support routines just to help you observe/debug the serialisation...

std::string printable(char c)
{
    std::ostringstream oss;
    if (isprint(c))
        oss << c;
    else
        oss << "\\x" << std::hex << std::setw(2) << std::setfill('0')
            << (int)(uint8_t)c << std::dec;
    return oss.str();
}

std::string printable(const std::string& s)
{
    std::string result;
    for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
        result += printable(*i);
    return result;
}

int main()
{
    {
        Binary_OStream<std::ostringstream> bs;

        Object o("pi", 3.14);

        bs << o;

        std::cout << "serialised to '" << printable(bs.str()) << "'\n";
    }

    {
        Binary_OStream<std::ostringstream> bs;

        std::map<int, std::string> m;
        m[0] = "zero";
        m[1] = "one";
        m[2] = "two";
        bs << m;

        std::cout << "serialised to '" << printable(bs.str()) << "'\n";
    }
}

The next step is to create a Binary_IStream - it's very, very similar to the above.  (boost reduces the work a little by using the '%' operator instead of the traditional << and >>, such that the same function can specify fields for serialiation and deserialisation.)
Implementation notes/thoughts:

*

*If you prefer, you can remove the template parameter from Binary_Stream, and have a constructor store an arbitrary std::ostream& into a private member variable, then send all streaming operations to that data member.

*

*This has the advantages of minimising code bloat from instantiations for differents stream types, allowing implementation to be hidden from the translation unit and linked in later (helps keep compilation times down in a large project), and letting you just attach a Binary_Stream to any existing stream at any time (great if someone's passing you a pre-existing stream).

*The "disadvantage" is that you have to explicitly forward to any other ostream member functions that you want to be accessible to Binary_Stream users (more control but tedious), or provide a (less convenient/elegant?) std::ostream& stream() { return s_; }-style accessor.


text:
Q: Unix Bash script to embolden/underline/italicize specific text I've been trawling the web trying to find examples of Unix Bash script that can handle basic text styling (bold/underline/italics), but can't find anything? Is such a thing possible to do?
For example:

*

*Embolden/Underline/Italicize all lines ending in ":"?

*(Turn off) Embolden/Underline/Italicize all lines ending in ":"?

I want to set it up as a Service via Automator; so using /bin/bash and actioning on "selected text" (in a rich-text-compatible file, of course).

A: Basically, you want to do declare some variables with the styling code--something like this:
underline=`tput smul`
nounderline=`tput rmul`
bold=`tput bold`
normal=`tput sgr0`

then you can call these for use in your output using the variables, like this:
echo "${bold}bold${normal} text stands out!"
echo "${underline}underlined${nounderline} text does, too."

As far as automating it to apply to all lines beginning with a specific character, you're better off just using the variables as shown above. Besides using this method just being easier, it's also cleaner and more usable. For example, when using this method you have the ability to style any number of words in a given output string differently, so as to emphasize a specific word, not the entire sentence (unless of course that's your goal).
For more information, you should check out http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x405.html and/or man tput

A: Just to add, that instead of using tput, you can also specify colors as ANSI escape sequences.
These are specified like \033[XXXm, where XXX is a series of semicolon-separated parameters (as covered by the ECMA-48 standard). For example:
Color_Off='\033[0m'       # Text Reset

# Regular Colors
Black='\033[0;30m'        # Black
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Blue='\033[0;34m'         # Blue
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan
White='\033[0;37m'        # White

# Bold
BBlack='\033[1;30m'       # Black
BRed='\033[1;31m'         # Red
BGreen='\033[1;32m'       # Green
BYellow='\033[1;33m'      # Yellow
BBlue='\033[1;34m'        # Blue
BPurple='\033[1;35m'      # Purple
BCyan='\033[1;36m'        # Cyan
BWhite='\033[1;37m'       # White

# Underline
UBlack='\033[4;30m'       # Black
URed='\033[4;31m'         # Red
UGreen='\033[4;32m'       # Green
UYellow='\033[4;33m'      # Yellow
UBlue='\033[4;34m'        # Blue
UPurple='\033[4;35m'      # Purple
UCyan='\033[4;36m'        # Cyan
UWhite='\033[4;37m'       # White

# Background
On_Black='\033[40m'       # Black
On_Red='\033[41m'         # Red
On_Green='\033[42m'       # Green
On_Yellow='\033[43m'      # Yellow
On_Blue='\033[44m'        # Blue
On_Purple='\033[45m'      # Purple
On_Cyan='\033[46m'        # Cyan
On_White='\033[47m'       # White

# High Intensity
IBlack='\033[0;90m'       # Black
IRed='\033[0;91m'         # Red
IGreen='\033[0;92m'       # Green
IYellow='\033[0;93m'      # Yellow
IBlue='\033[0;94m'        # Blue
IPurple='\033[0;95m'      # Purple
ICyan='\033[0;96m'        # Cyan
IWhite='\033[0;97m'       # White

# Bold High Intensity
BIBlack='\033[1;90m'      # Black
BIRed='\033[1;91m'        # Red
BIGreen='\033[1;92m'      # Green
BIYellow='\033[1;93m'     # Yellow
BIBlue='\033[1;94m'       # Blue
BIPurple='\033[1;95m'     # Purple
BICyan='\033[1;96m'       # Cyan
BIWhite='\033[1;97m'      # White

# High Intensity backgrounds
On_IBlack='\033[0;100m'   # Black
On_IRed='\033[0;101m'     # Red
On_IGreen='\033[0;102m'   # Green
On_IYellow='\033[0;103m'  # Yellow
On_IBlue='\033[0;104m'    # Blue
On_IPurple='\033[0;105m'  # Purple
On_ICyan='\033[0;106m'    # Cyan
On_IWhite='\033[0;107m'   # White

E.g. to print in bright purple (note that -e is required to enable interpretation of backslash escapes)
echo -e "\033[0;95m Hello World!\033[0m"

Colors are rendered by the terminal you are using, traditionally terminal colors were 8-bit, nowadays most termainl emulators are true color / 256-bit.


text:
Q: How to handle the mac integrated About MenuBar item in Qt QML? I created a QML app under Mac, but I don't know what happens when I click the about menu.
In http://doc.qt.io/qt-5/qmenubar.html, we find things about QMenuBar on OS X. But what's the corresponding QML method?
Currently, my code is:
Menu {
    title: qsTr("&File")
    MenuItem {
        text: qsTr("&Open")
        onTriggered: messageDialog.show(qsTr("Open action triggered"))
    }
    MenuItem {
        text: "about.*"
        onTriggered: console.debug("FDF")
    }
    MenuItem {
        text: qsTr("E&xit")
        onTriggered: Qt.quit()
    }
}

When I execute, this menu only shows Open, and About and Exit are correctly integrated into the mac menu. The exit is fine, but when I click about, it just quits normally.
So how do we handle that?

A: I found the problem. My code is like this,
menuBar: MenuBar {

    Menu {
        title: qsTr("&File")
        MenuItem {
            text: qsTr("&Open")
            onTriggered: messageDialog.show(qsTr("Open action triggered"))
        }

        MenuItem {
            text: "about.*"
            onTriggered: console.debug("FDF")
        }

        MenuItem {
            text: qsTr("E&xit")
            onTriggered: Qt.quit()
        }
    }

    Menu {
        title: qsTr("&Help")
        MenuItem {
            text: qsTr("&Help")
            onTriggered: messageDialog.show(qsTr("Open action triggered"))
        }
        MenuItem {
            text: qsTr("&About")
            onTriggered: Qt.quit()
        }
    }
}

There are two about menu items, and the latter overrides the previous one.

A: menuBar: MenuBar {

    Menu {
        title: qsTr("&File") // Name

        MenuItem {
            text: qsTr("&Open") // Name
            onTriggered: messageDialog.show(qsTr("Open action triggered")) // Action on Triggered
        }

        MenuItem {
            ...
        }
    }
}


text:
Q: Stretch documentView to fill NSScrollView What I would like to achieve:
A rectangle (paper) of a given size which is draw inside a view.
If it is larger than the view I would like it to be scrollable.
If it is smaller than the view I would like it be centered.
A list of shapes should be drawn on top of this rectangle.
If they are outside the rectangle they should not be clippd but be drawn anyway.
The scrollable area is only affected by the rect(paper) not by the shapes. So a shape outside the scrollable area does not need to be drawn.
I am using Swift2.0, auto layout and InterfaceBuilder
What I have now:
I have a custom CanvasView inside an NSScrollView.
I used this trick to center the CanvasView if the canvas size is smaller than the NSScrollView: https://stackoverflow.com/a/28154936/1533291
My CanvasView is defined like this:
class CanvasView : NSView {
  var canvasSize = Vec2d(x: 100, y: 100) {
    didSet {
      invalidateintrinsiccontentsize()
    }
  }

  var shapes : [MyShape] = []

  override func drawRect(dirtyRect: NSRect) {
    if let context = currentContext {
      let offsetX = (bounds.width-CGFloat(canvasSize.x))/2.0
      let offsetY = (bounds.height-CGFloat(canvasSize.y))/2.0
      CGContextTranslateCTM(context, offsetX, offsetY)

      CGContextSetRGBFillColor(context, 1, 1, 1, 1)
      CGContextFillRect(context, CGRect(x:0,y:0, width: CGFloat(canvasSize.x), height: CGFloat(canvasSize.y)))

      for shape in shapes {
          shape.shape.render(context)
      }
    }
  }

  override var intrinsicContentSize : NSSize {
    return NSSize(width: canvasSize.x, height: canvasSize.y)
  }
}

So as you can see I draw everything centered inside the canvas view.
The problem is if one of the shapes is outside the canvas it get's clipped because drawRect can only draw inside the view's bounds.
Thats why I would like to stretch the CanvasView so it's width and height are alway equal to or greater than the size of the scrollview. But I do not know how to do it and I am not even sure if this is the most elegant approach.
Update: The answer I posted below does not work when the ScrollView is zoomable and the zoom factor is less than one. I this case the canvas is neither stretched to full size nor is it centred. I am still interested in a working solution for zoomable Scrollviews.

A: Update: Does not work when the ScrollView is zoomable and the zoom factor is less than 1...

After some more experimenting I found a working solution myself.
The core solution is quite straightforward:

*

*Create a NSScrollView in InterfaceBuilder

*Specify the class for the custom NSView inside the Clip View
(you do not need to set change the ClipView's class)

*Now add two Constraints:

*

*customView.height >= clipView.height (prio:1000)

*customView.width >= clipView.width (prio:1000)

This is what I already tried before but it would result in InterfaceBuilder complaining the constraint definitions not being sufficient because it does not know that the alignment is done at runtime by the NSScrollView itself.

*That's why you need to add two more constraints:

*

*customView.centerX == clipView.centerX (prio: 1000)

*customView.centerY == clipView.centerY (prio: 1000)

But as these two constraints are not needed at runtime you can select the option "remove at build time" for both of them
But even now InterfaceBuilder is complaining. It does not know the intrinsicSize of the customView even though it is defined in the customView class. It marks the width/height constraints as ambiguous.

*That's why finally you have to set a placeholder for the customView's intrinsic size.

Now InterfaceBuilder is happy and when running the app the customView never is smaller than the scrollView.
All the compression resistance and content hugging priorities can be left set to their defaults.
The following screenshot shows the described options in InterfaceBuilder:


text:
Q: Omit a column while writing mysql data into a csv file using fputcsv My code for fetching mysql rows and write to csv file using fputscv is working fine. But I want to omit first column while writing to the csv file. Clearly telling, all the fetched values are different points of a graph and I would be directly importing that generated csv file for a graph generating code. The id (which is not a graph point) will be included in csv file if I use a query like,
$sql = "SELECT * FROM mybase WHERE id='$id'";
$qry = $dbo->prepare($sql);
$qry->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
fputcsv($data, $row);

Anyone knows the best method to eliminate the ID before writing into the csv file.?
I  saw an obvious and simple result here. Unfortunately, I have too many columns and it is difficult to specify each column in sql query. Thanks..

A: Just UNSET it like
unset($row['ID']);
fputcsv($data, $row);

Orelse You can fetch all the columns except ID in your query itself like
$sql = "SELECT other_than_ID_column FROM mybase WHERE id='$id'";


text:
Q: Unresolved external symbol - IdnToAscii I tried to build the following sample application available on msdn:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd319089%28v=vs.85%29.aspx
I created a new C++ command line project in Visual Studio 2012 Premium on a windows 7 64bit box, and copied the code of the sample in the main cpp file.
When I try to compile, I get the following error:
Error   1   error LNK2001: unresolved external symbol __imp__IdnToAscii@20

From other posts of people having similar errors, I figure I'm supposed to include some header or lib file. But which one(s)? How do I do that in VS2012/C++ (I'm a complete c++ noob...)

A: It seems from MSDN, you need to link against Normaliz.dll.
Try adding Normaliz.lib in Linker -> Input -> Additional Dependencies


text:
Q: C++17 variant inside the class The following code compiles well:
int main()
{
    variant<any> var;
    var = 5;
    cout << any_cast<int>(get<any>(var)) << endl;
    return 0;
}

But when I'm trying to put variant<any> as a class member
struct MyClass{
    variant<any> var;
};

int main()
{
    MyClass s;
    return 0;
}

It doesn't compile. Am I doing something wrong or it is some bug?
I'm using gcc 7.1.0
In file included from /home/zak/Projects/Anytest/main.cpp:3:0:
/usr/local/gcc-7.1/include/c++/7.1.0/variant: In instantiation of 'struct std::__detail::__variant::__accepted_index<const std::variant<std::any>&, std::variant<std::any>, void>':
/usr/local/gcc-7.1/include/c++/7.1.0/variant:911:26:   required from 'constexpr const size_t std::variant<std::any>::__accepted_index<const std::variant<std::any>&>'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:940:6:   required by substitution of 'template<class _Tp, class> constexpr std::variant<std::any>::variant(_Tp&&) [with _Tp = const std::variant<std::any>&; <template-parameter-1-2> = <missing>]'
/home/zak/Projects/Anytest/main.cpp:14:13:   required from here
/usr/local/gcc-7.1/include/c++/7.1.0/variant:559:49: error: no matching function for call to 'std::__detail::__variant::__overload_set<std::any>::_S_fun(const std::variant<std::any>&)'
       decltype(__overload_set<_Types...>::_S_fun(std::declval<_Tp>()),
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note: candidate: static std::integral_constant<long unsigned int, sizeof... (_Rest)> std::__detail::__variant::__overload_set<_First, _Rest ...>::_S_fun(_First) [with _First = std::any; _Rest = {}]
       static integral_constant<size_t, sizeof...(_Rest)> _S_fun(_First);
                                                          ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note:   no known conversion for argument 1 from 'const std::variant<std::any>' to 'std::any'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note: candidate: static void std::__detail::__variant::__overload_set<_Types>::_S_fun() [with _Types = {}]
     { static void _S_fun(); };
                   ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note:   candidate expects 0 arguments, 1 provided
/usr/local/gcc-7.1/include/c++/7.1.0/variant:559:49: error: no matching function for call to 'std::__detail::__variant::__overload_set<std::any>::_S_fun(const std::variant<std::any>&)'
       decltype(__overload_set<_Types...>::_S_fun(std::declval<_Tp>()),
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note: candidate: static std::integral_constant<long unsigned int, sizeof... (_Rest)> std::__detail::__variant::__overload_set<_First, _Rest ...>::_S_fun(_First) [with _First = std::any; _Rest = {}]
       static integral_constant<size_t, sizeof...(_Rest)> _S_fun(_First);
                                                          ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note:   no known conversion for argument 1 from 'const std::variant<std::any>' to 'std::any'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note: candidate: static void std::__detail::__variant::__overload_set<_Types>::_S_fun() [with _Types = {}]
     { static void _S_fun(); };
                   ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note:   candidate expects 0 arguments, 1 provided
/usr/local/gcc-7.1/include/c++/7.1.0/variant:559:49: error: no matching function for call to 'std::__detail::__variant::__overload_set<std::any>::_S_fun(const std::variant<std::any>&)'
       decltype(__overload_set<_Types...>::_S_fun(std::declval<_Tp>()),
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note: candidate: static std::integral_constant<long unsigned int, sizeof... (_Rest)> std::__detail::__variant::__overload_set<_First, _Rest ...>::_S_fun(_First) [with _First = std::any; _Rest = {}]
       static integral_constant<size_t, sizeof...(_Rest)> _S_fun(_First);
                                                          ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note:   no known conversion for argument 1 from 'const std::variant<std::any>' to 'std::any'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note: candidate: static void std::__detail::__variant::__overload_set<_Types>::_S_fun() [with _Types = {}]
     { static void _S_fun(); };
                   ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note:   candidate expects 0 arguments, 1 provided
/usr/local/gcc-7.1/include/c++/7.1.0/variant: In instantiation of 'constexpr const size_t std::__detail::__variant::__accepted_index<const std::variant<std::any>&, std::variant<std::any>, void>::value':
/usr/local/gcc-7.1/include/c++/7.1.0/variant:911:26:   required from 'constexpr const size_t std::variant<std::any>::__accepted_index<const std::variant<std::any>&>'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:940:6:   required by substitution of 'template<class _Tp, class> constexpr std::variant<std::any>::variant(_Tp&&) [with _Tp = const std::variant<std::any>&; <template-parameter-1-2> = <missing>]'
/home/zak/Projects/Anytest/main.cpp:14:13:   required from here
/usr/local/gcc-7.1/include/c++/7.1.0/variant:564:12: error: no matching function for call to 'std::__detail::__variant::__overload_set<std::any>::_S_fun(const std::variant<std::any>&)'
  - decltype(__overload_set<_Types...>::
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
      _S_fun(std::declval<_Tp>()))::value;
      ~~~~~~^~~~~~~~~~~~~~~~~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note: candidate: static std::integral_constant<long unsigned int, sizeof... (_Rest)> std::__detail::__variant::__overload_set<_First, _Rest ...>::_S_fun(_First) [with _First = std::any; _Rest = {}]
       static integral_constant<size_t, sizeof...(_Rest)> _S_fun(_First);
                                                          ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:541:58: note:   no known conversion for argument 1 from 'const std::variant<std::any>' to 'std::any'
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note: candidate: static void std::__detail::__variant::__overload_set<_Types>::_S_fun() [with _Types = {}]
     { static void _S_fun(); };
                   ^~~~~~
/usr/local/gcc-7.1/include/c++/7.1.0/variant:535:19: note:   candidate expects 0 arguments, 1 provided

A: The problem is with MyClass's implicitly defined copy constructor, when it tries to copy construct the member of type std::variant<std::any>.
To perform overload resolution, the compiler first needs to try to instantiate all of std::variant's constructor templates, with the function argument being a const std::variant<std::any>&1. The constructor of our interest is this one:
template <class T> constexpr variant(T&& t) noexcept(/*...*/);

It only participates in overload resolution if, among others, the expression FUN(std::forward<T>(t)) is well formed, where FUN is a set of overloaded functions produced according to [variant.ctor]/12.2
In this case, there is only one alternative type (std::any), so there is only one imaginary function FUN, whose signature is FUN(std::any). Now, the compiler needs to decide whether FUN can be called with a const std::variant<std::any>&1. In this process, the compiler needs to know whether std::any can be constructed with const std::variant<std::any>&1.
This will trigger the instantiation of std::any's constructor template template<class T> any(T&& value);, which only participates in overload resolution if std::is_copy_constructible_v<VT> is true (VT being std::decay_t<T>, and T being const std::variant<std::any>&).
Now in order to see whether VT (i.e. std::variant<std::any>) is copy constructible, the compiler needs to try to instantiate all of std::variant's constructor templates... and this is where we started, and we are stuck in a loop.
This can explain why we see template<class _Tp, class> constexpr std::variant<std::any>::variant(_Tp&&) and __overload_set<std::any>::_S_fun (which corresponds to the function FUN mentioned above) in the error message, and why we see the same error appearing several times.
It remains a question how GCC breaks from the above loop, and why tweaking the program can stop GCC from reporting the error. Maybe these are indication of some bug.

1. Strictly speaking, it should be "an lvalue of type const std::variant<std::any>" rather than "a const std::variant<std::any>&".
2. The standard also requires that this constructor shall only participate in overload resolution if is_same_v<decay_t<T>, variant> is false. GCC (libstdc++) chooses to check that later. I don't know whether this is conforming.


text:
Q: Подскажите, почему не происходит сортировки строк по алфавиту, с использованием метода Хоара? Почему при попытке сортировке массива по алфавиту методом Хоара, массив не сортируется должным образом. Хотя я добавил вложенный цикл for для проверки всех букв в слове, если вдруг буквы с первой и т.д. окажутся одинаковыми, а так же добавил проверку indexOf на случай если в центральной строке ser есть подстрока проверяемого слова. Подскажите пожалуйста, буду премного благодарен. И еще интересно, часто ли применяется ,такого рода метод сортировки, на практике. И целесообразно ли применять его для сортировки строк по алфавиту или легче применять пузырьковую сортировку?
class Sort5 {
static void sqr (String mas[]) {
sq (mas, 0, mas.length-1);}
//метод сортровки
private static void sq (String mas[], int left, int rigth) {
int i, j, index;
String ser, temp;

i = left; j = rigth;
ser = mas[(left+rigth)/2];

do {
metka : for (;i<rigth; i++) {
for (index=0; index<mas[i].length() & index<ser.length(); index++) {

if (mas[i].charAt(index)<ser.charAt(index)) break;
else if (mas[i].charAt(index)>ser.charAt(index)) break metka;
else if (ser.indexOf(mas[i])>=0) break;}}

metka2 : for (;j>left; j--) {
for (index=0; index<mas[j].length() & index<ser.length(); index++) {

if (mas[j].charAt(index)<ser.charAt(index)) break;
else if (mas[j].charAt(index)>ser.charAt(index)) break metka2;
else if (ser.indexOf(mas[j])>=0) break;}}

if (i<=j) {
temp = mas[i];
mas[i] = mas[j];
mas[j] = temp;
i++; j--;}
} while (i<=j);

if (i<rigth) sq (mas, i, rigth);
if (j>left) sq (mas, left, j);
}
}

class Prog131 {
public static void main (String args []) {
String mas [] = {
"this", "is", "in", "can", "do", "break", "thiss",
"mother", "glowing", "glow", "best", "z", "best", "zak", "probl"};

System.out.println ("Massiv do:");
for (String i : mas)
System.out.print (i+" ");

Sort5.sqr(mas);

System.out.println ("\nMassiv posle:");
for (String i : mas)
System.out.print (i+" ");
}}


text:
Q: FileOpenPicker windows 10 Mobile I want do an uwp app where I want use FileOpenPicker but the app work only on windows 10 and not on windows 10 mobile
On windows 10 mobile my app crash...and the exception message is: "Element not found. (Exception from HRESULT: 0x80070490)"
This is my code:
        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.FileTypeFilter.Add(".jpg");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".png");

        StorageFile file = await openPicker.PickSingleFileAsync();

        if (file != null)

        {

            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            var image = new BitmapImage();

            ImageBrush ib = new ImageBrush();
            ib.ImageSource = image;

            image.SetSource(stream);

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var filePath = file.Path;
            localSettings.Values["monimage"] = filePath;

            set.Background = new ImageBrush { ImageSource = image, Stretch = Stretch.UniformToFill };

        }

        else

        {

            //

        }

I have tested my app on windows 10 mobile 10.0.14393.693
I have not the possibility to test on others windows 10 mobile version but I think the problem is not the windows 10 version but my code...

A: I solved myself the problem, I tested the others app of the store who use FileOpenPicker and they all have the same error so I reinstalled windows 10 mobile and all work well now :)


text:
Q: How to get events in shared memory in client-server application I am trying to use shared memory for my client server application. I am using File mapping concept for it. Server is going to create file map using CreateFileMapping API. Then it will use MapViewOfFile and copymemory api to copy for the shared space.
Client is going to open the same File mapping and reading from the shared space.
The code is working fine But as per my requirements server is going to put data continuously and client is going to read data.
I need help if I use while as per the code below it is working but it is taking a huge CPU cycles about 90 percent.
Here is my client code :
while (1)
{
    pBuf = (WCHAR *)MapViewOfFile(hMapFile, // handle to map object
        FILE_MAP_ALL_ACCESS,  // read/write permission
        0,
        0,
        1024);

    if (pBuf == NULL)
    {
        printf("Could not map view of file (%d) \n", GetLastError());

        //CloseHandle(hMapFile);

        getchar();

        return 1;
    }
    if (wcslen(pBuffCheck) == 0)
    {
        wcscpy(pBuffCheck, pBuf);
        //printf("\n File From the Server Found %ls", pBuffCheck);
    }
    else
    {
        if (wcscmp(pBuf, pBuffCheck) != 0)
        {
            wcscpy(pBuffCheck, pBuf);
            printf("\n File Path %ls", pBuffCheck);
        }
    }

    UnmapViewOfFile(pBuf);
    //CloseHandle(hMapFile);
    pBuf = NULL;
}

A: You need to synchronise write and read operations across server and client instead of wasting CPU time in unwanted reads.
Think of using named manual reset event (CreateEvent) and WaitForSingleObject to synchronise between writes and reads inside the while loop across processes.


text:
Q: How to install directory structure recursively in OpenEmbedded BitBake recipe? I'd like to simplify a BitBake recipe that installs a large directory structure by using some sort of recursive install routine rather than calling install many times. The source directory layout is frequently changing during development, which is causing far more recipe revisions than I want to deal with.
As an example, how would the following do_install() be simplified from this:
do_install() {
    install -d ${D}/foo
    install -m 0644 ${S}/foo/*.* ${D}/foo

    install -d ${D}/foo/a
    install -m 0644 ${S}/foo/a/*.* ${D}/foo/a

    install -d ${D}/foo/b
    install -m 0644 ${S}/foo/b/*.* ${D}/foo/b

    install -d ${D}/foo/c
    install -m 0644 ${S}/foo/c/*.* ${D}/foo/c

    install -d ${D}/bar
    install -m 0644 ${S}/bar/*.* ${D}/bar

    install -d ${D}/bar/a
    install -m 0644 ${S}/bar/a/*.* ${D}/bar/a

    install -d ${D}/bar/a/bananas
    install -m 0644 ${S}/bar/a/bananas/*.* ${D}/bar/a/bananas
}

To something more like this pseudocode:
do_install() {
    for each subdir in ${S}/foo/
        install subdir recursively to ${D}/foo/subdir
    end

    for each subdir in ${S}/bar/
        install subdir recursively to ${D}/bar/subdir
    end
}

The top-level directories in our source files (foo & bar in the above example) rarely change, so calling them out in the recipe is fine. It's the lower level directories that are frequently changing.
It may be that cp -r ends up being the way to go, but I believe I've read that it's frowned upon in BitBake recipes, so I'm wondering if BitBake provides some alternate mechanism, or if there's
some other reasonably standardized way to do this.

A: We used to do it in that way:
do_install() {
find ${WORKDIR}/ -type f -exec 'install -m 0755 "{}" ${D}/var/www/' \;
}

A: The canonical form in OE is
cp -R --no-dereference --preserve=mode,links -v SOURCE DESTINATION

see the answer here (while they looks a bit different in code, the questions are semantically equivalent)


text:
Q: Error while performing ionic platform add android command in ionic I have installed nvm, and then perform following commands respectively as mentioned on ionic website
npm install -g cordova ionic
ionic start myApp tabs

and finally
cd myApp
ionic platform add ios

I have not used sudo(root user) while installing above commands in Ubuntu 16.04
I am getting following errors.
Error: Failed to fetch platform android
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
Error: EPERM: operation not permitted, utime '/home/dell/.cordova/lib/npm_cache/cordova-android/5.2.2/package/.npmignore'


text:
Q: Path to 3d Mathematics programming, where to start? This might read like duplicate of this question https://math.stackexchange.com/search?q=where+to+start
However since that one wasn't answered, and I have a more specific problem in regards to learning what I want to learn, I feel it was worth while to ask the question anyway.
My last hurdle to becoming a hireable game programmer is the the application of 3D mathematics in graphics programming. While I have no problems using simpler math while programming basic games and understanding how to use the 3D math libraries already present in other engines, every time I get a around actually doing matrix calculations myself and other complex calculations I find myself at a brick wall.  There have been a few times where I was able to briefly learn and apply 3d Mathematics but it didn't last that long and I find myself once a again stuck.
It feel my understanding of mathematics is only skin deep because of this. There may be something missing in my understanding of mathematics thus far, as often when I look up a lengthy equation or algorithm, I get overwhelmed with the all the symbols. Obviously this doesn't help me in understanding 3D mathematics at all.
So, does anyone know about how I can rectify this, not just in 3D mathematics. (I've already accumulated my own resources for this but I can't easily read through it because the amount of mathematics don't I know) Are there any books, articles, blogs or websites that can deepen my understanding enough so that I won't forget 3d mathematics again. This includes prerequisites just before the 3D mathematics and also sites that can help me practice. I already know about Khan Academy, however I would prefer a written version as I can get through those quicker. And also If you know of any books in kindle or eReader format that really help, as I hate reading lengthy texts on the computer screen.
Thank you!

A: If you wish to learn how to make 3d graphics to use in an existing game engine, you won't need more than very basic maths.
However, if you wish to develop game engines, you will need linear algebra, vector calculus and graph theory skills, and you will need to learn how to program!
Calculus' applications in game development are extensive. Physics is a typical example.
Graph theory is what you will crucially need. It underpins the theory of algorithms and data structures used in complicated software engineering. Algorithms such as Dijkstra's and Prim's are essential graph theory for software engineering.
Some nice introductory books are:
Thomas H. Cormen - Introduction To Algorithms, MIT Press.
R. Balakrishnan, K. Ranganathan - A Textbook of Graph Theory, Springer.

A: The best way to learn hands down is to read the code of an open source 3D framework. See how they implement all of the different operations. Try running one of their basic examples, and put breakpoints in the code to see how it gets executed.
To get started, check out Three.js. It's a very popular JavaScript 3D engine, and by reading the code you can get a good sense of how to implement everything.

*

*https://github.com/mrdoob/three.js (such as three.js/src/math)

To find frameworks in other languages, just search on GitHub. By far the best way to learn how to use math in programming. Much much better than any book.


text:
Q: why is the slug not saved in Strapi? there is a video content type field in which there is a link slug, and when a new video is created, in the get request we get a null slug. tell me what's the matter. didn't install slugify
docs

A: getting stuck at getting {slug : null} after api call in strapi?
ok, this is what I did
I made a variable before POST request based on one of my form fields (eg:name field)
my formValues is an object with values of form fields like this
 formValues = {name:"whatever" , decsription:"whatever"}
make a variable:
const slug = formValues.name.split(" ").join("-") + "-" + Math.random();
now we might have same names, so that's why I used a random value (you might want to use uuid or something like that)
then you send it like this
const res = await axios.post(`${API_URL}/api/events`,{...formValues, slug });
// you may not need to send an object with the shape like this
// but the point is you concat your custom slug to the object you want to send

notice I'm adding a custom slug from frontend which is somehow random but based off of one of the fields, but it doesn't really matter, right now strapi does not have any documentation about this common problem, it seems like the best solution might be usingstrapi-plugin-slugify but if that didn't work for you feel free to use my solution


text:
Q: Using a batch script to put files in a new folder named after them, how can I make it ignore everything between an underscore and a period? Here is the code I'm using:
  @echo off
    for %%a in (*.*) do (
        md "%%~na" 2>nul
        move "%%a" "%%~na"
    )

If the files were named the same way, but with different extensions, it works fine.  But my files look like this:
MS394-19-1872.tif
MS394-19-1872_mods.xml
MS394-19-1872_dc.xml
MS371-01-05-012A.tif
MS371-01-05-012A_mods.xml
MS371-01-05-012A_dc.xml
I need them grouped in folders that are named using everything before the "." OR the "_" and everything thrown into folders matching that, so that each folder holds any file that has that first part in it:
MS371-01-05-012A contains 3 files
MS394-19-1872 contains 3 files
Alternatively, I can come up with another way to name the files, such as MS394-19-1872.mods.xml if that helps.

A: My comment as an answer:
@For /F "EOL=_Delims=_" %%A In ('Dir /B/A-D-S-L 2^>NUL')Do @If /I Not "%%~nxA"=="%~nx0" MD "%%~nA" 2>NUL&If Exist "%%A*" Move "%%A*" "%%~nA"

Please note that if your naming structure changes, this may no longer be effective. Also your batch file must not be named with an underscore.


text:
Q: Using tuples to remove duplicate coordinates from a list in VBA I have two arrays filled with X and Y values. The values are pulled from text boxes the user fills.
These values (x1,y1), (y1,y2), (x_nth, y_nth) are plotted, where n is the number of points in my arrays.
I want to run through these coordinate pairs and find the ones that overlap each other. Once I find an overlapping point identified then I can change the duplicate(s) marker size to be bigger so the reader can see how often a point is repeated. Right now I just want to accomplish the former.
I'm not familiar with VBA I work mainly in Python. Below is my example code that works in python.
x = [1,2,2,4,5,5,5]
y = [1,3,3,4,5,5,5]
pts = []
for i in range(len(x)):
    cX = x[i]
    cY = y[i]
    if (cX, cY) in pts:
        print("duplicate")
        print(cX, cY)
        #plot this point on scatter
        #increase marker size for this particular point
    else:
        pts.append((cX, cY))
print(pts)

Output
Duplicate
2 3
Duplicate
5 5
Duplicate
5 5
[(1,1), (2, 3), (4,4), (5,5)]

A: I just threw this together real quick, but it does the job. Python does a better job working with data than vba (more data types like lists and tuples). There are a few ways to make this happen, I just chose to use a 2 dimensional array.
Dim array_Tuple() As Variant, i As Integer, xsplit, ysplit
Dim sLength As Integer, x As String, y As String, v
Dim bool As Boolean

x = "1,2,2,4,5,5,5"
y = "1,3,3,4,5,5,5"

xsplit = Split(x, ",")
ysplit = Split(y, ",")
count = 0

On Error Resume Next
For i = 0 To UBound(xsplit)
bool = True

    For j = 0 To count
        If xsplit(i) = array_Tuple(1, j) And ysplit(i) = array_Tuple(2, j) Then
            If Not err.Number <> 0 Then
                bool = False
            End If
            err.Clear
        End If
    Next

If bool Then
    count = count + 1
    ReDim Preserve array_Tuple(1 To 2, 1 To count)
    array_Tuple(1, count) = xsplit(i)
    array_Tuple(2, count) = ysplit(i)

    Debug.Print array_Tuple(1, count) & "," & array_Tuple(2, count)
End If

Next
On Error GoTo 0


text:
Q: Fairly Basic String Expansion in Python? I am trying to create a function that will take a 'compressed' string, for example
'a12b3c'

and return its 'expanded' form, which for this example would be
'aaaaaaaaaaaabbbc'

Each character is supposed to be repeated as many times as the following number or just one time if no number follows the character.
I have been able to create a function that will do this if the number values in the 'compressed' string are only single-digit numbers, so my attempt works for strings like
'a3b2c6'

but I can't seem to find a way to take into account the case where the number values are more than a single digit long.

A: Use a regular expression:
>>> import re
>>> compressed = "a12b3c"
>>> expanded = ""
>>> for char, count in re.findall(r'(\w)(\d+)?', compressed):
...     count = int(count or 1)
...     expanded += char*count
...
>>> expanded
'aaaaaaaaaaaabbbc'

A: Here's a oneliner with a generator expression:
>>> import re
>>> s = 'a12b3c'
>>> ''.join(x*int(y or 1) for x,y in re.findall('(\w)(\d*)', s))
'aaaaaaaaaaaabbbc'


text:
Q: Volume of a neighborhood of singular matrices Suppose we take the set of all $n\times n$ real matrices with entries in $[0,1]$ in Euclidean space.  Let $N_\epsilon$ be the $\epsilon$ neighborhood of the set of all singular matrices in this space, i.e. $N_\epsilon = \cup_{A:\det(A)=0} B_\epsilon(A)$.
Is there a simple way to compute or upper-bound the volume of $N_\epsilon$ in terms of $n$ and $\epsilon$?


text:
Q: Opencart "sent" message How can we edit the "SENT" (javascript alert) that is generated after the customer sends a message? For example, "Thank you very much for your message, we will get back to you as soon as possible."

A: You can use following code.

JavaScript Alert

<button onclick="myFunction()">Try it</button>

i think it's very helpful for you.


text:
Q: .htaccess единая точка входа Подскажите, пожалуйста, как сделать, чтобы при указании в урле любой ссылки (например, localhost/example) всегда перенаправляло на localhost/index.php, но в адресной строке так и оставалось localhost/example?

A: вот так можно через htaccess
RewriteRule ^localhost/example$    /localhost/index.php [QSA,L]

RewriteRule ^localhost/example$    /localhost/index.php?task=example [QSA,L]

вторая строка - пример как можно передать параметр дополнительный

A: RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [QSA,L]


text:
Q: Material Angular Accordion header/title height So I've been trying to adopt Materials Accordion in my Web Application development.
However having some troubles getting the header to expand in size as the content grows.
My header is expected to have quite a few number of lines to give a summary and not just a 1 liner.
If I hard-code the material header height it causes the animation to go hay-wire.
Below is a sample code
<mat-accordion [displayMode]="displayMode" [multi]="multi" class="mat-expansion-demo-width">
    <mat-expansion-panel #panel1 [hideToggle]="hideToggle">
        <mat-expansion-panel-header>Section 1</mat-expansion-panel-header>

This is the content text that makes sense here.

    </mat-expansion-panel>
</mat-accordion>

::ng-deep .mat-expansion-panel-header
{
    height: 190px !important;
}

If I do the above the height gets set, but the animation for expand and collapse goes weird.
How should I go about this?

A: Adding a general options/settings to set height for all panels across application:
MatExpansionPanelDefaultOptions
import { NgModule } from '@angular/core';
import { MAT_EXPANSION_PANEL_DEFAULT_OPTIONS } from '@angular/material';

@NgModule({
    providers: [
        {
            provide: MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
            useValue: {
                hideToggle: true,
                expandedHeight: '50px',
                collapsedHeight: '50px'
            }
        }
    ]
})
export class AppMaterialModule {}

A: As of today with Material 7.0.2, If you want to have the header follow some generic height:auto rule, this fix height might not be your solution. (for instance to follow the size of the text in the header in responsive situations)

in these situations, it's much better to have an auto height defined in css:
  mat-expansion-panel {
    mat-expansion-panel-header {
      height: auto!important;
    }
  }

and define
  <mat-expansion-panel-header collapsedHeight="*" expandedHeight="*">

as explained in https://github.com/angular/material2/pull/9313

A: That's what workerd for me, no css simply adding thowe to mat-expansion-panel-header
<mat-expansion-panel-header [collapsedHeight]="'auto'" [expandedHeight]="'auto'">

A: You dont have to use ::ng-deep. You can use [collapsedHeight] and [expandedHeight] on your mat-expansion-panel-header.
<mat-accordion [displayMode]="displayMode" [multi]="multi" class="mat-expansion-demo-width">
    <mat-expansion-panel #panel1 [hideToggle]="hideToggle">
        <mat-expansion-panel-header [collapsedHeight]="'190px'" [expandedHeight]="'190px'">
            Section 1
        </mat-expansion-panel-header>

This is the content text that makes sense here.

    </mat-expansion-panel>
</mat-accordion>

Link to StackBlitz Demo.

A: For Material 15, adding the following to the component CSS mimics the default padding, with a height that allows the content to be completely visible:
.mat-expansion-panel-header {
  height: auto;
  padding: 12px 24px; /* replacing with 1em looks fine to me */
}

A: To have multiple lines in a panel header, I just used display: flex; flex-direction:column on the header and it worked just fine.


text:
Q: Html table tie column widths together I have a table with a fixed number of columns. I would like 3 of the columns to have the same width, but I don't know what it is, as I don't know the width of the other 2. I want the browser to render it as best it can with the one constraint that my three designated columns all have the same width,
Here's an example. I would like columns 2,3,4 all to have the same width, I don't mind what it is, just that they are the same.

    Could be short or maybe it could be long
    Col2 Long Text
    Col3 Some More Long Text
    Col4 Some More Long Text and a bit more on top
    Could be short or long

I can only do something like I want by having a fixed percentage
td.samewidth {
  width: 25%;
  overflow: hidden;
}

Here's a fiddle with the best I could do which ties the three columns to have a width of 25%.
https://jsfiddle.net/GrimRob/zugnyzb4/
What I ideally want to do is get rid of width: 25% and put something in its place, but what?

A: Do it like this:
td.samewidth {
  width: 33%;
  overflow: hidden;
}

    Could be short or maybe it could be long

          Col2 Long Text
          Col3 Some More Long Text
          Col4 Some More Long Text and a bit more on top

    Could be short or long

Since your "samewidh" columns will be 33% fixed, you won't have trouble with other rows misaligning. At most you'll have to add !important.

A: Hard to arrive at a set answer for your question, since I am not exactly sure how you want the columns to resize based on content.  Flexbox could be an alternative for you. Here is the CSS and a Codepen illustrating, to as best I understood, what you are trying to accomplish.
table {
  width: 100%;
  border: 1px solid black;
}

tr {
  display: flex;
}

td {
  border: 1px solid black;
}

td.samewidth {
/*   width: 25%; */
  overflow: hidden;
  flex-grow: 1;
  display: inline-block;
  flex-basis: 0;
}

td:not(.samewidth) {
  flex-basis: content;
}

http://codepen.io/anon/pen/bpobGq
In this example, columns 1 and 5 (not samewidth) determine width based off of the content provided. Columns with the .samewidth class, will grow evenly to fill up the remaining space available in the parent container (in this case the tr).
You really have a lot of options here with how you'd want the columns to resize. You could set a fixed width for columns 1 and 5, size off of content (as in example), or have those grow to fill up space as well. Hopefully this gets you on the right path.
Here's a quick guide on Flexbox. https://css-tricks.com/snippets/css/a-guide-to-flexbox/


text:
Q: fireEvent.Blur() is not working in my custom input component // Custom Input component

const Container = styled.div``;

const InputBase = styled.div<{ width: string }>`
  display: flex;
  width: ${(props) => props.width};
  height: 42px;
  justify-content: space-between;
  align-items: center;
  padding: 9px 10px;
  border-radius: 8px;
  border: solid 2px ${color.gray[200]};
  background-color: white;

  &[data-focus="true"] {
    border: solid 2px ${color.gray[300]};
  }

  &[data-disabled="true"] {
    background-color: ${color.background.original};
  }
`;

const InputArea = styled.input`
  width: 100%;
  border: 0;
  background-color: inherit;
  font-size: 15px;
  font-weight: normal;

  &:focus {
    outline: none;
  }
  &:disabled {
    color: ${color.gray[600]};
  }
  ::placeholder {
    color: ${color.gray[600]};
  }
`;

const Label = styled.label`
  color: ${color.gray[600]};
  font-size: 15px;
  font-weight: bold;
  display: inline-block;
  margin-bottom: 10px;
`;

const Input: ForwardRefRenderFunction<HTMLInputElement, Props> = (
  { formWidth = "100%", icon = null, labelText, onFocus, onBlur, ...props },
  ref
) => {
  const [isFocus, setIsFocus] = useState<boolean>(false);

  const handelFocus = (e) => {
    setIsFocus(true);

    if (onFocus) onFocus(e);
  };

  const handleBlur = (e) => {
    setIsFocus(false);

    if (onBlur) onBlur(e);
  };

  return (
    <Container>
      {labelText && <Label htmlFor={props.id}>{labelText}</Label>}
      <InputBase
        data-focus={isFocus}
        data-disabled={props.disabled}
        width={formWidth}
      >
        <InputArea
          ref={ref}
          type="text"
          {...props}
          onFocus={handelFocus}
          onBlur={handleBlur}
        />
        {icon}
      </InputBase>
    </Container>
  );
};

export default forwardRef(Input);

I'm making the component into a library and using it in another project.
The code below works normally when testing in the library.
describe("Input", () => {
  it("test", async () => {
    const handleBlur = jest.fn();

    render(
      <Input data-testid="input" onBlur={handleBlur} />
    );

    const input = screen.getByTestId("input") as HTMLInputElement;

    fireEvent.change(input, { target: { value: "test" } });
    fireEvent.blur(input);

    expect(handleBlur).toHaveBeenCalledTimes(1);
  });
});

However, in other projects that use that library, fireEvent.blur(input) does not work (toHaveBeenCalledTime is 0) and fireEvent.focusOut(input) does.
Is there something wrong with the library bundling process? Or is there something I'm missing?


text:
Q: Matlab split into train/valid/test set and keep proportion I have dataset with 12 columns + 1 target (binary) and about 4000 rows. I need to split it into train (70%), validation (20%) and test (10%) set.
The dataset is quite undersampled (95% of class 0 to 5% of class 1) so I need to keep the ratio of target in each sample.
I am able to split the dataset somehow, but I have no idea how to keep the ratio.
I am working with subset Wine Quality data here

A: If you have access to Matlab's Statistical processing toolbox you can used the cvpartition
function.
From matlab help on cvpartition -:

c = cvpartition(group,'HoldOut',p) randomly partitions observations into a training set and a test set with stratification, using the class information in group; that is, both training and test sets have roughly the same class proportions as in group.

You can apply the function twice to get three partitions. This function preserves the original class distribution.

A: So far I came up with this, if anyone knows better solution, let me know.
I split my dataset by target column, then each of those two splits were further split into first 70%, next 20% and last 10% data and then merged together.
After, I split features and targets.
%split in 0/1 samples
winedataset_0 = winedataset(winedataset(:, 13) == 0, :);
winedataset_1 = winedataset(winedataset(:, 13) == 1, :);

%train
split_tr_0 = round(length(winedataset_0)*0.7);
split_tr_1 = round(length(winedataset_1)*0.7);
train_0 = winedataset_0(1:split_tr_0,:);
train_1 = winedataset_1(1:split_tr_1,:);
train_set = vertcat(train_0, train_1);
train_set = train_set(randperm(length(train_set)),:);

%valid
split_valid_0 = split_tr_0 + round(length(winedataset_0)*0.2);
split_valid_1 = split_tr_1 + round(length(winedataset_1)*0.2);
valid_0 = winedataset_0(split_tr_0+1:split_valid_0,:);
valid_1 = winedataset_1(split_tr_1+1:split_valid_1,:);
valid_set = vertcat(valid_0, valid_1);
valid_set = valid_set(randperm(length(valid_set)),:);

%test
test_0 = winedataset_0(split_valid_0+1:end,:);
test_1 = winedataset_1(split_valid_1+1:end,:);
test_set = vertcat(test_0, test_1);
test_set = test_set(randperm(length(test_set)),:);

%Split into X and y
X_train = train_set(:,1:12);
y_train = train_set(:,13);

X_valid = valid_set(:,1:12);
y_valid = valid_set(:,13);

X_test = test_set(:,1:12);
y_test = test_set(:,13);


text:
Q: Notification count doesn't match displayed number of notifications I think this is a bit of a disconnect:

The badge number is telling me that there should be 12 items to review, while the notification list only displays 4 new items.
That creates a very confusing UX.  It's like having a mail client that says "12 new messages", but then only lets you see 4 of them.  You're liable to drive yourself insane trying to find the "missing" 8 messages.
After looking into the notifications, it appears that what happened is that the notification list merged multiple comment notifications into a single notification.  That's fine, in and of itself, but I think the count also needs to be updated to reflect the merge operation (or else the merged item needs to clearly indicate that it's standing in for multiple notifications).
Specifically, I think that either:

*

*When multiple notification events are merged into a single inbox item, the count displayed in the badge should be reduced by a corresponding amount so that the count always exactly matches the number of inbox items.

Or

*When multiple notification events are merged into a single inbox item, the inbox item should clearly indicate how many separate events it is standing in for.  So for instance, if 9 comments have been merged into a single item in the inbox, then call that item "9 comments" instead of "comment".

Bottom Line
The notification count and the number of unread inbox items should always match, if not by simple 1:1 correspondence then by having a clear indication of how much each item contributes to the total notification count.


text:
Q: Is it possible to constrain a scrolling element's height by its container? I have a containing div that is constrained in its height and width.  It has 2 child elements.
The first child can be of variable height (as the text within it can wrap, and this is desired behavior).
The second child is a div wrapping a table.  The div is set to overflow-y: scroll, so it is meant to fill the remaining height of its container, and provide scrolling for the rest of its inner table when it doesn't completely fit.
Here's a simple view of the structure:

    ...

      ...

Despite my tinkering, I can never get the second child, the scrollingTable div, to constrain itself to the limits provided by the container.  Using height:100% doesn't FILL the remaining container height, but sets the height to the container's exact height (300px), which is too much because the headerArea takes up space too.
If the height of the headerArea was fixed, I could specify the scrollingTable's size as 300 - heightOfHeaderArea, but as mentioned above the headerArea's height is NOT fixed.
I'm likely going to have to use JQuery to resize the scrollingTable to the specified height, but I am curious if there is a pure css solution.
Any suggestions, or is this impossible without fixing the headerArea's height?

A: You can't do this with css alone. You have to give the scrolling div a height for it to be able to scroll (100% or fixed value).
http://jsfiddle.net/tUrTu/
This can be achieved though with javascript :
http://jsfiddle.net/tUrTu/2/
Hope it helps.

A: If you set the scrollTable to 100% it will inherit the 300px from the container div and go outside of the container div regardless of the fixed height you set to headerArea
You shall use Javascript to dynamically generate the height, but beware the sequence of the code must be HTML -> Javascript -> CSS.
code:

        ...

              ...


text:
Q: Alternative interpretation of Off-shell internal QFT propagators? In Quantum Field Theory in a (1, D - 1) space-time, to calculate transition amplitudes, we are using Feynman diagrams, where internal lines (internal propagators) corresponds to momenta which are said to be off-shell : $p^2 \neq 0$.
Is it posssible to interpret these momenta as on-shell, but within (2) space-time(s), with a supplementary dimension ?

For instance, consider a  massless (1,3) space-time Quantum Field Theory, like pure Yang-Mills theory (gluons only).
External legs corresponds to on-shell momenta $p^2 = (p_o)^2 - (p_1)^2 - (p_2)^2 - (p_3)^2 = 0$
Internal lines correspond to (1, 3) off-shell momenta, but there are 2 possibilites,
$p^2 >= 0$ and $p^2 <= 0$.
For $p^2 >= 0$, a (1, 4) on-shell condition could be written :
$$ (p_o)^2 - (p_1)^2 - (p_2)^2 - (p_3)^2  - (p_4)^2 = 0$$
For $p^2 <= 0$, a (2, 3) on-shell condition could be written :
$$ (p_{-1})^2 + (p_o)^2 - (p_1)^2 - (p_2)^2 - (p_3)^2  = 0$$
So, we could consider than free particles (on-shell external legs) live in a (1, 3) space-time, but than "interactive" particles (off-shell internal lines), live in 2 "interaction" space-times, which have signatures (1, 4) and (2, 3).
So we could say, that in fact, everything is on-shell, but interaction make one supplementary dimension appears (depending on the value of $p^2$, this is a time-like or space-like dimension).
Another way to say it, is that free particles could live on a space-time which could be the intersection of 2 "interaction" space-times.
A even more interesting model would be that free particles live in a space-time which would be the boundary of some "interaction" space-time.


text:
Q: How to show the vertical bar on the left side of code block in Visual Studio? (see the figure to get the idea) Screenshot

Question
I noticed some people can show the left bar as shown above.
How to do that?

A: There's a very useful free add-on for Visual Studio called CodeRush Express which will do this.
http://community.devexpress.com/blogs/markmiller/archive/2009/06/25/coderush-xpress-for-c-and-visual-basic-2008.aspx  (Scroll to the 'Structural Highlighting' bit to see a screenshot of it).
http://www.codekana.com/ is another add-on that does a similar thing.


text:
Q: Instant update of basic cloudbees java application run locally Trying to run basic java application (backbone.js and jax-rs) I was pleasantly surprised that modifying js or html file in src/main does not require application rebuild. Just refreshing it in browser is enough to update the application.
However changing java file, I can't find how to make application be updated locally.
Using Eclipse it's automatically compiled into target/classes, however applicaiton is not updated in browser. I can't find any bees command to cause update. I don't see compile command also.
Killing running tomcat and 'bees run' makes the trick, but the question is, if instant update is possible in case of basic java web application?

A: I'm not sure how to do it with a normal Java app. One option would be to use Playframework has this auto-reloading stuff built in, and is supported well on CloudBees. http://wiki.cloudbees.com/bin/view/RUN/Playframework

A: You need to use something like JavaRebel or Javeleon if you wish to reload Java classes in a running application.


text:
Q: javascript google map empty gray background when zoomed to zero Am using google map javascript for my hybrid webview app. When i zoom out map till 0, it will show gray area while map tiles will be on center of the screen.
Is there any way i can fix this to avoid the gray area?
I have tried using map tile image for background but is noticeable when you move map. I have also tried setting minZoom to 2, but still if i scroll map the gray area will be visible.
Or is it possible to prevent scrolling map area when zoom is '2`?
MinZoom default

MinZoom 2

I tried below also but after zooming out, it doesn't allow me to zoom in back.
google.maps.event.addListener(map, 'zoom_changed', function(){
    map.setOptions({draggable: ((map.getZoom() < 3) ? false : true)});
});

And also this, but the else statement doesn't get called.
google.maps.event.addListener(map, 'zoom_changed', function(){
        if(map.getZoom() < 3){
            document.getElementById('mapCanvas').setAttribute("style", "pointer-events: none;");
        }else{
            document.getElementById('mapCanvas').removeAttribute("style");
        }
    });

A: You can find the real north and south edges of the map.
Then use a MapRestriction to prevent the map from panning outside the defined area.
Apply the calculated result to the north and south parameters of the restriction. Set west: -180 and east: 180 to apply a latitude only restriction.
Set strictBounds: true to strictly restrict to the given bounds, even when zooming out.

function initMap() {

  var maxLat = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
  var myLatLng = new google.maps.LatLng(-24, 123);
  var mapOptions = {
    zoom: 2,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    restriction: {
      latLngBounds: {north: maxLat, south: -maxLat, west: -180, east: 180},
      strictBounds: true
    },
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
#map-canvas {
  height: 110px;
}


text:
Q: Обновить данные с проверкой их изменения Есть переменная changed, которая определяет, было ли обновление переменной data:
const auto new_data = get_new_data();
changed = data != new_data;
data = new_data;

Можно ли переписать этот кусок кода проще? Например, без промежуточной переменной new_data? Валиден ли следующий вариант или это UB из-за непонятного порядка выполнения?
changed = std::exchange(data, get_new_data()) == data;

Проверка правильности обновлений.


text:
Q: Formating a date in the text of a label inside a form view I want to know if there's a easier way to format a label that is inside a form view, the code I use is this one, it's inside the event form view databound:
protected void FormView2_DataBound(object sender, EventArgs e)
{
    if (FormView2.CurrentMode == FormViewMode.Edit)
    {
        Label DAT_Label1 = (Label)FormView2.FindControl("DAT_Label1");
        if (DAT_Label1 != null)
        {
            DateTime date = Convert.ToDateTime(DAT_Label1.Text);
            DAT_Label1.Text = string.Format("{0:dd/MM/yyyy}", date);
        }
    }
}

Is there no attribute in the label control that can help making this formating?

A: There is the standard Short Date format specifier which is marginally less verbose than your code, but does have the advantage that it uses the users formatting style, so would display dd/mm/yyyy in the UK or mm/dd/yyyy if the locale is set to US
protected void FormView2_DataBound(object sender, EventArgs e)
{
if (FormView2.CurrentMode == FormViewMode.Edit)
{
    Label DAT_Label1 = (Label)FormView2.FindControl("DAT_Label1");
    if (DAT_Label1 != null)
    {
        DateTime date = Convert.ToDateTime(DAT_Label1.Text);
        DAT_Label1.Text = string.Format("{0:d}", date);
    }
}

}


text:
Q: DataGridView.DataSource does not have new row from the grid (.NET) I have a datagridview which is initially bound to an empty datatable. Then the first row is populated by setting values to the columns of the grid's CurrentRow.DataBoundItem row.
I enter a new row manually by typing values in the last blank row. I hit a save button which does:
DataTable dt = (DataTable)MyGrid.DataSource.......
I noticed the number of rows in dt is only 1 instead of the two showing in the grid. However if I hit the Enter key first on the row and then click save, the number of rows is 3. The two filled rows plus the new row caused by the Enter key.
How do I get the two rows placed in the datatable without hitting the Enter key? (I don't want to programmatically send an Enter keystroke)
I tried to call the EndEdit() and UpdateCellValue() to accept the new row but the datasource still shows only one row.

A: if you are talking about windows Apllication as i think, you can just add ds.AcceptChanges();
 if (txtUserId.Text.Trim() != "" && txtPasswoed.Text.Trim() != "" && txtUserName.Text.Trim() != "")
            {
                DataRow r = ds.Tables[0].NewRow();
                r["userName"] = txtUserName.Text.Trim();
                r["ID"] = txtUserId.Text.Trim();
                r["Password"] = txtPasswoed.Text.Trim();
                ds.Tables[0].Rows.Add(r);

                ds.AcceptChanges();

                txtPasswoed.Clear();
                txtUserName.Clear();
                txtUserId.Clear();
            }

A: I answered a similar question recently, you should use Form.Validate() to push data back to the underlying business object (your DataTable) before saving your changes to the database.

A: As Jason mentioned make sure you're rebinding the grid after you insert into your DataTable.
myGrid.DataSource = dt;
myGrid.DataBind(); <-----

A: I had to add a binding source which the grid binds to instead of binding to a datatable.