text:
Q: How can I extend LVM volume online I would like to extend /dev/sda2 with the free space on /dev/sda without using a CD.
fdisk -l output
[root@ip126 ~]# fdisk -l

Disk /dev/sda: 26.8 GB, 26843545600 bytes
64 heads, 32 sectors/track, 25600 cylinders
Units = cylinders of 2048 * 512 = 1048576 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00086c7a

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           2         501      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2             502       10240     9972736   8e  Linux LVM
Partition 2 does not end on cylinder boundary.

Disk /dev/mapper/VolGroup-lv_root: 9168 MB, 9168748544 bytes
255 heads, 63 sectors/track, 1114 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/VolGroup-lv_swap: 1040 MB, 1040187392 bytes
255 heads, 63 sectors/track, 126 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

pvdisplay output
[root@ip126 ~]# pvdisplay
  --- Physical volume ---
  PV Name               /dev/sda2
  VG Name               VolGroup
  PV Size               9.51 GiB / not usable 3.00 MiB
  Allocatable           yes (but full)
  PE Size               4.00 MiB
  Total PE              2434
  Free PE               0
  Allocated PE          2434
  PV UUID               2lmvRB-u3AL-DYAX-2Azh-HsHE-skwW-3hewTE

vgdisplay output
[root@ip126 ~]# vgdisplay
  --- Volume group ---
  VG Name               VolGroup
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               9.51 GiB
  PE Size               4.00 MiB
  Total PE              2434
  Alloc PE / Size       2434 / 9.51 GiB
  Free  PE / Size       0 / 0
  VG UUID               tp0a2o-Hkup-3V0m-01K1-udfY-Y2l2-gTMHjg

lvdisplay output
[root@ip126 ~]# lvdisplay
  --- Logical volume ---
  LV Path                /dev/VolGroup/lv_root
  LV Name                lv_root
  VG Name                VolGroup
  LV UUID                9xV22O-69gz-fib7-t3tF-ksqc-LWhj-KLYful
  LV Write Access        read/write
  LV Creation host, time localhost.localdomain, 2018-05-23 09:31:01 -0400
  LV Status              available
  # open                 1
  LV Size                8.54 GiB
  Current LE             2186
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:0

  --- Logical volume ---
  LV Path                /dev/VolGroup/lv_swap
  LV Name                lv_swap
  VG Name                VolGroup
  LV UUID                0iRAF9-rF8Y-kpn2-rPyV-fnAW-Q2vq-aK2ODT
  LV Write Access        read/write
  LV Creation host, time localhost.localdomain, 2018-05-23 09:31:02 -0400
  LV Status              available
  # open                 1
  LV Size                992.00 MiB
  Current LE             248
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:1

A: *

*Make sure that you have up to date backups of the data which you may want to keep. Never mess with filesystems, logical volumes, volume groups, physical volumes and partitions without having a backup of the data.
Then read and understand the manual pages for the utilities mentioned in this answer. Only proceed when you are confident that you understood the process.
What you really want is to extend the filesystem. In order to extend the filesystem you must extend the logical volume on which it resides. In order to extend the logical volume you must extend the volume group.

*You have two options; you can either make a new physical volume and add it to the volume group, or you can extend the partition and resize the physical volume.

*

*Using fdisk or parted or gparted or whatever make a new partition covering the free space on the disk.

*Create a new LVM physical volume on the new partition using pvcreate. Check that you did it correctly using pvs or pvdisplay.

*Add the new physical volume to the volume group using vgextend. Check that you did it correctly using vgs or vgdisplay.
Or, if you prefer, you can extend the partition and the physical volume:

*

*Extend the partition to the end of the disk using parted:
sudo parted /dev/sda resizepart 2 -1s

*Extend the physical volume to cover the newly extended partition using pvresize.

*Extend the logical volume using lvextend. Check that you did it correctly using lvs or lvdisplay.

*If needed, extend the filesystem into the newly available space. Use the appropriate utility for the specific filesystem; for example, for Ext4 you would use resize2fs.


text:
Q: Can we use CloudWatch for monitoring apps outside AWS? Say I have few applications running on physical machines which are not part of AWS infra, is it possible for such applications to publish metrics to cloudwatch and use its alerting mechanism?
Docs do not mention this case, and it seems that CloudWatch CLIs just take metrics as arguments and probably derive the AWS instance ID and send the metric to CloudWatch.

A: It is possible to use CloudWatch to record custom metrics even if your apps do not run on the AWS EC2 infrastructure. See this blog post that announces the introduction of custom metrics (in 2011) and the CloudWatch custom metrics documentation for more details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can QGIS open KMZ files? I know I can add KML files once I have unzipped the KMZ files, but is there a way to open KMZ files directly?
When I try to open a kmz file on QGIS 1.8.0 on Windows XP, through the all files filter, it does not accept it as a valid format.
Am I doing something wrong?
Does this all depend on OGR support?

A: Here is a guide to create and import KML files into Quantum. It does not work for KMZ files so these would need to first be decompressed to be used in this manner.

A: On a Mac, where QGIS uses the Kyngchaos.com GDAL 1.9 Complete framework, or on any platform where QGIS has been compiled against a GDAL build with support for the Google LIBKML driver, you can open .kmz files directly using the open dialog and selecting the All Files (*) option, or simply drag/drop onto QGIS. (Otherwise, you will need to decompress the .kmz to .kml files as noted by @Kurt)

If the .kmz has multiple layers, you will be presented with a layer selection dialog (single layer .kmz files are immediately loaded):

You can select multiple layers in that dialog to import. The Example Overlay of Multiple Datasets .kmz file I tested (from here) allowed multiple layer import of point, line and polygon layer types.

EDIT: You can check for ogr LIBKML driver support in your version of QGIS by running the following commands in QGIS's Python Console:
import osgeo.ogr
print 'Has LIBKML ogr driver: ' + str(osgeo.ogr.GetDriverByName('LIBKML') is not None)

A: You can add kml layers as any other kind of vector layer, using the "add vector" dialog.

A: Once you have opened the KML file in QGIS, you can also save it as a shapefile by right-clicking on the file in the layers pane and selecting 'save as'.

A: as far as I know, you are right: vectors in qgis  are read and written by ogr. qgis 1.8 uses the lastest gdal/ogr, which is 1.91. you can read zipped shape-files, but *.kmz, which actually are a zip-archive containing *.kml-file(s) need to be unzipped manually before importing

A: Rename datafile.kmz to datafile.zip then unzip the *.kml from inside.

A: I have QGIS 2.18 and you can add a *.kmz file.

A: First Open In Google Earth And Save As Kml Format File and That
you will open in QGIS 1.8....
open Vector Data File Change kml format...

A: The solution is simple:

*

*in Google Earth, right-click on your loaded *.kmz file

*choose "save as..." and save the file as *kml

*Now, open the kml-file with QGIS
Tipp: if you want to save several *.kmz files and merge them in one sinlge *kml file, put your *.kmz files in Google Earth in one single folder in hte "locations" window of Google Earth. Than apply the procedure described above for the folder. One single *kml with all geogrpahic points in the folder will be produced, you can then open it with QGis.
If "on the fly projection" is activated, the points will show up on the right place in your OpenLayers Map in QGIS.


text:
Q: Reading objects from a file and adding them to an array I'm trying to read objects from a file then add them to an Array List of Ticket. But it's not working. May I please know where's the problem?
public void writeTicketToFile(Ticket ticket) {
    try {
        FileOutputStream fileOut = new FileOutputStream("tickets.txt");
        ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(ticket.toString());
        objectOut.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public void readTicketFromFile(){
    ArrayList<Ticket> tickets = new ArrayList<Ticket>();
    try {
        FileInputStream fi = new FileInputStream(new File("tickets.txt"));
        ObjectInputStream oi = new ObjectInputStream(fi);
        Ticket ticket;
        while (ticket=oi.readObject() != null){
            tickets.add((Ticket)oi.readObject());
        }
        System.out.println(tickets);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

A: One of your main problems lies here:
while (ticket=oi.readObject() != null){
  tickets.add((Ticket)oi.readObject());
}

Compare the fact that you're trying to read a Ticket object out of a file with the way you're writing the Ticket to the file:
objectOut.writeObject(ticket.toString());

As you can see, you're converting the Ticket to a String and writing the String to the file. Then when you try to read, you're trying to read a Ticket. Instead, you should read a String, and then convert the String into a Ticket in code.
If Ticket is serializable, you may instead just be able to remove .toString() from the write step, but I've never worked with object streams, so I can't say 100% if that will work.

A: Just add the Ticket objects into an ArrayList and write the list (instead of each object one by one) as a single object. Then read the list from the file in your readTicketFromFile() method as :
 ArrayList<Ticket> ticketsList = (ArrayList<Ticket>)oi.readObject();

A: There are a lot of issues here:
Make sure your Ticket implements Serializable interface for writing/reading objects from/to file as in this simple example:
public class Ticket implements Serializable{

private String name;
private LocalDateTime issued;

public Ticket() {
}

public Ticket(String name, LocalDateTime issued) {
    this.name = name;
    this.issued = issued;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the issued
 */
public LocalDateTime getIssued() {
    return issued;
}

/**
 * @param issued the issued to set
 */
public void setIssued(LocalDateTime issued) {
    this.issued = issued;
}

}

Now pay attention to while writing tickets to a file to write them one at a time. You can achieve it by iterating thru your list of tickets and writing it one at a time, something like:
for (int i = 0; i < tickets.size(); i++) {
                    objectOut.writeObject(tickets.get(i));
                }

Also, make sure to close your ObjectInputStream after reading as it will surely throw EOFException at the end, take a look at implementation of it in readTicketFromFile method.

public class SerializationAndDeserializationOfTicket {

    public static void main(String[] args) {
        List<Ticket> listOfTickets = new ArrayList<>();
        listOfTickets.add(new Ticket("Concert 1", LocalDateTime.now()));
        listOfTickets.add(new Ticket("Concert 2", LocalDateTime.now()));
        listOfTickets.add(new Ticket("Concert 3", LocalDateTime.now()));

        writeTicketToFile(listOfTickets);

        readTicketFromFile();
    }

    public static void writeTicketToFile(List<Ticket> tickets) {

        try {
            FileOutputStream fileOut = new FileOutputStream("tickets.txt");
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            for (int i = 0; i < tickets.size(); i++) {
                objectOut.writeObject(tickets.get(i));
            }
            objectOut.close();
        } catch (IOException e) {
            System.err.println("JVM reported an IO exception. Please, take a look.");
        }
    }

    public static void readTicketFromFile() {
        ArrayList<Ticket> tickets = new ArrayList<>();
        try {
            FileInputStream fi = new FileInputStream(new File("tickets.txt"));
            ObjectInputStream oi = new ObjectInputStream(fi);
            while (true) {
                try {

                    Ticket ticket = (Ticket) oi.readObject();
                    tickets.add(ticket);
                    System.out.println(ticket.getName() + " " + ticket.getIssued());
                } catch (EOFException ex) {
                    oi.close();
                    break;
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("JVM reported an IO/ClassNotFound exception. Please, take a look.");
    }
    }


text:
Q: Retain rows in an R dataframe which contain a specific pattern in a column df is a test dataframe in which I want to retain only the rows which contain the | character in the Hits column and the rows which contain the hits (i.e. Hit1, Hit2 etc.) and also the blank cells in the Hits column.
df <- data.frame(
 Hits = c("# test114", "# ID|987129470", "# 13135", "Hit1", "", "Hit2", "Hit3", "", "# test739", "# ID|6971324987", "# 83771", "Hit1", "Hit2", "", "Hit3"),
 Category1 = c(NA, NA, NA, 0.001, 0.001, 0.002, 0.003, 0.003, NA, NA, NA, 0.023, 0.341, 0.341, 0.569),
 Category2 = c(NA, NA, NA, 100, 100, 99, 98, 98, NA, NA, NA, 100, 95, 95, 97),
 Category3 = c(NA, NA, NA, 100, 100, 99, 98, 98, NA, NA, NA, 98, 97, 97, 92)
)

df looks like this

The output should look something like this

Since I want to retain only the rows having the | character and the ones not having the # character and the blank cells, maybe pattern matching could help. But I can't seem to figure out how to implement it in the code. Any suggestions?
Please note that in the original dataframe, the hits can have different names. Some hits don't start with the term 'Hit'

A: We could use grep with a regex pattern - "^[^#]+$|\\| (Hits column with no # from start (^) to end ($) or (|) the | character - escaped as it is metacharacter)
subset(df, grepl("^[^#]+$|\\|", Hits)|Hits == "")
              Hits Category1 Category2 Category3
2   # ID|987129470        NA        NA        NA
4             Hit1     0.001       100       100
5                      0.001       100       100
6             Hit2     0.002        99        99
7             Hit3     0.003        98        98
8                      0.003        98        98
10 # ID|6971324987        NA        NA        NA
12            Hit1     0.023       100        98
13            Hit2     0.341        95        97
14                     0.341        95        97
15            Hit3     0.569        97        92

Or do this in single grepl
> subset(df, grepl("^$|^[^#]+$|\\|", Hits))
              Hits Category1 Category2 Category3
2   # ID|987129470        NA        NA        NA
4             Hit1     0.001       100       100
5                      0.001       100       100
6             Hit2     0.002        99        99
7             Hit3     0.003        98        98
8                      0.003        98        98
10 # ID|6971324987        NA        NA        NA
12            Hit1     0.023       100        98
13            Hit2     0.341        95        97
14                     0.341        95        97
15            Hit3     0.569        97        92

or in dplyr
library(dplyr)
library(stringr)
df %>%
   filter(str_detect(Hits, "^[^#]+$|\\|")|Hits == "")
             Hits Category1 Category2 Category3
1   # ID|987129470        NA        NA        NA
2             Hit1     0.001       100       100
3                      0.001       100       100
4             Hit2     0.002        99        99
5             Hit3     0.003        98        98
6                      0.003        98        98
7  # ID|6971324987        NA        NA        NA
8             Hit1     0.023       100        98
9             Hit2     0.341        95        97
10                     0.341        95        97
11            Hit3     0.569        97        92

A: Similar to akruns solution but using no regex solution:
library(dplyr)
library(stringr)
df %>%
  filter(str_detect(Hits, 'ID|Hit'))

              Hits Category1 Category2 Category3
1   # ID|987129470        NA        NA        NA
2             Hit1     0.001       100       100
3             Hit1     0.001       100       100
4             Hit2     0.002        99        99
5             Hit3     0.003        98        98
6             Hit3     0.003        98        98
7  # ID|6971324987        NA        NA        NA
8             Hit1     0.023       100        98
9             Hit2     0.341        95        97
10            Hit2     0.341        95        97
11            Hit3     0.569        97        92

A: Another possible solution:
library(tidyverse)

df %>%
  filter(!str_detect(Hits,"(?=.*#)(?!.*\\|)"))

#>               Hits Category1 Category2 Category3
#> 1   # ID|987129470        NA        NA        NA
#> 2             Hit1     0.001       100       100
#> 3                      0.001       100       100
#> 4             Hit2     0.002        99        99
#> 5             Hit3     0.003        98        98
#> 6                      0.003        98        98
#> 7  # ID|6971324987        NA        NA        NA
#> 8             Hit1     0.023       100        98
#> 9             Hit2     0.341        95        97
#> 10                     0.341        95        97
#> 11            Hit3     0.569        97        92


text:
Q: How do I run containerized Cypress runner against containerized server? I'm trying to run Cypress tests against containerized Nginx:
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                                       NAMES
7c3efd24e6e6   tdd_nginx      "/docker-entrypoint.…"   19 minutes ago   Up 19 minutes   0.0.0.0:80->80/tcp, :::80->80/tcp           tdd_nginx_1

from official docs I learned I can use docker run -it -v $PWD:/e2e -w /e2e -e CYPRESS_baseUrl=host.docker.internal cypress/included:7.7.0
Here I learned about host.docker.internal which is how supposedly Cypress knows to look for localhost in a particular container.
Nginx container has exposed port 80 so I've tried -e CYPRESS_baseUrl=host.docker.internal:80 as well as without specifying port as port 80 is a fallback port in most cases.
error output:
Cypress could not verify that this server is running:

  > http://host.docker.internal:80

We are verifying this server because it has been configured as your `baseUrl`.

Cypress automatically waits until your server is accessible before running tests.

We will try connecting to it 3 more times...
We will try connecting to it 2 more times...
We will try connecting to it 1 more time...

Cypress failed to verify that your server is running.

Please start this server and then run Cypress again.

Moving the env variable into cypress.json made no difference:
{
  "baseUrl": "host.docker.internal",
  "video": false
}

A: Changed the cypress.json to:
{
  "CYPRESS_BASE_URL": "host.docker.internal",
  "video": false
}

parsing CYPRESS_BASE_URL as env variable didn't help but putting it into the file did the trick. Strangely, it makes difference.
Thanks goes to @jonrsharpe


text:
Q: 'Failed to execute MI command: -exec-run' error when trying to debug a GNU project with Eclipse I wish to debug GNU Emacs in Eclipse IDE for C/C++ on my macOS Sierra. I have downloaded the source code with Git and built the project successfully via the command line. I then imported the project to Eclipse as an existing Makefile project with the GNU autotools toolchain setting.
I can now run the Emacs GUI from Eclipse. However, when I try to debug it (with gdb), I get the following error message:
'Launching emacs-26.0.50.1' has encountered a problem.

Error in final launch sequence

Failed to execute MI command:
-exec-run
Error message from debugger back end:
During startup program terminated with signal ?, Unknown signal.
During startup program terminated with signal ?, Unknown signal.

A: I managed to get rid of this error by specifying the full path to the .gdbinit file in the Run > Debug Configurations... > C/C++ Application > emacs-26.0.50.1 > Debugger > GDB command file: textbox.
I now get a different error, but this is a matter for another question...

A: I had a similar error message while using the debugger for a small dummy code. I used the suggestion given in this link and got it fixed. In short, I had to change the debugger to an older one. Hope that helps if you are still having the same issue.

A: The problem for me was using USB 3.0 port. Connected board to USB 2 port and it was working fine.


text:
Q: Error when computing Gauss curvature Am trying to find constant negative Gauss curvature surface using parametrization  for a 2-D patch in 3-D space $$ (\sin u\, \cos v ,\sin u \,\sin v, f(v))$$
A solution obtained is $$ f(v) = c v \sin^2 u + d $$
c and d are constants. But it has an error ( back substitution K not constant), I am unable to find source of the same.
Please help to find it.


text:
Q: how can to use array containing c++ map I have difficulty understanding this part of a code? Is it possible to get pictorial/diagram explanation.
//test.h
typedef std::map<std::string, std::string> mType;
    static const m_Type::value_type data[] = {
        m_Type::value_type("A", "B"),
        m_Type::value_type("C", "D"),
        m_Type::value_type("E", "F")
    };
//test.cc
void test(std::map<std::string, std::string>::value_type data)
{
    cout<<data[0].first<<endl;
}
//main.cc
test(data);

In main.cc I wanted to call test() to print elements but getting error
main.cc: In function 'void test(std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >)':
main.cc:10: error: no match for 'operator[]' in 'data[0]'

A: You have to declare the function the following way
void test( const std::map<std::string, std::string>::value_type data[] )
{
    cout<<data[0].first<<endl;
}

because originally data is defined as an array that you are going to pass to the function. Otherwise you may not use the subscript operator.
Also you need to use qualifier const for the parameter because array data also is defined as a constant array.
As for this type
m_Type::value_type

then it is equivalent to std::pair<const std::string, std::string> So this declaration
static const m_Type::value_type data[] = { /*...*/ };

is equivalent to
static const std::pair<const std::string, std::string> data[] = { /*...*/ };

A: You are supposed to pass to test a value_type not the whole map.
A value_type corresponds to a pair(key, value) and is define like so in stdlib : typedef pair<const Key, Type> value_type;
therefore this data[0]makes no sense. Should be data.first


text:
Q: Querybuilder in AEM 6.2 returning different result than AEM6.0 We are working on moving some projects from AEM 6.0 and 6.2 one of the applications has an error and documentation hasn't been helpful.her is the reduced case querybuilder query
type=cq:page
path=/content/nera/en/experts
p.hits=full
p.nodedepth=1
1_property.opertaion=like
1_property=jcr:content/jcr:title
1_property.value=Dr.

The issue is that even though the operation is set to like only full matches are returned. partial matches return no results however on AEM 6.0 partial results are returned. In my case the value of "Dr." returns nothing while Dr. Lawrence Wu which is an existing node returns the page.
Any help appreciated

A: You have a typo or probably an error in your sample/code:
1_property.opertaion=like
instead of:
1_property.operation=like

Beside this, I don't thing that there is any difference in the QueryBuilder implementation between 6.0 and 6.2. All query builder queries are converted to SQL2 before they are executed. You can set the log level to DEBUG for the following packages in order to see the actual queries in your log:

*

*org.apache.jackrabbit.oak.query

*com.day.cq.search

You can also test your queries using the query debug servlet and see what xpath is produced in the end. The option p.hits=full controls only if all properties are included in the result or just a small set of them (e.g. path, name, title, etc.)


text:
Q: SQL Server 2012 or 2014 Failover Cluster - Change Instance Port Number I am trying to change the randomly-assigned TCP Port Number for my Two-Node SQL Server Failover Cluster to a static value (a value already setup in our firewalls, etc.)
I have seen a number of posts from various sources on this topic, all of which jump on pointing you at articles for SQL Server 2005 and 2008 and the old Cluster.exe tool (which I don't think is currently delivered).
You can't just use SQL Server Configuration Manager to change TCP Port in a Failover Cluster environment.
Does anyone have insight into how to assign a static port for a named instance on a failover cluster of 2012 generation or newer?
Thanks in advance.


text:
Q: Obtaining list of proxies It there a source where I can obtain a large up to date list of proxy ips? I would like to limit users votes on a website if they are using proxy.

A: Instead, restrict access based on the presence of the X-Forwarded-For: header.

A: You could use cookies and/or evercookies to track which users have voted before and/or which users have been seen using known proxies (such as those identified by the X-Forwarded-For: header).
I suspect this will be far more reliable than trying to find a list of "all" public proxy servers.


text:
Q: How to sort Google Generated Keyword Ideas Result? Although, I have successfully implemented Google Keyword Planner API to generate Keyword Ideas in PHP with the link below.
https://developers.google.com/google-ads/api/docs/keyword-planning/generate-keyword-ideas
Does anyone know the fastest way to sort the result by AvgMonthlySearches?
// Iterate over the results and print its detail.
foreach ($response->iterateAllElements() as $result) {
    /** @var GenerateKeywordIdeaResult $result */
    // Note that the competition printed below is enum value.
    // For example, a value of 2 will be returned when the competition is 'LOW'.
    // A mapping of enum names to values can be found at KeywordPlanCompetitionLevel.php.
    printf(
        "Keyword idea text '%s' has %d average monthly searches and competition as %d.%s",
        $result->getText(),
        is_null($result->getKeywordIdeaMetrics()) ?
            0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches(),
        is_null($result->getKeywordIdeaMetrics()) ?
            0 : $result->getKeywordIdeaMetrics()->getCompetition(),
        PHP_EOL
    );
}

Thanks

A: You could implement a function that can compare two instances of your object and use usort:
function cmp($a, $b) {
    return $a->getKeywordIdeaMetrics()->getAvgMonthlySearches() - $b->getKeywordIdeaMetrics()->getAvgMonthlySearches();
}

$list = iterator_to_array($response->->iterateAllElements());

usort($list, "cmp");

// $list will be your sorted array to work with from here onwards ...

See more:

*

*Sort array of objects by object fields

*https://www.php.net/manual/en/function.iterator-to-array.php


text:
Q: (How) does PHP cache script and custom INI-files? Currently I'm storing the configuration for my PHP scripts in variables and constants within another PHP script (e.g. config.php).
So each time a script is called, it includes the configuration script to gain access to the values of the variables/constants.
Since INI-files are easier to parse by other scripts, I thought about storing values for my configuration in such a file an read it using parse_ini_file().
In my notion PHP keeps script-files in memory, so including a script-file does (usually) not cause IO (Or does Zend do the caching? Or are the sources not cached at all?).
How is it with reading custom INI-files. I know that for .user.ini there is caching (see user_ini.cache_ttl), but does PHP also cache custom INI-files?, or does a call to parse_ini_file() always cause IO?

A: Summary
The time required to load configuration directives (which is not the same as the time needed by the app to perform those directives) is usually negligible - below one millisecond for most "reasonably sized" configurations. So don't worry - INI, PHP, or JSON are, performance wise, all equally good choices. Even if PHP were ten times faster than JSON, that would be like loading in 0.001s instead of 0.01s; very few will ever notice.
That said, there are considerations when deciding where to store config data.
.ini vs .php config storage

*

*Time to load: mostly identical unless caching is involved (see below), and as I said, not really important.

*ease of use: .ini is easier to read and modify for a human. This may be an advantage, or a disadvantage (if the latter, think integrity check).

*data format: PHP can store more structured data than .ini files, unless really complicated workarounds are used. But consider the possibility of using JSON instead of INI.

*

*More structured data means that you can more easily create a "super configuration" PHP or JSON holding the equivalent of several INI files, while keeping information well isolated.

*automatic redundancy control: PHP file inclusion can be streamlined with require_once.

*user modifications: there are visual INI and JSON editors that can allow a user to modify a INI or JSON file while keeping it, at least, syntactically valid. Not so for PHP (you would need to roll your own).

Caching
The PHP core does not do caching. Period. That said, you'll never use the PHP core alone: it will be loaded as a (fast)CGI, an Apache module, et cetera. Also you might not use a "barebones" installation but you could have (chances are that you will have) several modules installed.
Both the "loader" part and the "module" part might do caching; and their both doing this could lead to unnecessary duplications or conflicts, so it is worth checking this out:

*

*the file (but this does not change between INI, JSON and PHP files) will be cached into the filesystem I/O subsystem layer and, unless memory is really at a premium, will be loaded from there (on a related note, this is one of the reasons why not all filesystems are equally good for all websites).

*if you need the configuration in several files, and use require_once in all of them, the configuration will be loaded once only, as soon as it is needed. This is not caching, but it is a performance improvement nonetheless.

*several modules exist (Zend, opcache, APC, ...) that will cache all PHP files, configuration included. They will not cache INI files, though.

*the caching done by modules (e.g. opcache) can (a) ignore further modifications to the file system, which means that upon modifying a PHP file, you'll need to somehow reload or invalidate the cache; how to do this changes from module to module; (b) implement shortcuts that might conflict with either the file system data management or its file structure (famously, opcache can ignore the path part of a file, allowing for much faster performances unless you have two files with the same name in different directories, when it risks loading one instead of the other).

Performance enhancement: cache digested data instead of config directives
Quite often it will be the case that depending on some config directive, you will have to perform one of several not trivial operations. Then you will use the results for the actual output.
What slows down the workflow in this case is not reading whether, say, "config.layout" is "VERTICAL" or "HORIZONTAL", but actually generating the layout (or whatever else). In this case you might reap huge benefits by storing the generated object somewhere:

*

*serialized inside a file (e.g. cache/config.layout.vertical.html.gz). You will probably need to deploy some kind of 'stale data check' if the layout changes, or some kind of cache invalidation procedure. (For layouts specifically, you could check out Twig, which also does parameterized template caching).

*inside a keystore, such as Redis.

*in a RDBMS database such as MySQL (even if that's overkill - you'd use it as a keystore, basically).

*faster NoSQL alternatives such as MongoDB.

Additional options
You will probably want to read about client caching and headers, and possibly explore whatever options your hosting offers (load balancers, HTTP caches such as Varnish, etc.).

A: parse_ini_file() uses standard operations to convert the file into an array.


text:
Q: Show that $f(x) = O(1/x)$ Let $f:\mathbb{R}\to\mathbb{R}$ such that $f\ge 0$, monotonically decreasing and $\int_0^\infty f(x) \ dx < \infty$. Prove that $f(x) = O(1/x)$.
So basically, both $f(x)$ and $1/x$ are non-negative and monotonically decreasing. We know that $\int_0^\infty \frac{1}{x} = \infty$ but $\int_0^\infty \lt \infty $ - so there must be some $N$ such that for every $x>N$: $f(x) \le \frac{1}{x}$ which implies $f(x) = O(\frac{1}{x})$.
Is that valid/rigorous enough?
Thanks.

A: For $t > 0$,
$$tf(t) = \int_0^{t}f(t)\, dx \le \int_0^t f(x)\, dx \le \int_0^\infty f(x)\, dx.$$
Thus $0 \le f(t) \le M/t$ for all $t > 0$, where $M = \int_0^\infty f(x)\, dx$. So $f(x) = O(1/x)$.


text:
Q: Bitbucket Pipelines - No Application Version named found I'm trying to deploy django project to elasticbeanstalk using bitbucket pipelines.
Here's my config
image: python:3.7.2

pipelines:
  branches:
      master:
        - step:
            script:
              - pipe: atlassian/aws-elasticbeanstalk-deploy:0.2.5
                variables:
                  AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
                  AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
                  AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
                  APPLICATION_NAME: $APPLICATION_NAME
                  COMMAND: $COMMAND
                  ENVIRONMENT_NAME: $ENVIRONMENT_NAME
                  VERSION_LABEL: ${ENVIRONMENT_NAME}_${BITBUCKET_COMMIT:0:8}_(YYYY-mm-dd_HHMMSS)
                  WAIT: 'true'
              - pip3 install -r requirements.txt
              - python3 manage.py makemigrations
              - python3 manage.py migrate
              - python3 manage.py collectstatic

I get the following error :
An error occurred (InvalidParameterValue) when calling the UpdateEnvironment operation: No Application Version named 'production_d095cbe2_YYYY-mm-dd_HHMMSS)' found.

I'm just wondering, shouldn't it have year and time frame instead of the YYYY-mm-dd_HHMMSS?

A: Well, if you want the date and time you can invoke the date function of the underlaying linux container:
date +"%Y-%m-d_%H%M%S" # displays 2019-03-26_223932

So your bitbucket-piplines.yml should do what you expect written this way:
image: python:3.7.2
pipelines:
  branches:
      master:
        - step:
            script:
              - pipe: atlassian/aws-elasticbeanstalk-deploy:0.2.5
                variables:
                  AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
                  AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
                  AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
                  APPLICATION_NAME: $APPLICATION_NAME
                  COMMAND: $COMMAND
                  ENVIRONMENT_NAME: $ENVIRONMENT_NAME
                  VERSION_LABEL: ${ENVIRONMENT_NAME}_${BITBUCKET_COMMIT:0:8}_$(date +"%Y-%m-d_%H%M%S")
                  WAIT: 'true'
              - pip3 install -r requirements.txt
              - python3 manage.py makemigrations
              - python3 manage.py migrate
              - python3 manage.py collectstatic


text:
Q: Не всегда срабатывает hover на svg в компоненте Vue При наведении на svg в компоненте то заливается фон то нет. При наведении в обычном html файле всё работает отлично. Почему в компоненте Vue работает не корректно?

#svg-container {
    background-color: beige;
  }
  .shape-nav{
    width:100px;
    height:100px;
    padding:10px;
  }
  .shape-nav-path {
    fill: none;
    stroke: pink;
    stroke-width: 1px;
  }
  .shape-nav-path:hover {
    cursor: pointer;
    fill: green;
  }
<template>
  <div>
    <v-container grid-list-md text-xs-center>
      <v-layout row wrap>
        <v-flex xs12 md6>
          <svg class="shape-nav" viewBox="-10 -10 120 120">
            <path class="shape-nav-path" d="M 0 100 L 100 100 L 50 0 L 0 100 Z"></path>
          </svg>

          <svg class="shape-nav" viewBox="-10 -10 120 120">
            <path class="shape-nav-path" d="M 0 100 L 0 0 L 100 0 L 100 100 L 0 100 Z"></path>
          </svg>

          <svg class="shape-nav" viewBox="-10 -10 120 120">
            <path class="shape-nav-path" d="M 50 50 m -50 0 a 50 50 0 0 1 100 0 a 50 50 0 0 1 -100 0 z"></path>
          </svg>

          <svg class="shape-nav" viewBox="-10 -10 120 120">
            <path class="shape-nav-path" d="M 0 100 L 100 100 L 75 0 L 25 0 L 0 100 Z"></path>
          </svg>

          <svg class="shape-nav" viewBox="-10 -10 120 120">
            <path class="shape-nav-path" d="M 0 100 L 0 50 A 50 50 0 0 1 100 50 L 100 100 L 0 100 Z"></path>
          </svg>
        </v-flex>
      </v-layout>
    </v-container>

  </div>
</template>

A: Проблема решается за счет fill: transparent; вместо fill: none; у path

#svg-container {
  background-color: beige;
}
.shape-nav{
  width:100px;
  height:100px;
  padding:10px;
}
.shape-nav-path {
  fill: transparent;
  stroke: pink;
  stroke-width: 1px;
}
.shape-nav-path:hover {
  cursor: pointer;
  fill: green;
}
<svg class="shape-nav" viewBox="-10 -10 120 120">
  <path class="shape-nav-path" d="M 0 100 L 100 100 L 50 0 L 0 100 Z"></path>
</svg>

Или, как было сказано в комментарии ниже за счет pointer-events: all;

#svg-container {
  background-color: beige;
}
.shape-nav{
  width:100px;
  height:100px;
  padding:10px;
}
.shape-nav-path {
  pointer-events:all;
  fill:none;
  stroke: pink;
  stroke-width: 1px;
}
.shape-nav-path:hover {
  cursor: pointer;
  fill: green;
}
<svg class="shape-nav" viewBox="-10 -10 120 120">
  <path class="shape-nav-path" d="M 0 100 L 100 100 L 50 0 L 0 100 Z"></path>
</svg>

A: Не всегда срабатывает. Вот без вью всяких. А не срабатывает, потому что линия слишком тонкая и нужно аккурат в неё попасть при наведении. А если быстро мышкой пролетаешь, то далеко не всегда курсор оказывается четко над линией и событие просто не срабатывает. Это моё предположение.

#svg-container {
    background-color: beige;
  }
  .shape-nav{
    width:100px;
    height:100px;
    padding:10px;
  }
  .shape-nav-path {
    fill: none;
    stroke: pink;
    stroke-width: 1px;
  }
  .shape-nav-path:hover {
    cursor: pointer;
    fill: green;
  }
<svg class="shape-nav" viewBox="-10 -10 120 120">
  <path class="shape-nav-path" d="M 0 100 L 100 100 L 50 0 L 0 100 Z"></path>
</svg>


text:
Q: How to solve captcha in Imacros by API I want to use deathbycaptcha to solve captchas in Imacros.
I see api for imacros, but it isnot working for me.

http://api.dbcapi.me/decaptcher?function=imagegroup&print_format=html

what I am doing:

*

*submit user name and password

*chose a picture

*click send

but result is -1
can anyone help me?
This is their API
VERSION BUILD=844

URL GOTO=http://api.dbcapi.me/decaptcher?function=imagegroup&print_format=html
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:username CONTENT={{YOUR_DBC_USERNAME}}
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:password CONTENT={{YOUR_DBC_PASSWORD}}
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:pict CONTENT={{PATH_TO_MAIN_IMAGE}}
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:banner CONTENT={{PATH_TO_BANNER_IMAGE}}
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:banner_text CONTENT={{BANNER_TEXT}}
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:grid CONTENT={{GRID}}
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=*

TAG POS=6 TYPE=TD ATTR=* EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}

This is my code in imacros
VERSION BUILD=10022823
TAB T=1
TAB CLOSEALLOTHERS
SET !EXTRACT_TEST_POPUP NO
FILEDELETE NAME=C:\captcha\captcha1.jpg
URL GOTO=https://www.jayde.com/submit-site.html
TAG POS=1 TYPE=IMG FORM=NAME:jayde-url-submit ATTR=SRC:https://rservice.ientry.com/captcha.srv
ONDOWNLOAD FOLDER=C:\captcha\ FILE=captcha1.jpg

TAG POS=1 TYPE=IMG FORM=NAME:jayde-url-submit ATTR=HREF:"https://rservice.ientry.com/captcha.srv" CONTENT=EVENT:SAVEITEM
tab open
tab t=2
URL GOTO=http://api.dbcapi.me/decaptcher?function=imagegroup&print_format=html
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:username CONTENT=myusername
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:password CONTENT=mypassword
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://api.dbcapi.me/decaptcher ATTR=NAME:pict CONTENT=C:\captcha\captcha1.jpg
TAG POS=1 TYPE=INPUT:SUBMIT ATTR=TYPE:submit
Wait seconds=20
TAG POS=6 TYPE=TD ATTR=* EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}
tab close
Tab t=1
TAG POS=1 TYPE=INPUT:TEXT ATTR=NAME:HUMAN-TEST CONTENT={{VAR1}}


text:
Q: changing font and color of text in table header - material table(0.19.4) I have started working with react and material ui and facing problem in changing the color and font of text in the table header. Over riding it doesn't seem to change the default style.It is specified that using "headerStyle"(object) changes the header styling. Can anyone help me with properties that has to be changed to achieve this.

A: Just checked you code.
Adding className work fine.
<TableHeader className="table-header">

And now you can apply styling you need according to your need like
.table-header{
   background: #cdcdcd !important;
}

.table-header th {
   color: blue !important
}

This works well for changing the background color and heading color for the table!


text:
Q: Worklight 6.0 Create View Patterns hangs loading pattern I just installed Worklight 6.0 Dev edition on eclipse Juno 64 bit.  When I open the mobile Navigation view and try to create a new Dojo Mobile View, where the Create view from UI pattern radio button is selected, the patterns are never displayed and an hourglass with the message "Loading:" is displayed.  This appears to hang.  I can click on Create empty view to create a view without patterns.  One more piece of information, I can see views if I run through the same scenario using the 32 bit version of eclipse.  Thanks for any help.
JT

A: Are you running Windows? What Internet Explorer version you have installed in your system?
If you have Internet Explorer 8 or below, I think this won't work. If that's the case, try upgrading to Internet Explorer 9.


text:
Q: Expandable menu over its parent's margins in Android I'm trying to use a circle menu, such as Ramotion's Circle Menu (https://github.com/Ramotion/circle-menu-android) or MaterialArcMenu (https://github.com/saurabharora90/MaterialArcMenu) inside a Linear Layout, which is within a Constrait Layout.
Those menus use a view to wrapping all items within margins of this view. The margin sizes of this view are greater than size of the central item and, in my case, even greater than parent's margins.
The problem is on click to open and display all menu items, the items that are in position outside parent's margins simply aren't shown.
I tried with android:elevation and android:transpolationZ with no positive result.
Here's my layout code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    tools:context=".Fragments.fragment"
    android:background="@color/colorSurfaceDarkTransluent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ScrollView
        android:id="@+id/picker"
        android:layout_width="match_parent"
        android:layout_height="@dimen/poster_normal_height"
        ads:dsv_orientation="horizontal"

        ads:layout_constraintBottom_toTopOf="@+id/slider"
        ads:layout_constraintEnd_toStartOf="@id/slider"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent"
        ads:layout_constraintVertical_bias="0.550"
        />

    <TextView
        android:id="@+id/text"
        style="@style/textBorder"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_gravity="start"
        android:layout_marginTop="6dp"
        android:focusable="true"
        android:gravity="center"
        android:text="@string/app_name"
        android:textSize="15dp"
        android:visibility="visible"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/player"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintTop_toBottomOf="@+id/picker"
        app:layout_constraintVertical_bias="0.609" />

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:gravity="center_horizontal"
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintHorizontal_bias="0.0"
        ads:layout_constraintStart_toStartOf="parent"
        android:clipChildren="false"
        app:layout_constraintTop_toBottomOf="@+id/picker">

        <LinearLayout
            android:id="@+id/mediaplayer_view"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:orientation="horizontal"
            android:gravity="center_horizontal"
            >

            <ImageView
                android:id="@+id/play"
                android:layout_width="@dimen/button_normal_play_width"
                android:layout_height="@dimen/button_normal_play_height"
                android:layout_gravity="center"
                android:background="@drawable/ic_play"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/stop"
                android:layout_width="@dimen/button_normal_stop_width"
                android:layout_height="@dimen/button_normal_stop_height"
                android:layout_gravity="center"
                android:src="@drawable/ic_pause"
                android:translationZ="3dp"
                android:visibility="gone" />

        </LinearLayout>

      <!-- This view collides with @+id/layout marings -->
        <CircleMenuView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:elevation="@dimen/spacing_m"
            android:translationZ="2dp"
            app:button_colors="@array/colors"
            app:button_icons="@array/icons"
            app:layout_constraintBottom_toBottomOf="parent" />

    </LinearLayout>

      <!-- Placed outside of the linear layout. Here, view would be displayed over all views. It is hidden only beyond its parent's margins  -->

    <View
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="24dp"
        android:elevation="0dp"
        android:gravity="bottom"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintHorizontal_bias="1.0"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toBottomOf="@idlayout"
        app:bar_color="@color/colorSurfaceDark"
        app:bubble_color="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:size="small" />

</androidx.constraintlayout.widget.ConstraintLayout>

Regards


text:
Q: How to Upload Image in React js and Django? I am trying to upload an image using react js on django backend but wheni try to upload pic and check it console.log() image FILE exist there and once i submit the form image file object shsows {} empty i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link . https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. Thanks.
import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      image: null
    };
  }

  handleInputChange = async (event) => {
    await this.setState({
      [event.target.name]: event.target.files[0]
      // image: event.target.files[0]
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    const formdata = new FormData();
    formdata("image", this.state.image);
    fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, {
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw"
      },
      body: formdata
    })
      .then((response) => {
        if (response.ok) {
          alert("Success");
        } else {
          alert("error");
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  render() {
    return (

          Uplaod

        <form onSubmit={this.handleSubmit}>
          <input type="file" name="image" onChange={this.handleInputChange} />
          <button>Submit</button>
        </form>

    );
  }
}

export default App;

A: please try using formdata like this:
formdata.append("image", this.state.image);

A: Thanks , I am able to solve this issue, here is working code and sandbox link. https://codesandbox.io/s/naughty-maxwell-ojnql?file=/src/App.js:0-1344.
import React, { Component } from "react";
import axios from "axios";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      image: null
    };
  }

  handleInputChange = async (event) => {
    event.preventDefault();
    await this.setState({
      // [event.target.name]: event.target.files[0]
      image: event.target.files[0]
      // image: event.target.files[0]
    });
  };

  handleFormSubmit = (event) => {
    event.preventDefault();

    let data = new FormData(); // creates a new FormData object

    data.append("image", this.state.image); // add your file to form data

    axios({
      method: "POST",
      url: "https://inback.herokuapp.com/api/1/blog/image/list/",
      headers: {

        Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw"
      },
      data
    })
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  };

  render() {
    return (

          Uplaod

        <form onSubmit={this.handleFormSubmit}>
          <input type="file" name="image" onChange={this.handleInputChange} />
          <button>Submit</button>
        </form>

    );
  }
}

export default App;


text:
Q: Route to /login and /{PageName} in an asp.net app not working In an ASP.NET Blazor App with Identity I have a page with the page routing
@page "/{PageName}"

When I change the page routing of the login page in Areas/Identity/Pages/Login.cshtml to
@page "/login"

and enter the URL 'localhost:44397/login', the login page shows up as expected.
However, if I follow the link in header bar that I have adapted in LoginDisplay.razor to Log in, the URL changes to 'localhost:44397/login' as expected, but the login page does not appear. Instead, the above page is rendered, where the PageName parameter is set to 'login'.
Endpoint routing obviously works if the URL is entered manually but fails when clicking a link, as if half of the routing middleware would have been bypassed. I tested this with a fresh Blazor template and have no more ideas where to look for the bug.

A: Accoring to this article, a click on a hyperlink in a Blazor component is intercepted automatically. While the URL in the browser is updated, the request is not sent to the browser but the page is renderd by Blazor. In my case, Blazor can find a suitable page (the one with the @page "/{PageName}" directive) and renders it.
To force loading of the page, NavigationManager can be used:
 navigationManager.NavigateTo("/login", true))">Login

The href is necessary to render the link with the typical layout. It's probably not the most elegant solution but at least it works.


text:
Q: Windows 7 Ultimate Product key doesn't work without SP1? HEy I tried my windows 7 ultimate sp1 key but is it normal that this key doesn't work with windows 7 ultimate? (No SP1 installed)
checking it on: http://d-fault.nl/PidCheck.aspx
Gives me the following results:
Validity     : Valid
Edition Type     : Ultimate
Description  : Windows 7 SP1 Ultimate Retail
Edition ID   : X16-95496
Key Type     : Retail

So does this SP1 actually matter?
Just wondering (Downloading SP1 right now)

A: From Microsoft's own help topic on the issue:

You can't use a product key for Windows 7 with Service Pack 1 (SP1) to activate a copy of Windows 7 without SP1.

You can leave the key blank on install, and follow this helpful guide to activating Windows 7 after SP1 is installed.

A: I remember some XP SP3 serial numbers not working on XP SP2 and below,
so I think you might be right, the same could apply to Windows 7.
Also, where exactly is windows not accepting the serial number, during the setup phase,
or inside windows itself, are you connected to the internet when it tries to activate online?


text:
Q: Ensemble of Spins along magnetic field Say we have $N$ spins. These can be oriented along a B-Field or "antiparalell" to it. Spins along the field give Energy $\epsilon$ and antiparallel to it energy zero. Now for a given energy $E$ of the system I want to find the number of microstates $\Omega(E)$.
As then there are $M$ spins that have energy $\epsilon$ I'd say: $E=M\epsilon$.
Is finding $\Omega$ then just combinatorics of how I can arrange the $M$ spins along $B$ and the $N-M$ spins antiparallel to it? Or is there more to it?


text:
Q: Latest String value assigned to a variable is not returned by the function in python In the Below code i am trying to get the user input until it matches the value in the 'type_details' dictionaries.
But the function is returning the invalid input but not the correct value entered finally
Enter the preferred Type:fsafs
Please Choose the Type available in the Menu
Enter the preferred Type:Cup
Traceback (most recent call last):
File "C:\Users\Workspace-Python\MyFirstPythonProject\Main.py", line 186, in <module>
typeprice = type_details[typeValue]
KeyError: 'fsafs'

Below is the code
type_details = {'Plain':1.5,
             'Waffle':2,
             'Cup':1}
def getType():
    type = input("Enter the preferred Type:")
    if not ValidateString(type):
        print("Type is not valid")
        getType()
    else:
        check = None
        for ct in type_details:
            if ct.lower() == type.lower():
                check = True
                type=ct
                break
            else:
                check = False
        if not check:
            print("Please Choose the Type available in the Menu")
            getType()
    return type

typeValue = getType()
typeprice = type_details[typeValue]

A: How about something simple as this?
Get user input, check if it's in dictionary, return if so else continue in the infinite loop.
type_details = {'Plain':1.5,
             'Waffle':2,
             'Cup':1}

def getType():
    while True:
        user_in = input("Enter the preferred Type: ")
        if user_in in type_details:
            return user_in

user_in = getType()
print(f'You entered: {user_in}')
print(f'Type Price: {type_details[user_in]}')

A: Each time getType() is called (even inside itself) a new local variable type is created whose content is lost if it isn't returned to the calling function.
The content of type in the calling getType() isn't modified.


text:
Q: PvApi for prosilica camera I am using prosilica camera on Mac os x 10.8.5. I downloaded the SDK for Mac OS X.
I try to execute the examples on the SDK but always I got this errors.
> make sample
g++-4.2   -O3  -mmacosx-version-min=10.5 -I/usr/include -D_x64 -D_OSX -Wall -I../../inc-pc -D_REENTRANT  ListCameras.cpp -o ListCameras -lpthread -lz -Bdynamic -lm -lc -L../../bin-pc/x64 -lPvAPI
make: g++-4.2: No such file or directory
make: *** [sample] Error 1

But when i run g++ -v on terminal I got:
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.38) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin12.5.0
Thread model: posix

What is the error ? could help me please ?

A: TO understand the error open your ARCH file and see the error
g++-4.2   -O3  -mmacosx-version-min=10.5 -I/usr/include -D_x64 -D_OSX -Wall -I../../inc-pc -D_REENTRANT  ListCameras.cpp -o ListCameras -lpthread -lz -Bdynamic -lm -lc -L../../bin-pc/x64 -lPvAPI
make: g++-4.2: No such file or directory

It is running fine up-to the 24 line of ARCH file printing g++-$(VER) but after that It is not able to link.
So I guess try to change the ARCH file according to your directories especially this part
## few locations
INC_DIR   = ../../inc-pc
BIN_DIR   = ../../bin-pc/$(CPU)
LIB_DIR   = ../../lib-pc/$(CPU)
OBJ_DIR   = ./obj/$(CPU)
EXTRA_LIB = -lpthread -lz

Complete the paths of all the directories.
Or mainly it needs the path to libPvAPI.a library so you can also change the following part directly :
## libs (shared/static)
PVLIB   = -L$(BIN_DIR) -lPvAPI

to
PVLIB   = -L/fullpath -lPvAPI

by fullpath I mean something like -L/home/username/folder1/.../ .


text:
Q: Divergence of function $f(x,y,z)=e^{x}\sin(yz)$ is
For a given function  $f(x,y,z)=e^{x}\sin(yz)$. Then divergence of $f(x,y,z)$ is

What i try ::
For a function $f(x,y,z)=<f_{1}(x,y,z),f_{2}(x,y,z),f_{3}(x,y,z)>$
Now we know that $$Div f=<\frac{d}{dx},\frac{d}{dy},\frac{d}{dz}>\cdot <f_{1},f_{2},f_{3}>$$
$$Div f=\frac{df_{1}}{dx}+\frac{df_{2}}{dy}+\frac{df_{3}}{dz}$$
But in my function given $f(x,y,z)=e^{x}\sin(yz)$
I have find $f_{x}=e^{x}\sin(yz)$
$f_{y}=ze^{x}\cos(yz)$ and $f_{z}=ye^{x}\cos(yz)$
Above function not in component form. Then how do i find Divergence . Help me please. Thanks

A: Divergence is a vector operator that acts on a vector field producing a scalar field. However, your $f$ here is a scalar field, not a vector field. In other words, the divergence of $f$, i.e. a scalar field, is not a defined operation.
Note: what you can calculate for scalar field is its gradient.


text:
Q: 16GB SSD booster on ubuntu I've bought a Lenovo Thinkpad Edge laptop which has a hybrid 320GB HDD + 16GB SSD, then I've installed Ubuntu 12.04, so now I have dual boot - Ubuntu/Windows7.
Everything is fine but the question is - will the Ubuntu use the 16GB SSD drive?
I mean will it take the advantage of it?
As far as I know Windows uses it like a cache while waking up from sleep/hibernation, doesn't it?

A: If your SSD shows up as a separate 16 gigabyte drive I don't think so.
I came across some  forum posts talking about Lenovo hybrid disks. It seems to be a Hybrid drive in some sense yes.
But it seems to require software in the running operating system.
"Real" hybrid drives transparently move files to the SSD part of the drive to "boost" performance. and present themselves as a single drive to the operating system.
Since they check blocks being read / written often and move those blocks to the SSD part of the drive they are filesystem agnostic and work on any or multiple operating systems.
Llimited space of the SSD part and the algorithm is constantly trying to optimize for the current running OS. Switching between operating systems often will lower the performance gain. The longer you stay on the same OS the bigger the optimization gain of the hybrid will be for that particular OS.

A: yes absolutely ubuntu will use this SSD
The hard drive will manage the split between ssd and magnetic storage itself
All new hybrid drives are self-managed
The Momentus XT drive installs as easily as a traditional 9.5mm-high notebook drive for new systems or laptop upgrades and, unlike early hybrid drives, operates independently of the operating system and the motherboard chipset.
check this link for instance


text:
Q: Symfony2 - routing subdomains, but subdomain has a special directory I read a Google and Symfony2 docs about routing on Subdomains like:
acme_admin_separator:
    path:     /
    resource: "@AcmeAdminSeparatorBundle/Resources/config/routing.yml"
    host:     admin.{domain}
    requirements:
        domain: %domain%

But it should works only, if subdomains are handled by .htaccess. But I have this webhosting hierarchy:
+ /domain.com/
+-- /web/ <-- Here are all my Symfony2 files
+--- /app/
+--- /bundles/
+--- /src/
+--- ...
+-- /sub/ <-- directory for subdomains
+---- /admin/ <-- directory for admin.domain.com subdomain

And I'm asking - is it possible to configure routing to be able to use admin.domain.com as the route for my Symfony2 project without copying all my Symfony2 files to this folder? And if is, should I do something in /admin/ directory?

A: Your route is right. You must to config your hosting or server for handle all requests for non-existent subdomains *.domain.com.

A: You have to copy app.php, and paste file in directory like this : /sub/admin/ (change include path in app.php). Or make a blank file and include app.php.


text:
Q: Как вытащить svg из html Здравствуйте, у меня есть скрипт, рендерящий график из Google Charts. Мне необходимо сохранить его в отчете, каким образом его вытащить?
Через GET запрос выдает мой div в котором ничего нет.
Мой скрипт:
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawCurveTypes);
google.charts.setOnLoadCallback(drawCurveTypes2);
function drawCurveTypes() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Месяц');
    data.addColumn('number', 'Количество ссылок');
    data.addRows(@{WriteLiteral(linkpad.DiagramHrefs);});
    var options = {
        legend: 'none',
        colors: ['green']
        };
    var chart = new google.visualization.LineChart(document.getElementById('href'));
    chart.draw(data, options);
};
function drawCurveTypes2() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Месяц');
    data.addColumn('number', 'Количество доноров');
    data.addRows(@{WriteLiteral(linkpad.DiagramDonors);});
    var options = { legend: 'none' };
    var chart = new google.visualization.LineChart(document.getElementById('donor'));
    chart.draw(data, options);
};

A: Можно сохранить график как png. Следующий код создает картинку.
google.visualization.events.addListener(chart, 'ready', function () {
    var = chart_div = document.getElementById('href')
    chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
    console.log(chart_div.innerHTML);
  });


text:
Q: Injected class name compiler discrepancy Consider this code:
struct foo{};

int main() {
    foo::foo a;
}

I would expect this to be well-formed, declaring a variable of type foo by the rule in [class]/2 (N4140, emphasis mine):

A class-name is inserted into the scope in which it is declared immediately after the class-name is seen.
  The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.
  For purposes of access checking, the injected-class-name is treated as if it were a public member name.

clang 3.6.0 agrees with me, compiling the above code with no applicable warnings with -Wall -pedantic.
gcc 5.2.0 disagrees, providing the following error message:
main.cpp: In function 'int main()':
main.cpp:5:5: error: 'foo::foo' names the constructor, not the type
   foo::foo a;

The above holds no matter how deep the nesting of injected class names, e.g. foo::foo::foo::foo.
Is there a rule which forces that construct to be interpreted as a constructor in that context, or is this agcc bug? Or am I interpreting the standards quote incorrectly?

A: Relevant, but not an answer: The GCC people discussed exactly this for years and figured that it should not be accepted. They explicitly made this an error in GCC 4.5 and newer - in 4.4.7 it was accepted.
BTW: You probably want to use Clang's -Weverything instead of -Wall -pedantic when investigating such stuff.

A: It appears that clang is wrong in this case. The relevant exception I was looking for is in [class.qual]/2:

2 In a lookup in which function names are not ignored and the nested-name-specifier nominates a class C:

*

*(2.1)
  if the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C, or

*[...]
the name is instead considered to name the constructor of class C.

The standard has a near-equivalent (non-normative, obviously) example:
struct A { A(); };
struct B: public A { B(); };

A::A() { }
B::B() { }

B::A ba;// object of type A
A::A a;// error, A::A is not a type name
struct A::A a2;// object of type A

However, clang actually issues a correct diagnostic in this case:
error: qualified reference to 'A' is a constructor name rather than a type wherever a constructor can be declared

Perhaps clang interprets the line In a lookup in which function names are not ignored as In a lookup in which a constructor declaration is valid, but that doesn't seem to be a correct interpretation.
There is an existing bug for this in the clang bugzilla.

A: I think this is the subject of language defect #147
which contains this example
class B { };
class A: public B {
    A::B ab;       // B is the inherited injected B
    A::A aa;       // Error: A::A is the constructor
};

At least gcc seems to believe that. :-)


text:
Q: Sign in button not working with firebase authentication Hi there people i cannot run the code on this and the sign in button doesnt respond to the firebase i have tried all the things but couldnt figure out the problem can you please help me on this one

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:my_project/hello/Courses.dart';
import 'package:url_launcher/url_launcher.dart';

class MyLogin extends StatefulWidget {
  const MyLogin({super.key});

  @override
  State<MyLogin> createState() => _MyLoginState();
}

class _MyLoginState extends State<MyLogin> {

final emailcontroller = TextEditingController();
  final passwordcontroller = TextEditingController();

   Future SignIn() async{
    await FirebaseAuth.instance.signInWithEmailAndPassword(email: emailcontroller.text.trim(), password:
    passwordcontroller.text.trim());
   }
   @override
  void dispose() {
    emailcontroller.dispose();
    passwordcontroller.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage('assets/hello.jpg'),fit: BoxFit.cover)
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Stack(
          children: [
            Container(
              padding: EdgeInsets.only(left:35,top: 45),
              child: Text('Welcome Back,\nStudent',
               style: TextStyle(color: Color.fromARGB(255, 255, 255, 255),fontSize: 20),),

            ),
            SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.3,
                right: 35,
                left: 35),
                child: Column(children: [
                  TextField(
                    controller: emailcontroller,

                    decoration: InputDecoration(
                      fillColor: Colors.grey.shade100,
                      filled: true,
                      hintText: 'Email',
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(10))
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  TextField(
                    controller: passwordcontroller,

                    obscureText: true,
                    decoration: InputDecoration(
                      fillColor: Colors.grey.shade100,
                      filled: true,
                      hintText: 'Password',
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(10))
                    ),
                  ),
                  SizedBox(height: 40,),
                 ElevatedButton.icon(style: ElevatedButton.styleFrom(
                  minimumSize: Size.fromHeight(50),
                 ), icon: Icon(Icons.lock_open,size: 32,), label: Text(
                  'Sign In', style: TextStyle(fontSize: 24),
                 ), onPressed: SignIn,),

           RichText(
            text: new TextSpan(
              children: [
                new TextSpan(
                  text: 'Forgot Your Password?, ',
                  style: new TextStyle(color: Color.fromARGB(255, 226, 218, 218)),
                ),
                new TextSpan(
                  text: 'Click Here',
                  style: new TextStyle(color: Colors.blue),
                  recognizer: new TapGestureRecognizer()
                    ..onTap = () { launch('https://www.dandenongclc.org.au/about-us');
                  },
                ),
              ],
            ),
          ),
                ]),
              ),
            )
          ],
        ),
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:my_project/hello/Courses.dart';

import 'package:my_project/hello/timetable.dart';
import 'login.dart';
import 'package:flutter/foundation.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(
    MaterialApp(
    debugShowCheckedModeBanner: false,
    initialRoute: 'login',
    routes: {
      'login':(context) => const MyLogin()
    },
    home: const Mainpage(),
  ));
}

class Mainpage extends StatelessWidget {
  const Mainpage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot)
        {
          if (snapshot.hasData){
            return Courses();
          }

          return MyLogin();
        }
      ),);
  }
}

I was expecting the sign in button to configure with firebase as i have added the user authentication with email and password on firebase but whenever i click the sign i cannot go through to the page i linked to here are my main.dart and my login.dart file can you help guys

A: In Your Mylogin file use like this
 ElevatedButton.icon(style: ElevatedButton.styleFrom(
                  minimumSize: Size.fromHeight(50),
                 ), icon: Icon(Icons.lock_open,size: 32,), label: Text(
                  'Sign In', style: TextStyle(fontSize: 24),
                 ),onPressed: ()async {
                   await SignIn();
                  },),


text:
Q: How can I use a numpy array with index values to set elements of another numpy array to 0? I am taking a numpy array proc_ranges and finding which values are +/- 5 apart in value. I then want to set elements within a certain range of those indexes to 0. I have the following two numpy arrays, where the elements are the indexes of the elements of diff_array that are > 5 or < -5.
diff_array = np.diff(proc_ranges)
bubble_to_the_right_arr = np.where(diff_array > 5)
bubble_to_the_left_arr = np.where(diff_array < -5)

I am using the following lines to set index ranges within proc_ranges to 0:
proc_ranges[bubble_to_the_right_arr-bubble_size:bubble_to_the_right_arr+bubble_size] = 0
proc_ranges[bubble_to_the_left_arr-bubble_size:bubble_to_the_left_arr+bubble_size] = 0

These lines are giving me an error as you cannot add or subtract a tuple from an int. bubble_size is just a constant int. Basically I am trying to set multiple index ranges within proc_ranges to 0, but I am not sure how to set values using a tuple as an index parameter.


text:
Q: Matlab 2D wave equation using FDM The Following is my Matlab code to simulate a 2D wave equation with a Gaussian source at center using FDM.I used imagesc function to output the wave. The wave seems to spread out from the center, but very slowly. It seems like I messed it upp somewhere. And the output is very pixelated. What am I doing wrong?
clc
close all
clear all

c0 = 3e1;         % speed of light or any wave
e0 = 8.854e-12;   % free space permittivity
u0 = 1.2566e-6;   % free space permeability

size=170;        % size of free space

s=size;            % s determines the position of the source in the free space

dx=0.001;        % spatial increment

dt=dx/(c0);   % time increment

cons=c0*dt/dx; % constant term of electric and magnetic field equations

n =500 ; % total time

% u=zeros(1,size); % initially, E at all points is taken zero
u_n=zeros(size);    %constant time next state of wave
u_p=zeros(size);    %constant time previous state of wave
u = zeros(size);    %constant time present state of wave

t0=15;   % t0 of Gaussian source
tp=5;   % tp of Gaussian source

for k=1:n

    for i=2:size-1
    for j=2:size-1
        u_n(i,j)= 2*u_n(i,j)-u_p(i,j)+(cons^2)*( u(i+1,j)+u(i-1,j)-4*u(i,j)+u(i,j+1)+u(i,j-1) );
    end
    end
u_p=u;   % after this iteration present state becomes previous state
u=u_n;   % next step becomes present state

u(size/2,size/2)=exp(-((k-t0)/tp)^2);  % gaussian source position selected at the centre of the matrix
%u(size/2,size/2)=sin(2*pi*0.03*i);
imagesc(u)
A(k)=getframe;
end

A: I guess that the variable dx is the relevant here. But you are never using it. Look at the next piece of code
dx=0.001;        % spatial increment

dt=dx/(c0);   % time increment

cons=c0*dt/dx; % constant term of electric and magnetic field equations

You will fastly realize that cons=1 always!! Thus, you are not using the spatial increment never.
If I randomly change cons to 0.5 I get this fantastic gif:

Good job coding this!


text:
Q: Handling Json response with alamofire I'm working on a IOS login application , but I don't know how to handle the Json response from the server , I want to write a Boolean function that depends on the server response :
this is the server response if the username and the password are right :
SUCCESS: {
    users =     (
                {
            email = test;
            id = 1;
            money = 200;
            password = test;
            username = test;
        }
    );
}

And if the username and password are wrong :
SUCCESS: {
    users =     (
    );
}

this is my backend code written in NodeJs:
app.get('/login/:username/:password',(req,res)=>{
    let user = req.params;
    var sql = "SELECT * FROM  users WHERE username = ? And password = ? ";
    mysqlConnection.query(sql,[user.username,user.password],
    function(err, rows){
        if(!err){

       res.send(JSON.stringify({"users" : rows}));
}
 else {
console.log(err)
         }
    }

This is my swift function :
   class func login(username : String , password : String, _ completion: @escaping (Bool) -> ()) {
        let url = "http://127.0.0.1:3000/login/"+username+"/"+password
        Alamofire.request(url).responseJSON{response in
            switch response.result
            {
            case .failure:
    print(response)
    completion(false)
            case .success:
                //I want to handle the response here
                //return true if the username and password are right
                //return wrong if not
    print(response)
    completion(true)

            }
        }
}

A: In both case you are getting SUCCESS so you can take users as a key and check weather it's containing any element or not like if the username and the password are right you will get
(
            {
        email = test;
        id = 1;
        money = 200;
        password = test;
        username = test;
    }
)

But if the username and password are wrong you will get empty value for users key so in that case you can use
if usersDict.count == 0 {

    //username and password are wrong
} else {

    //username and the password are right
}

A: Use above code:-
func CallAPI(){

    let parameters: [String: Any] = [
        "Username": "Admin",
        "Password": "123456",
        "Language_Code": "EN"]

    Alamofire.request("Your API Url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
        .responseJSON { response in

            if((response.result.value) != nil) {

                let ResultJson = JSON(response.result.value!)

                print("ResultJson==",ResultJson)

                let UserCount = ResultJson["users"].count

                if UserCount > 0 {

                    // Do with your above code

                    let Email =  ResultJson["users"]["email"].stringValue
                    let id =  ResultJson["users"]["id"].intValue
                    let money =  ResultJson["users"]["money"].intValue
                    let password =  ResultJson["users"]["password"].stringValue
                    let username =  ResultJson["users"]["username"].stringValue
                }
            }
    }
}


text:
Q: Win32 button appearance I'm working on a GUI for a chess program using Win32, and my first thought was to make the board an 8X8 grid of buttons. However, I would prefer the squares on my board to be solid, single colors with no additional visual frills, while I haven't found a way to create a button that doesn't have a border around it. Is it possible to alter the appearance of a button arbitrarily, or are the borders unavoidable? If the latter, what other implementation could I look into for rendering a board that looks exactly how I want?

A: Create the buttons with the BS_OWNERDRAW style and handle the WM_DRAWITEM message.


text:
Q: How to filter a table by a value in another table with sql? Ive got two tables that look like this:
Customer Infomation:

Rent Infomation:

I want to show all the details of the customer table, but only display the customers that are currently renting.
Ive tried but haven't had any success with the sql.

A: There are multiple ways to achieve this
select c.* from customer_information c inner join rent_information r on r.customerId = c.customerId and r.endDate > now();

If you want only unique results then use this
select c.* from customer_information c inner join rent_information r on r.customerId = c.customerId and r.endDate > now() group by c.customerId;

If you want to run these queries on a large dataset, you might wanna see the use of subqueries

A: I think you may be looking at possibly just a simple inner join and Where query, that is if you are able to use SQL/T-SQL.
SELECT c.CustomerID, c.CustomerName
FROM CustomerInformation c
INNER JOIN RentInformation r ON r.CustomerID = c.CustomerID
WHERE r.endDate > GetDate()


text:
Q: Finding a common denominator when adding binomial coefficients I'm working my way through Serge Lang's Basic Mathematics. I'm having some trouble with exercise 7d on page 40:

Show that if $n$ is a positive integer at most equal to $m$, then
$$
\binom{m}{n} + \binom{m}{n - 1} = \binom{m + 1}{n}.
$$

I understand that I need to show that the following is true, obtained by using the binomial coefficient formula:
$$
\frac{m!}{n!(m - n)!} + \frac{m!}{(n - 1)!(m - (n - 1))!} = \frac{(m + 1)!}{n!((m + 1) - n)!}
$$
When I add the two operands on the left side, I get the following:
$$
\frac{m!(n - 1)!(m - n + 1)! + m!n!(m - n)!}{n!(m - n)!(n - 1)!(m - n + 1)!}
$$
And then I'm not sure how to proceed further. There is a solution to the exercise in the book, which shows that the next step should be as follows:
$$
\frac{m!(m - n + 1) + m!n}{n!(m - n + 1)!}
$$
However I do not understand how adding $\frac{m!}{n!(m - n)!}$ and $\frac{m!}{(n - 1)!(m - (n - 1))!}$ results in the above.


text:
Q: Reading and Writing to a File using C++ I need to read each line in the "test.txt" file using fscanf and print to new files using fprintf. If the read line is an integer, it is written to the integer file.
Float to the float file and string to string file respectively. However, when i try to compile it and run it, nothing happens and it goes to infinite loop.
Here is my code
#include <iostream>
#include <stdio.h>

using namespace std;

void writeFloat(){

  FILE *file;
  FILE *file2;
  float value;

  file = fopen("test.txt", "r");
  file2 = fopen("float.out.txt", "w");

  while(!feof(file)){

    fscanf(file, "%f", &value);
    fprintf(file2,"%f", value);

  }

  fclose(file);
  fclose(file2);

}

void writeInteger(){

  FILE *file;
  FILE *file2;
  int value;

  file = fopen("test.txt", "r");
  file2 = fopen("int.out.txt", "w");

  while(!feof(file)){

    fscanf(file, "%d", &value);
    fprintf(file2, "%d", value);
  }

  fclose(file);
  fclose(file);
}

void writeString(){
  FILE *file;
  FILE *file2;
  char value;

  file = fopen("test.txt", "r");
  file2 = fopen("string.out.txt", "w");

  while(!feof(file)){

    fscanf(file, "%s", &value);
    cout<<value<<endl;
    fprintf(file2, "%s", value);

  }

  fclose(file);
  fclose(file2);
}

int main(){

  writeFloat();
  writeInteger();
  writeString();

  return(0);

}

The test.txt file contains the values:

100
1.6E-10
hey nice to meet you.
43
56
4.5E-09
what is going on?

I don't know what wrong with my code. Please help me to achieve my requirement.

A: feof() is never true because fscanf in writefloat() refuses to read the first letter of "hey": It's not part of a legal number. scanf then returns with 0 ("no item could be read"). That is not EOF yet, though. But you should do something about it ;-).
Besides you must check for eof after you try to read something, before you try to use it. Not before the first failed read will the eof flag be turned on, but those variables will not be assigned.

A: I think, adopting a different strategy might be more appropriate for your needs.
Just have one function that reads the contents of the file line by line. It checks whether the line contains an integer or a floating point number.  It line does not contain any numbers, the line is written out to "string.out.txt". If the number is an integer, it is written out to "int.out.txt". If the number is a floating point number, it is written out to "float.out.txt".
With this strategy, you have to read the contents of the input file only once and process the contents of the file only once.
It also simplifies the reading of the data and checking when you have reached EOF.
#include <stdio.h>

void writeData()
{
  FILE *file1 = NULL;
  FILE *file2 = NULL;
  FILE *file3 = NULL;
  FILE *file4 = NULL;
  char value;
  double realNum = 0.0;
  int intNum = 0;
  int n = 0;
  char line[256];

  file1 = fopen("test.txt", "r");
  file2 = fopen("string.out.txt", "w");
  file3 = fopen("int.out.txt", "w");
  file4 = fopen("float.out.txt", "w");

  while ( fgets(line, 255, file1) != NULL )
  {
     // Each line can be plain old text, a floating point number, or an
     // integer.

     // If the line does not contain a number, assume it is a float.
     // Try to read a real number.
     n = sscanf(line, "%lf", &realNum);
     if ( n == 0 )
     {
        // The line does not have a number.
        // Write the line to the text file.
        fputs(line, file2);
     }
     else
     {
        // We have a real number.
        // Could it be just an integer?
        // Read the integer.
        sscanf(line, "%d", &intNum);

        // How do we decide whether the number is a real number or an
        // integer?
        // Is 1.0 a real number or an integer?
        // Assume for now it is an integer.
        if ( realNum == intNum )
        {
           // We have an integer.
           fprintf(file3, "%d\n", intNum);
        }
        else
        {
           // We have a real number.
           fprintf(file4, "%lG\n", realNum);
        }
     }
  }

  fclose(file4);
  fclose(file3);
  fclose(file2);
  fclose(file1);
}

int main()
{
  writeData();
  return(0);
}

A: That is not the common way to open and close a file in C++. It looks like a c program. Try using functions from fstream and iostream libraries. See http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm.


text:
Q: Prevent ActionBar back button to recreate the MainActivity How can I prevent the ActionBar back button (we gonna say ABBB) of my SecondActivity to recreate the MainActivitywhen clicked ?
I have a ListView in the MainActivity and it can be edited using the SecondActivity. The problem is that when the user presses the ABBB, the ListView is reset to default...
However, when the user clicks my OK button or presses physical back button, there is not any problem because I'm using finish();
@Override
public void onBackPressed() {
    finish();
}

If I use this code... :
switch (item.getItemId()) {
    case (android.R.id.home):
        finish();
}

...there is the same problem because, I guess, this method is called after "Android's code".
How can I totally override Android ABBB's clicked code to set it to just call finish(); ?

A: The ideal scenario is, when are you in the SecondActivity (I take it that, this means that you are in Edit mode), and you press the device back button or ABBB, you show a subtle alert to the user saying "do they really want to dismiss the editing", or go ahead and apply the edit done as in the Contacts application.
So that being said, if all you require is to finish() the activity on press of ABBB, the code that you shown above should work fine (though you need to put return true; after finish()). It works for me. Try the below one in your activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed(); // or finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

I put onBackPressed(); because your ABBB with now imitate your device back button.

A: Or, you can set your parent activity's launch mode as -
android:launchMode="singleTop"

that will do all without changing anything.
Reference


text:
Q: Which languages will call C++ with no explicit bridging? While developing a new product, we decided to go for a mix of C++ and C#, haven been told that bridging them to allow the C# code to call the C++ code would be easy (spoiler, it's not).
We're pretty experienced C++ programmers and not at all C# programmers so we pretty much just had to believe what we've read. A few attempts to call C and Objective-C was promising and we even found a few articles that showed how to make an unmanaged C++ class available in C# -- or at least we thought. The C++ code in the articles, wasn't C++, but instead the horrible monster C++/CLI that Microsoft seems to think is C++. Since we're doing the C# stuff to get some bits "for free" in macOS and Windows, C++/CLI isn't an option either :-(.
Anyway, plenty of people have claimed that it's easy to call C++ code from some specific programming language, but so far, I haven't seen a single one that will allow me to do so (I haven't been paying too much attention to this, so please provide me with an obvious example). C++ invariably always means C with no C++ stuff at all; no namespaces, classes, no stl, lambdas or anything. Just plain dumb C.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:

*

*Create an instance of a class, using a C++ constructor, and dispatch it with a C++ destructor.

*Call member functions on an object ( foo f; f.foo();) with a C++ class.

*Use std::vector, std::find_if, std::string and other stuff from the stl. Complete coverage of the stl is not required.

*Use overloaded functions (i.e. f(), f(int), f(std::string))

*Use overloaded operators (foo operator + (foo, foo))

*Use C++11, C++14 and/or C++17 features.

*Use RAII (rather important IMHO).

*Use namespaces.

A: No. There is no such language.
Unless you count Objective-C++. But that falls pretty much in the same bucket as C++/CLI, in being C++ with some extensions. And C++/CX is another such beast.
There are some interop tools that can work with C++ classes (SWIG for example), but I have never heard of a tool that is capable of instantiating C++ templates (like vector or find_if) on demand.

A:
What languages will call C++ with no explicit bridging?

The short answer to this question is: NONE
Remember that a programming language is a specification written in some technical report, usually in English. For examples, read n1570 (the spec of C11) or R5RS (the spec of Scheme). For C++, see n3337.
Actually, you are interested in implementations, e.g. in compilers and interpreters for your programming languages. These implementations are practically software. And then the answer might become: it depends (notably on the ABI used & targetted by your compiler and system).
See for examples this list of ABIs for Linux.

plenty of people have claimed that it's easy to call C++ code from some specific programming language,

The C calling conventions are quite common, and it might help to declare every C++ function callable from outside as extern "C". But there is no silver bullet, and details matter a lot.

So, are there any languages, besides C++(/CLI) that will allow me to do the following:

list of C++ features skipped
Probably not.
You probably need at least to understand more about memory management approaches. I recommend understanding more about garbage collection, e.g. by reading the GC handbook (at least for underlying concepts & terminology). Learn more about foreign function interfaces (in some cases, the libffi might help) and language bindings.
You might also consider generating some of the C++ or C glue code, maybe with SWIG (or write your own C++ glue code generator).
On operating systems providing dynamic linking capable of loading plugins at runtime (e.g. Linux with dlopen(3)/dlsym(3); but other OSes often have similar facilities) you could even consider generating some C or C++ glue code at runtime in some temporary file, compile it as a temporary plugin, and dynamically loading that plugin. You could also consider JIT-compiling libraries like GCCJIT or LLVM (or libjit).
I recommend reading SICP, the Dragon Book, and probably Lisp In Small Pieces. Of course, learn something about OSes, e.g. Operating Systems: Three Easy Pieces. Reading about Linkers and Loaders could also help.
As an excellent example of cleverly gluing C++, look into CLASP and see this video.
But whatever approach you take, you'll need a lot of work (years, not weeks).

A: C++ as a language does not have a defined ABI (Application Binary Interface) - which basically means that there is no universal standard of what a C++ class/function call/template would look like in binary form on any given platform, or across platforms.
What that means is that there is no universal way to call C++ code from other languages, on different platforms, or even across compilers on the same platform.  It also means that the people who are telling you "it's easy to call C++ code from XYZ language"  are mostly incorrect (or at least incredibly incomplete).
Where there are interfaces it's either because the provider of the interface controls the ABI (C++/CLI with .NET), or because there is a translation layer from C++ to something like the C calling convention (Boost::python).
Some work has been done towards attempting to define an ABI per-platform (http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4028.pdf), but as far as I'm aware it has not yet been accepted into C++17.

A: You can look into using C++ interpreter, which allows for the fine-grained control you ask for. But I don't know of any that "just works", see also:
Have you used any of the C++ interpreters (not compilers)?


text:
Q: How to connect a Power Apps gallery created with a Sharepoint list, to another Sharepoint list but only to leave records? I have been trying to create an app in Power Apps that, take a list of Sharepoint to create a gallery, with an image and some data of a certain number of items. I want to put a "Comply" button that generates a record, with this data, in another list that will only save the record when this button is pressed. How can I make this connection and have the application detect the list that will only receive the information?
I have tried with collections, patch and also creating the "destination list" identical to the list that created the gallery.


text:
Q: How to segment the cloth area in the image using python opencv I want to segment cloth in this

I am using the following code but this only segments the table not the cloth.
img = cv2.imread("/content/task5/20210514_153525.jpg",0)
imgplot = plt.imshow(img,cmap='gray')
plt.show()
blur = cv2.blur(img, (3, 3))
ret, thresh = cv2.threshold(blur, 150, 255, cv2.THRESH_BINARY)
ker2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(15,15))
mask = cv2.morphologyEx(np.float32(thresh), cv2.MORPH_CLOSE, ker2)
mask = mask.astype(np.uint8)
contours, hierarchy = cv2.findContours(image =mask , mode = cv2.RETR_TREE,method = cv2.CHAIN_APPROX_SIMPLE)
mask1=mask.copy()*0
for i,cnt in enumerate(contours):
    if hierarchy[0][i][2] == -1 :
        if  cv2.contourArea(cnt) > 100000:
            cv2.drawContours(mask1,[cnt], 0, (255), -1)

imgplot = plt.imshow(mask1,cmap='gray')
plt.show()

A: You can do that in Python/OpenCV by using cv2.inRange()to threshold in HSV color space and then some morphology to clean the result of small holes and white spots.
Infile:

import cv2
import numpy as np

# load image with alpha channel
img = cv2.imread('shirt.jpg')

# convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# create mask for shirt in hsv
# specify lower and upper ranges for h,s,v colors of shirt
lower = (0,30,120)
upper = (30,70,160)
mask = cv2.inRange(hsv, lower, upper)
mask = cv2.merge([mask,mask,mask])

# apply morphology to clean mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (17,17))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# save mask
cv2.imwrite("shirt_masked.png", mask)

# display mask
cv2.imshow('mask',mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

Masked Image:


text:
Q: SetAdapter is crashing Android studio in Fragment for spinner When I comment out setAdapter line, the program does not crash.
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

final Spinner mySpinner = getActivity().findViewById(R.id.mySpinner);

ArrayAdapter adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.spinnerArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);

}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.input_personal_data_fragment, container, false);

    return view;
}

I've tried using new ArrayAdapter instead createFromResource but that didn't work either.  And I've put everything in OnCreateView method so that doesn't help. I know I'm missing something, I tried this in MainActivity and it works fine.

A: Because you have to inflate your layout in onCreateView while using fragment and then do findViewById on that view reference that you are returning from onCreateView.

A: Try This:
Problem was you are not inflate a view
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View v = inflater.inflate(R.layout.manual, container, false);

String [] values =
    {"demo1","demo2","demo3","demo4","demo5"};
Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);

return v;

}

it helps you.


text:
Q: Caml query to search in Sharepoint ListItem MetaInfo I am working with Sharepoint Lists in Silverlight and I am trying to write a CAML query that returns me all list items (pictures) which where made (effectively taken with the camera) after a specific date.
I found that the ListItems have a MetaInfo property called "vti_ct" which is exactly the date I need. The problem is that I don't know how to write a Caml query on MetaInfo fields!? Because MetaInfo is already a field.
I would be able to write a contains query but that does not help me...
Is it even possible??