text:
Q: Why does IntelliJ give me "Package doesn't exist" error? I'm trying to use the barbecue barcode printing library. I have successfully added the library to IntelliJ through project structure add library.  Then I imported the packages and wrote the methods, which gave me no error.  The packages were available in the class.
But when I compile it gives me the error:
error: package net.sourceforge.barbecue does not exist

How can this be?
I'm coding in ubuntu, is there any other place to which I have to add the library?

A: Quit IntelliJ, remove every .idea directory:
rm -Rf **/.idea/

and restart.

A: Invalidate Caches/ Restart and then Build -> Rebuild Project helped for me

A: I tried all appreciated answers and none of them solve my problem!
According to Intellij community, there is a bug  with Maven builds in 2020.1 and 2020.1.1 versions: https://youtrack.jetbrains.com/issue/IDEA-237320?_ga=2.235486722.203129946.1591253608-322129264.1584010541
Please try to run on 2019.3.4 version (Its worked for me from the first time)
You can download from here
https://www.jetbrains.com/idea/download/previous.html?_ga=2.190043688.203129946.1591253608-322129264.1584010541

A: None of the 13 existing answers worked for me. However, I could resolve the issue by first removing all modules:

*

*open File > Project Structure...,

*go to Modules tab,

*select all modules and press the remove button,

then removing all remaining Maven modules from Maven tool window:

*

*select all modules,

*right click on them,

*press Remove projects,

and then adding them again in Project tool window:

*

*right click on root pom.xml,

*press Add as Maven project,

now unignoring any ignored modules from Maven tool window:

*

*select all ignored (grey) Maven modules,

*right click on them,

*press Unignore,

and finally rebuilding using Build > Rebuild project. This assumes that a mvn clean install already happened.

A: Right click your project / Maven (at bottom) / Reimport
Edit, much later: I also saw this happen much more frequently when I had the Clover plugin installed.  Drop that plugin like a bad habit!

A: Similar to cvdr. Too high a Java version can be the problem.
A collegaue just have this problem with multiple java sources in our test project. She had just updated to a later Intellij and when we investigated none of the rebuild options worked but Intellij seemed to have 'bumped' the project Java settings to Java 11 (I guess it takes highest installed version on upgrade install?) Setting it back to Java8 and the project compiles successfully.
Go File>Project Structure > Project Settings > Project and select the right ones in the drop downs.

A: I got this error after I changed pom, and I fixed it by execute:
mvn idea:module

it works for me

A: In my case the only thing that worked is:
mvn idea:idea

The good thing is that you don't have to delete .idea folder or .iml files and loose all configuration. Everything will be preserved.
(Possibly something like gradle idea works for gradle too).

A: Here is a solution worked for me:
Disable the "Use --release option for cross-compilation like the following in intellij idea:
got Settings -> Build,Execution,Deployment -> Compiler -> Java Compiler and disable:

Use '--release' option for cross compilation(java 9 and later)

A: As someone who only occasionally needs to do Java work, this was very annoying. Inevitably, packages would have been added since the last time I ran our server inside IntelliJ and it would fail to build. I found what seems to be an easier solution: just don't build within IntelliJ. Build from the command line via Maven, then make sure that the run configuration does not list Build as a "Before launch" task.

A: I tried

*

*"Maven > Reimport"

*Deleting the .idea directory, and reopening the project.

*File -> Invalidate Caches/Restart then Build -> Rebuild Project

*Deleting what is inside local .m2 folder, and downloading dependencies again.

*Running mvn idea:idea in Maven console (Though this command is obsolete, I had to try.)

in different combinations.
But going from Intellij 2020 version to 2019 solved my issue.

A: I had this problem in IntelliJ 2020.3 and tried the invalidate cache option and rebuild, but the problem persisted. The only thing that fixed it was to rename the package and rename it back to what it was originally.

A: menu -> build -> Rebuild Project

has worked for me
(Invalidating caches without this step doesn't help)

A: Just reimport didn't work. Following worked for me.

File -> Invalidate Caches /Restart

Then

Build -> Rebuild Project

That will reimport maven project.
Note : You need to invalidate the cache AND ALSO rebuild the project.

A: I had the same problem and it was fixed for me by changing the "Maven home directory" in Settings from "Bundled" to my locally installed maven.  Perhaps this triggered some kind of refresh somewhere since I had not changed this setting for months without any issue.

A: What happens here is the particular package is not available in the cache. Resetting will help solve the problem.

*

*File -> Invalidate Caches /Restart

*Goto terminal and build the project again
./gradlew build

This should download all the missing packages again

A: If you are trying the suggested ways and still no chance, be sure about your order:

*

*Delete your .idea/

*Invalidate and Restart Cache afterwards

*Import maven projects from your maven tool

If you did not invalidate and restart cache just after deleting your .idea/, Intellij keeps generating it and that was keeping error in my case.

A: I had the same issue with my unit tests. I created tests on my master branch and early everything worked well, no matter what branch I was using. But when I switched again to master branch, tests did not work anymore.
What helped me was to:
close intellij -> delete .idea file from directory -> open project again by pom.xml (idk if it matters what way you open the project, but first time when I tried to open it normally by intellij, it still dit not work)  -> reload all maven projects from right menu -> rebuild project and that's it, everything works now

A: I did re-import all maven projects. This worked for me.

A: If you added a library to the project structure (rather than via maven, that would be different), be sure it is included as a dependency for the relevant module.
Project Structure -> Modules -> Dependencies

A: I tried to "Maven > Reimport" but the only thing that actually fixed it was to close the project, delete the .idea directory, and reopen the project.

A: It's a very annoying problem which happens quite often. Especially after switching to a different git branch. It wasted me way too much time to troubleshoot this kind problem. I have tried all the methods above. But I can't find a reliable way. Here I just summarize those steps which could help in my situation. Jetbrains, please fix this issue to save your customer's precious time.

*

*Make sure do a success command line build (If UT failed, please ignore UT by using -Dmaven.test.skip=true.

*In the "Maven Projects" view, try to use "reimport" all the maven project.

*In the file menu, use "Invalidate Caches"

*Delete .idea folder, basically create the workspace from scratch. (That's the only reliable way can solve this issue)

A: In my case the problem was that there was a different repository directory configuration in IntelliJ and in settings.xml file.
Check both repository directories are the same:
IntelliJ (File > Settings > Build,Execution,Deployment > Build Tools > Maven )

settings.xml
(usually in C:\Users\myuser\.m2 or /home/myuser/.m2)
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">

  ...
  <localRepository>C:\Users\myuser\.m2\repository</localRepository>
  ...
</settings>

After fixing directories run:

*

*Generate Folders and Update Sources for All Projects

*Reimport all maven projects

A: Tried all the above approaches, didn't work.
Finally running maven clean install solved it!

A: I had the same problem. I fixed it by applying the android-apt plugin https://bitbucket.org/hvisser/android-apt

A: Maven reimport, rebuild and invalidate caches did not work. I solved it by opening a terminal and executing maven clean install in the root folder project. (IntelliJ was opened and I was able to see the IDE updating and triggering reindexation while maven was doing his job)

A: The above solutions didn't work for me. I had to add the dependency explicitly in the pom.xml.
Just add your jar under resources/library and then add it as a dependency in your pom.xml like:
        <dependency>
            <groupId>your-jar-group-id</groupId>
            <artifactId>artifact-id</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/library/name-of-jar.jar</systemPath>
        </dependency>

Try this out if none of the above work.

A: *

*Delete your .idea/

*Invalidate and Restart Cache afterwards

*Re-import project

A: If you do not want to destroy .idea, you can try :

*

*open Project Structure > Modules

*unmark the java folder as a source folder

*apply / rebuild

*then mark it again as a source folder

*rebuild

A: In case you're facing very weird "unable to resolve java, sun packages problem", try the following:

*

*Open Project Structure and change Project SDK to another version, example: java 8 -> 9; 11->13, etc, and wait until it re-index all jdk's jars. Switch between jdks with same version may not work! (Ex: jetbrains jdk11 -> openjdk 11)

*Open a new project (or create a empty one); pause new project's indexing; close the old one; start indexing; open the old project and pause the new project's indexing and wait.

A: I tried compile a java 8 project with JDK 12 and has the same issue.
None of previous answer solved my problem.
I changed o Shortel Command Line to "JAR Manifest" and worked like a charm.

A: Follow the steps below:

*

*Ctrl+Shift -> Type Invalidate Caches -> Chech all options except: Ask before...

*Superior menu -> Build -> Rebuild Project

A: I created two new classes under a new package and used it in rest of the code, Intellij was able to resolve these no red highlights were shown in the intellij editor.
While building it was showing package doesn't exist error.
I tried everything from gradle clean build, rebuild project, clear .idea and .gradle and reimporting the project, clearing the gradle local cache but nothing was working.
Finally I refactored the name of the new package and this time intellij was able to recognize the new classes and it started working.

A: Invalidate caches worked for me but it's too long to recover the caches so I don't have the patience to wait for it. I found another way to solve it in my case. "Repair IDE" step 3 (delete Package search project caches) worked for me perfectly

A: package com.example;

import com.sun.jna.Library;
import com.sun.jna.Native;

public class C {
    public interface Kernel32 extends Library {
        public void OutputDebugStringA(String Text);
        public void DebugBreak();
        public void Sleep(int a);
    }

    public static int incint(int in1)
    {
        testpkg.xxxBird.Say("xxxee"); //only use this statement to call external lib
                                      //I don't use "import" statement.
        return in1*2;
    }
}

I am using intellij idea.
You need to add testpkg path in project dependency.

A: I faced the same situation in ver 2022.1.4. I tried all solutions from the first answer, nothing worked except the delete the ".idea" folder.
Even through many friends mentioned this solution, I couldn't find this folder, I was looking around user profile and AppData folders. This folder was in fact created under the project folder itself.
I closed the project, and re-opened after deleting this folder.. everything back to normal. It felt like the "Intel" was lost and the IDE was only "lij" for sometime.. lol

A: I tried all answers, but eventually what helped me was changing the Maven from bundled to my own Maven distribution.
I think vice versa (changing from own to bundled) will help as well.

A: For me worked:

*

*Reimport

*Invalidate Caches/ Resart

*Rebuild Project


text:
Q: Mysql.Data and Azure Mysql error 'Table 'mysql.proc' doesn't exist' When I try to execute the stored procedure against Azure MySQL version 8.0.15 server using following code I get the error saying 'Table 'mysql.proc' doesn't exist'. This error does not happen with older versions. some search says to use MySQL_upgrade but I don't get that to work against azure MySQL. How do I overcome this error? Everything works fine when I connect to local MySQL version which is same as azure hosted.
Sample code
static async Task Main(string[] args)
    {
        var builder = new MySqlConnectionStringBuilder
        {
            Server = "myserver.mysql.database.azure.com",
            Database = "mydb",
            UserID = "myserver@myserver",
            Password = "password",
            SslMode = MySqlSslMode.Prefered,
        };

        using (var conn = new MySqlConnection(builder.ConnectionString))
        {
            Console.WriteLine("Opening connection");
            await conn.OpenAsync();

            using (var command = conn.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "prc_myprocedure";

                var reader = await command.ExecuteReaderAsync(CommandBehavior.Default);
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetValue(0));
                }
            }

            Console.WriteLine("Closing connection");
        }

        Console.WriteLine("Press RETURN to exit");
        Console.ReadLine();
    }
}

Complete error:
Unhandled exception. MySql.Data.MySqlClient.MySqlException (0x80004005): Table 'mysql.proc' doesn't exist
   at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
   at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.SchemaProvider.GetProcedures(String[] restrictions)
   at MySql.Data.MySqlClient.ISSchemaProvider.GetProcedures(String[] restrictions)
   at MySql.Data.MySqlClient.ISSchemaProvider.GetSchemaInternal(String collection, String[] restrictions)
   at MySql.Data.MySqlClient.SchemaProvider.GetSchema(String collection, String[] restrictions)
   at MySql.Data.MySqlClient.MySqlConnection.GetSchemaCollection(String collectionName, String[] restrictionValues)
   at MySql.Data.MySqlClient.ProcedureCache.GetProcData(MySqlConnection connection, String spName)
   at MySql.Data.MySqlClient.ProcedureCache.AddNew(MySqlConnection connection, String spName)
   at MySql.Data.MySqlClient.ProcedureCache.GetProcedure(MySqlConnection conn, String spName, String cacheKey)
   at MySql.Data.MySqlClient.StoredProcedure.GetParameters(String procName)
   at MySql.Data.MySqlClient.StoredProcedure.CheckParameters(String spName)
   at MySql.Data.MySqlClient.StoredProcedure.Resolve(Boolean preparing)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at AzureMySqlExample.MySqlUpdate.Main(String[] args) in C:\Users\sammo\source\repos\ConsoleApp1\Program.cs:line 31
   at AzureMySqlExample.MySqlUpdate.<Main>(String[] args)

A: ISSUE: You are getting the below error because when you start a connection to Azure MySQL, the gateway of Azure MySQL will first send back a greeting package with a default server version "5.6.42.0 MySQL Community Server (GPL)". This make the MySQL.Data driver treat the server version as 5.6. But actually it is 8.0 and in MySQL 8.0, the table mysql.proc not exists anymore.
Workaround: You can use ProxySQL to fix the version issue:

*

*Set up ProxySQL for Azure MySQL
https://techcommunity.microsoft.com/t5/Azure-Database-for-MySQL/Load-balance-read-replicas-using-ProxySQL-in-Azure-Database-for/ba-p/880042

*Update the server version in ProxySQL
Connecting to ProxySQL with admin account, run the following commands.
a.  mysql –u admin –padmin -h 127.0.0.1 -P 6032
b.  UPDATE global_variables SET variable_value='' WHERE variable_name='mysql-server_version';
c.  load mysql variables to runtime;
d.  save mysql variable to disk;

A: To complement Mike Ubezzi's answer (credit to this post to point me in the right direction), the solution was to simply change the port from 3306 to 3309 in the database connection string. More information here.
In my case, I was running an ASP.NET app linked to a MySQL database version 8.0.  After editing the connection string in the web app's configuration settings and restarting the web app, my stored procedures executed as expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ container contents traits confusion I want to be able to select a different class to instantiate at compile time based on the type of contents of a container class. Both Clang and GCC give errors for the code below so I expect there is something wrong with it, even though it behaves correctly using Visual Studio. Any ideas?
#include <iostream>

template <bool, class T = void>
struct enable_if {};

template <class T>
struct enable_if<true, T> {
  typedef T type;
};

struct a {};
struct b {};

struct a_container {
  typedef a contents_type;
};

struct b_container {
  typedef b contents_type;
};

template <class T>
struct is_an_a { enum { value = false }; };

template <>
struct is_an_a<a> { enum { value = true }; };

template <class container_type>
struct container_traits {
  typedef typename container_type::contents_type value_type;
};

template <class container_type>
struct is_an_a_container {
  enum { value = typename is_an_a<typename container_traits<container_type>::value_type>::value };
};

template<class container_type, class enable = void>
struct S {
  void operator()() {
    std::cout << "Not an A\n";
  }
};

template<class container_type>
struct S<container_type, typename enable_if<is_an_a_container<container_type>::value>::type> {
  void operator()() {
    std::cout << "Got an A\n";
  }
};

int main() {
  S<a_container>()();
  S<b_container>()();

  return 0;
}

From Visual Studio, the output is:
Got an A
Not an A

GCC fails with:
35: error: expected `(' before '}' token

Whilst Clang fails with:
35 : error: expected '(' for function-style cast or type construction

I can work round the problem by inlining the definition of is_an_a_container into the second version of S (e.g. below), but it seems to me a little more obscure and I'd like to understand the error.
template<class container_type>
struct S<container_type, typename enable_if<is_an_a<typename container_traits<container_type>::value_type>::value>::type> {
  void operator()() {
    std::cout << "Got an A\n";
  }
};

Or maybe there is a neater solution to achieving the goal? NB: I have to use the container_traits.

A: template <class container_type>
struct is_an_a_container {
  enum { value = typename is_an_a<typename conntainer_traits<container_type>::value_type>::value };
                 ^^^^^^^^                                                                  ^^^^^ // this is not a type
};

Just remove the typename
template <class container_type>
struct is_an_a_container {
  enum { value = is_an_a<typename conntainer_traits<container_type>::value_type>::value };

};


text:
Q: Uniqueness of abelian group structure on a given set and recursive algorithms If we have some function $f$ under $\mathbb{Z}$ and
$$f(a, f(b, c)) = f(f(a, b), c)$$
$$f(a, b) = f(b, a)$$
$$f(a, 0) = a$$
$$f(a, -a) = 0$$
meaning $f$ is an abelian group with an identity element of $0$. Is that enough to prove that $f$ is addition? In other words, is an abelian group with a specific identity element unique within a certain domain? Similarly, could multiplication be proved if we had an abelian group with an identity element of $1$?
More generally, I'm trying to figure out if it is possible to deduce an algorithm (set of simple unambiguous recursive rules) from a set of axioms for some operation under a domain (axioms could perhaps be thought of as a form of ambiguous recursion). The first step is to figure out if a set of axioms can define the uniqueness of an operation. The more difficult step is to actually infer the specific recursive steps necessary.

A: No, this would imply that all (infinite) countable groups are isomorphic (as the underlying sets of any two such groups are in bijection), but that is not the case: For example both $(\mathbb{Z}, +)$ and $(\mathbb{Z} \times \mathbb{Z}, +)$ are countable, but they are not isomorphic, because the former is generated by a single element but the latter is not.


text:
Q: Parsing json using jq I am trying to get the difficulty value out of a JSON structure using jq on the linux command line:
./jq '{result: .difficulty}' status.txt

(The JSON is held in a file called status.txt - shown below) But try as I might I keep getting:
{
  "result": null
}

Returned, can someone tell me what I am doing wrong?
{
   "result":{
      "version":1030000,
      "protocolversion":60001,
      "walletversion":60000,
      "balance":2600.00020000,
      "blocks":16042,
      "connections":6,
      "proxy":"",
      "difficulty":28.20775972,
      "testnet":false,
      "keypoololdest":1382340615,
      "keypoolsize":94,
      "paytxfee":0.00000000,
      "mininput":0.00010000,
      "unlocked_until":0,
      "errors":""
   },
   "error":null,
   "id":"curltest"
}

A: Try to access to result object and inside it extract the difficulty value:
./jq '.result.difficulty' status.txt

It yields:
28.20775972


text:
Q: Internet conection problem when updating Ubuntu 12.04 to 14.04 Server Upgraded my server's software from Ubuntu 12.04 to Ubuntu 14.04 and now the server cannot access the internet.
I can ping devices on my LAN, including my modem. When I try to ping any site on the internet (8.8.8.8 for example), I get 100% packet loss. I feel like this may be a DNS issue from what I've been reading. I've added the following line to /etc/network/interfaces :
dns-nameservers 8.8.8.8 8.8.4.4

with no success.
Relevant outupt of ifconfig :
eth0     Link encap:Ethernet  HWaddr 64:31:50:1f:88:72
          inet addr:192.168.0.222  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::6631:50ff:fe1f:8872/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:575229 errors:0 dropped:55 overruns:0 frame:0
          TX packets:10313 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:35490659 (35.4 MB)  TX bytes:898607 (898.6 KB)

output of route -n:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 eth0
192.168.0.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

Content of /etc/network/interfaces file :
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static

address 192.168.0.222
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1
dns-nameservers 8.8.8.8 8.8.4.4

output of tracepath 8.8.8.8 :
1?: [LOCALHOST]                                         pmtu 1500
1:  192.168.0.1                                           0.446ms
1:  192.168.0.1                                           0.444ms
2:  no reply`
3:  no reply`
//continues with no reply until interrupted

A: Looks like an unusual one this...
Firstly I sincerely doubt that DNS is involved, though if you are using 8.8.8.8 et al for your DNS then DNS will fail because you can't reach those servers.
Firstly it can't be your LAN configuration because you can ping your local gateway, so traffic to and from it works.
The biggest hint is the double listing of your gateway in the trace. Your gateway should only be shown once, and this hints at a loop at your gateway - but all your other systems work fine, and according to what you write, it's only the local system that changed.
The only thing that I can remotely think of is if you had an iptables rule roughly like this:
iptables -t nat -D POSTROUTING ! -d 192.168.0.0/24 -j SNAT --to-source 1.2.3.4

Where 1.2.3.4 is some bogus or possibly previously valid IP address that no longer works.
This would let local traffic work but anything going out beyond the local network would break because replies would go to the wrong place. Your gateway may block traffic like that because it is in essence 'spoofed' traffic.
I think you would get a good hint to the issue with some traffic inspection at your gateway if it is at all possible.
If you can't do that - quite understandable - then maybe set up another Linux box on your network and make it the default gateway for this faulty system, and then you can inspect the traffic it is generating. This is assuming that the fault is on the upgraded system. If you configured that 2nd Linux box to ip_forward and make it's gateway the 192.168.0.1 device you might also see more useful info to help nail down the cause.
Will be interesting to see what it was when you finally get it sorted.

A: Try to go into "/etc/resolv.conf" and below the lines starting with #'s add these lines:
 "nameserver 8.8.8.8"
 "nameserver 8.8.4.4"
See if you can connect after doing this. Do not reboot after changing the file, just save it and test your connection. If this works then it was a DNS problem. The changes made to the file will be undone after a reboot.

A: I had exactly the same situation - no internet connection, no ping to outside, no ping from router to the box. But a working SSH connection from another workstation in the same LAN.
The cause was the router who was blocking the new box as it had the same IP as the replaced old box, but a different MAC address.
As soon as I changed the IP everything worked.


text:
Q: What's happening to my cash? Playing a tile on Bloons Monkey City Mobile (on Android) later rounds don't seem to give me as much cash as I expect. Normally you get $1 per pop, but for eg on a tile with 29 rounds I am doing round 27 and popping hundreds of bloons, but my cash is only ticking up slowly.
To confirm I started round 29 with $538 and popped at least 12 MOABs, a lot of ceramics, and one ZOMG. I finished with $1099, which seems a lot less than it should be.
Is there some sort of diminishing returns at later rounds? Is it that certain monkeys don't give a reward for popping?

A: Apparently, this has been a mechanic in the Bloons games for a long time, and that is why Banana Farms are really important.
Here is the amount of cash you get per pop :
Difficulty: Hardcore

*

*Wave 1 – 15: $1

*Wave 16 – 22: $0.5

*Wave 23 – 27: $0.2

*Wave 28+: $0.05

Difficulty: Normal

*

*Wave 1 – 11: $1.1

*Wave 12 – 15: $1

*Wave 16 – 22: $0.65

*Wave 23 – 27: $0.2

*Wave 28+: $0.05

More info about BMC in this post.


text:
Q: Transferring user input from one page to another I am making a website that allows students to find upcoming study sessions for their courses. I am doing this in Django and HTML. A student uploads their courses to the site and they are shown on the courses page as buttons (ex. CS 101 - Intro to CS). When a student clicks on one of their courses (button), it is supposed to bring them to a page that shows available study sessions for that course. I am stuck because I do not know how to properly filter the available study sessions on the next page based on which course is clicked. Is there a way to store the info of the course as a variable so when the button is clicked I can use that variable to filter the results? EDIT: I have made these changes and now I am getting a ValueError too many values to unpack expected 2. I am almost certain it is happening in my views.
Here is the page that shows a user's courses:

    {% if courses_list %}
    {% for course in courses_list %}
    {{ course.subject }} {{ course.number}}-{{course.name}}

    {% endfor %}
    {% else %}

You have not added any courses yet!

    {% endif %}

And here is the page that I am trying to filter the list of study sessions (which have a field course that is a ForeignKey to the Courses model):

Upcoming Study Sessions

    Back to My Courses

      <button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }}
 Location: {{ session.location }} </button>

View for the template:
def CourseSessionView(request, course_pk):

course_wanted = Course.objects.get(id=course_pk)
try:
    return Study.objects.filter(course=course_wanted)
except:
    return messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')

Model for course and session:
class Course(models.Model):
    SUBJECT_CHOICES = [
        ('AAS', 'AAS')
    ]
    subject = models.CharField(
        max_length=4, choices=SUBJECT_CHOICES, default='')
    number = models.PositiveSmallIntegerField(
        validators=[MaxValueValidator(9999)], default=0)
    name = models.CharField(max_length=100, default='')
    roster = models.ManyToManyField(
        Student, blank=True, related_name="courses")
    # Use [Student object].courses.all() to see all of a student's courses

    def __str__(self):
        return f"{self.subject} {self.number} - {self.name}"

class Study(models.Model):
    organizer = models.ForeignKey(Student, on_delete=models.CASCADE)
    date = models.DateTimeField()
    # Use [Student object].studies.all() to see all of a student's study sessions
    attendees = models.ManyToManyField(Student, related_name="studies")
    location = models.CharField(max_length=30)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.date} - {self.location}"

Url:
path('<int:course_pk>/sessions/',
         views.CourseSessionView, name='course-session')

A:
Note: The function based views' name doesn't require to be in PascalCase as in your case, it should be in snake_case.

The page that show the user's courses, there you need to pk of courses:

    {% if courses_list %}
    {% for course in courses_list %}
    {{ course.subject }} {{ course.number}}-{{course.name}}

    {% endfor %}
    {% else %}

You have not added any courses yet!

    {% endif %}

Your view for the template, i am defining it in snake_case, since its recommended way.
def course_session(request, course_pk):
    course_wanted = Course.objects.get(id=course_pk)
    study_courses=''
    try:
        study_courses= Study.objects.filter(course=course_wanted)
    except:
        messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')
    else:
        return render(request,'anyfolder/anyfile.html',{'study_courses':study_courses})

    return render(request,'anyfolder/anyfile.html') #then it will show only your error message.

Your url in urls.py be like:
path('any_route_name/<int:course_pk>/', views.course_session, name='course_session')

Note: Never forget to pass / at the end of your url or route_name.

Then, in your any template file you can access it and run loop:
{% for study in study_courses %}
{{study.organizer}},{{study.date}}
{% endfor %}

Then, you can access all its properties, and take benefit of ManyToOne relation.

A: This is going to be a very general type of answer since you are not providing your models or your views, but I think the idea would be the following.
First, in your template you can pass a parameter for the course number in the url:
your_template.html

   {{ course.subject }} {{ course.number}}-{{course.name}}

Then in your view you can access that value, and from it get the course:
views.py
def the_view_name(request, course_pk):
    # Here you now have access to the course's primary key, pk, so you can get the
    # course and filter the study sessions by that course, etc...

You will need to modify the urls.py so the view can accept this new parameter:
urls.py
path('the_view_name/<int:course_pk>', views.the_view_name, name='the_view_name'),

EDIT
Make the following changes:
First to your views.py:
def CourseSessionView(request, course_pk):

    try:
        course_wanted = Course.objects.get(id=course_pk)
    except:
        return messages.error(request, 'course not found')

    study_sessions = Study.objects.filter(course=course_wanted)

    if study_sessions.count() < 1:
        return messages.error(request, 'There are no upcoming study sessions at this time for the requested course')

    context = {
        'study_sessions': study_sessions,
    }

    return render(request, 'study/your_template_file.html', context)

Then in your html

Upcoming Study Sessions

Back to My Courses

  {% for session in study_sessions %}

   <button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }}
 Location: {{ session.location }} </button>

  {% endfor %}


text:
Q: Create spotify playlist follow botton on my website I want to create button that users can follow playlists in spotify from my site.
I checked web developer spotify Doc and create button and a input and create app for Client ID in developer.spotify.com then put js code in site . when user click on button he/she should be log in and its ok but after that nothing happen and followers dont be change.

(function() {

    function login(callback) {
        var CLIENT_ID = '02dc3058bff748e5ba6c814b8366edfs5';
        var REDIRECT_URI = 'http://musatamusic.com/demo-submission';
        function getLoginURL(scopes) {
            return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +
              '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +
              '&scope=' + encodeURIComponent(scopes.join(' ')) +
              '&response_type=token';
        }

        var url = getLoginURL([
            'playlist-modify-public'
        ]);

        var width = 450,
            height = 730,
            left = (screen.width / 2) - (width / 2),
            top = (screen.height / 2) - (height / 2);

        window.addEventListener("message", function(event) {
            var hash = JSON.parse(event.data);
            if (hash.type == 'BQD4D9oZwlG2u1cLOcx8P7lJGs63ZA7s0eTKi9O6wI8NmvGEBQI6JCnHAn_jtg_f1_7rWfBF_nD8saECxvAAJbc06ci1p-xa5qMGGWnc3g84byOKPiULBO8J80qEtxxdsJkdZtIH4O9FY7QdHCwq0ODU6fKD9ObazgrrdkxxWz78CMhe6HpaC3jtIkZAaUAog2gjjstbFXnczUxjnNzFAgAs-KUISuHH8F_Fs') {
                callback(hash.access_token);
            }
        }, false);

        var w = window.open(url,
                            'Spotify',
                            'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left
                           );

    }

    function followPlaylist(accessToken, playlistUri) {
        var parts = playlistUri.split(':');
        $.ajax({
            url: 'https://api.spotify.com/v1/users/zcszsah76l94tltmiget761mi/playlists/4ZxTESEv0m00o2kKq47745/followers',
            headers: {
               'Authorization': 'Bearer BQD4D9oZwlG2u1cLOcx8P7lJGs63ZA7s0eTKi9O6wI8NmvGEBQI6JCnHAn_jtg_f1_7rWfBF_nD8saECxvAAJbc06ci1p-xa5qMGGWnc3g84byOKPiULBO8J80qEtxxdsJkdZtIH4O9FY7QdHCwq0ODU6fKD9ObazgrrdkxxWz78CMhe6HpaC3jtIkZAaUAog2gjjstbFXnczUxjnNzFAgAs-KUISuHH8F_Fs'
            },
            method: 'PUT',
            success: function() {
                $(".follow-us").remove();
                $(".popup").append("
THANKS FOR FOLLOWING PLAYLIST
");
                $(".popup").append("GO TO SUBMIT");
            },
            dataType: 'html',
            error: function(e) {
                $(".follow-us").remove();
                $(".popup").append("
THERE IS A PROBLEM
");
            }
        });
    }

    var followButton = document.getElementById('follow-us'),
        playlistUriInput = document.getElementById('playlist-uri');

    followButton.addEventListener('click', function() {
        login(function(accessToken) {
            followPlaylist(accessToken, playlistUriInput.value);
        });
    });

})();
<input type="text" id="playlist-uri" value="spotify:user:zcszsah76l94tltmiget761mi:playlist:4ZxTESEv0m00o2kKq47745" hidden>
<button class="follow-us" id="follow-us">

   FOLLOW ON SPOTIFY
</button>

what is wrong???


text:
Q: Ebean delete object not refresh realtionship The following problem makes me confused. I would like to delete an measurement value from an relationship and the referenced object should bee update the measurements. So what is my problem, if I delete an measurement, that works fine, but if I get the all measurements from cure object, I see that the delete object is inside. What is the best ways to refresh the relationship?
Measurement.java
@Entity
@Table(name = "measurements")
public class Measurement extends Model {

    @Id
    public Long id;

    @Formats.DateTime(pattern = "dd.MM.yyyy")
    public Date created = new Date();

    @Constraints.Required
    public double weight;

    @Constraints.Required
    public double belly;

    @Constraints.Required
    public double thigh;

    @Constraints.Required
    public double gluteal;

    @ManyToOne
    @JsonBackReference
    public Cure cure;
}

Cure.java
@Entity
@Table(name = "cures")
public class Cure extends Model  implements Comparable<Cure> {

    @Id
    public Long id;

    @Formats.DateTime(pattern = "dd.MM.yyyy")
    public Date created = new Date();

    public int startHour = 10;

    @ManyToOne
    @JsonIgnore
    public Challenge challenge;

    @JsonManagedReference
    @OneToMany
    public List<Measurement> measurements;
}

My action that should bee handle the delete
public static Result delete(Long id){
    Measurement measurement = Measurement.find.byId(id);

    if(measurement == null && !measurement.belongsToUser(user)){
        return noContent();
    }

    measurement.delete();
    return ok();
}

A: Well i didn't see the finder in your models class. Implement those as follow
public static Finder<Long, Measurement> find = new Finder<Long, Measurement>(Long.class, Measurement.class);

then try. Also ebean has lots of issue you can use raw query to delete as follow
SqlUpdate deletObject = Ebean
                        .createSqlUpdate("delete from table_name where id = "
                                + id);
deletObject.execute();


text:
Q: UIButton Tag not being assigned indexPath.row after 6 cells I have a weird problem going on here. I have a TableView and I assign the indexPath.row to the tag of a UIButton so I can pass that tag as a parameter on a segue and give an object to the next view controller. Everything works hunky dory until I go past 6 cells in the TableView, when pressing the button passes the wrong object from the array. I decided to put in some NSLogs to see what was happening and I find the results quite bizarre. The assignment buttonForApplyingTag.tag = indexPath.row; happens just after the NSLogs and is the last statement before return cell;. Since the actual value of indexPath.row is correct, the objects from the array are getting loaded properly. It's just the buttons that are causing problems. Here is my output:
2012-11-28 19:01:57.596  IndexPath.row: 0
2012-11-28 19:01:57.596  IndexPath.Row from Tag: 0
2012-11-28 19:01:57.597  SearchResults Count: 100
2012-11-28 19:01:57.598  IndexPath.row: 1
2012-11-28 19:01:57.598  IndexPath.Row from Tag: 1
2012-11-28 19:01:57.598  SearchResults Count: 100
2012-11-28 19:01:57.599  IndexPath.row: 2
2012-11-28 19:01:57.600  IndexPath.Row from Tag: 2
2012-11-28 19:01:57.600  SearchResults Count: 100
2012-11-28 19:01:57.601  IndexPath.row: 3
2012-11-28 19:01:57.601  IndexPath.Row from Tag: 3
2012-11-28 19:01:57.602  SearchResults Count: 100
2012-11-28 19:01:57.602  IndexPath.row: 4
2012-11-28 19:01:57.603  IndexPath.Row from Tag: 4
2012-11-28 19:01:57.603  SearchResults Count: 100
2012-11-28 19:01:57.604  IndexPath.row: 5
2012-11-28 19:01:57.605  IndexPath.Row from Tag: 5
2012-11-28 19:01:57.605  SearchResults Count: 100
2012-11-28 19:02:02.004  IndexPath.row: 6
2012-11-28 19:02:02.004  IndexPath.Row from Tag: 6
2012-11-28 19:02:02.005  SearchResults Count: 100
2012-11-28 19:02:03.993  IndexPath.row: 7
2012-11-28 19:02:03.993  IndexPath.Row from Tag: 0
2012-11-28 19:02:03.993  SearchResults Count: 100
2012-11-28 19:02:17.846  IndexPath.row: 8
2012-11-28 19:02:17.846  IndexPath.Row from Tag: 0
2012-11-28 19:02:17.846  SearchResults Count: 100
2012-11-28 19:02:18.482  IndexPath.row: 9
2012-11-28 19:02:18.482  IndexPath.Row from Tag: 0
2012-11-28 19:02:18.482  SearchResults Count: 100

Sorry for the excessive amount of lines, but you get the idea. This trend continues all the way down to 100, meaning that the buttons are not receiving the correct tag. Even weirder is the fact that when the button is clicked on the cells with a false indexPath.row tag, another tag is apparently made up and I get a low value tag. Furthermore, when the cell 6 has partially appeared at the bottom of the TableView, even though it's clear the cell has actually loaded, the NSLogs haven't been posted to the debugger, and therefore the button fails and returns a tag of 5. So there are actually 3 issues with this way of doing things.
Really, what I want to ask is why is this strange behaviour happening, and how can I fix it? And secondly, since this just appears to be a disaster, is there a better way of passing down the indexPath.row value so I can get an object from my array when the button is clicked?
Thanks for any help.
Regards,
Mike
P.S. I'm a complete amateur so if you could explain it in Lehmann's terms, I'd appreciate it.
EDIT: Here's the code where I actually assign the tag to the button, as requested.
    UIButton *buttonForApplyingTag = (UIButton *)[cell viewWithTag:1004];

    NSLog(@"IndexPath.row: %d", indexPath.row);
    NSLog(@"IndexPath.Row from Tag: %d", buttonForApplyingTag.tag);
    NSLog(@"SearchResults Count: %d", [searchResults count]);
    buttonForApplyingTag.tag = indexPath.row;

    return cell;

EDIT 2: Here's the entire cellForRowAtIndexPath code:
if (isLoading) {
    return [tableView dequeueReusableCellWithIdentifier:LoadingCellIdentifier];
} else if ([searchResults count] == 0) {
    return [tableView dequeueReusableCellWithIdentifier:NothingFoundCellIdentifier];
} else {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchResultCellIdentifier];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [tableView setSeparatorColor:[UIColor grayColor]];
    /* Then we do a load of assignments for labels in the cell, then we reach the tagging code. */

SearchResultCellIdentifier comes from this: static NSString *const SearchResultCellIdentifier = @"SearchResultCellProto";

A: It looks like what you want to do is have buttons in cells, and then know which cell's button was pressed when the button action occurs.  Using tags is a reasonable idea, but tough to implement because the tag needs to change when the cell gets reused (and ends up at a different index path).
Here's a better approach:  Add the buttons using a constant tag (or no tags), then on the click action do this...
- (IBAction)pressedButtonInMyCell:(id)sender {

    UIButton *button = (UIButton *)sender;

    // find the cell that contains the button, this might be one or two levels
    // up depending on how you created the button (one level in code, two in IB, probably)
    UIView *view = button.superview;
    while (view && ![view isKindOfClass:[UITableViewCell self]]) view = view.superview;

    UITableViewCell *cell = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSLog(@"cell is in section %d, row %d", indexPath.section, indexPath.row);
}

A: This line gets the button from the cell:
UIButton *buttonForApplyingTag = (UIButton *)[cell viewWithTag:1004];

However, in reused cells, the tag is not 1004. It is in fact the tag that was set when the cell was used previously. So buttonForApplyingTag will likely be nil on a reused cell and the whole system fails.
It's better to create a subclassed cell and attach the UIButton to an instance variable.
Subclassing:
Create a new UITableViewCell subclass, let's call it CustomCellView.  Make sure you instantiate this class in cellForRowAtIndexPath instead of the regular UITableViewCell . Add an instance variable to it called theButton. Then create and assign buttonForApplyingTag to this instance variable. It's best to do this in the init of your subclass. Then in cellForRowAtIndexPath, you don't have to create a button, you just use cell.theButton.
But, even better would be to just store the 'tag' in a instance variable integer of your subclass.


text:
Q: Obscure Scala Error Message What's wrong with that Scala Code?
trait A[E]
trait B[E, F[_]] extends A[F[E]]
trait C[E]
trait D[E] extends B[E, C[E]]

It produces the error message "C[E] takes no type parameters, expected: one"
Is it a compiler (2.10.3) bug?
Thank you

A: I think D should be defined as:
trait D[E] extends B[E, C]

The second generic argument to B should take a single type parameter, while C[E] doesn't take any.


text:
Q: Product of Independent Random Variables - Conditional Expectation Let $X_1,X_2,\ldots$ be independent random variables, not necessarily iid, such as $\forall\; i\geq{1}\; X_i\geq{0}$,$\mathbb{E}(X_i)<\infty$ and
$\mathbb{E}(X_i)\!=\!\mathbb{E}(X_j)$. Assume $N\in\{1,\ldots ,k\}$ and $N, X_i$ are independent $\forall\; i\geq{1}$. Calculate $\mathbb{E}(\prod_{i=1}^{N}{X_i})$

So, I asked my teacher and he said that N is a random variable.
I know that
(a) if $X_1,X_2,\ldots$ are independent random variables $=> \mathbb{E}(\prod_{i=1}^{n}{X_i})\!=\!\mathbb{E}(X_1)\ldots\mathbb{E}(X_n)$
(b) $N$ and $X_i$ are independent then $\mathbb{E}(X_i|N)\!=\!\mathbb{E}(X_i)\;\;\forall\;i\geq{1}$
(c) $\mathbb{E}(X_i)\!=\!\mathbb{E}(X_j)\;\;\forall\;i,j$
Is this all right?
$\mathbb{E}(\prod_{i=1}^{N}{X_i})\!=\!\sum_{j=1}^{k}\mathbb{E}(\prod_{i=1}^{j}{X_i}|N=j)P(N=j)$
And, $\mathbb{E}(\prod_{i=1}^{j}{X_i}|N=j)\!=\!\frac{\mathbb{E}(\prod_{i=1}^{j}{X_i},\Large{1}_{\{N=j\}})}{P(N=n)}\!=\!
\frac{\mathbb{E}(X_1|N)\ldots\mathbb{E}(X_j|N)}{P(N=n)}\!=\!\frac{\mathbb{E}(X_1)\ldots\mathbb{E}(X_j)}{P(N=n)}\!=\!\frac{[\mathbb{E}(X_1)]^j}{P(N=n)}$
Then,
$\mathbb{E}(\prod_{i=1}^{N}{X_i})\!=\!\sum_{j=1}^{k}\mathbb{E}(\prod_{i=1}^{j}{X_i}|N=j)P(N=j)\!=\!\sum_{j=1}^{k}\frac{[\mathbb{E}(X_1)]^j}{P(N=n)}P(N=n)\!=\!\sum_{j=1}^{k}[\mathbb{E}(X_1)]^j$

A: Denote $\mu=\mathbb EX_1$.
Your first steps are okay and proceeding we arrive at:$$\mathbb{E}\prod_{i=1}^{N}X_{i}=\sum_{j=1}^{k}\mathbb{E}\left(\prod_{i=1}^{j}X_{i}\mid N=j\right)P\left(N=j\right)$$$$=\sum_{j=1}^{k}\left(\mathbb{E}\prod_{i=1}^{j}X_{i}\right)P\left(N=j\right)=\sum_{j=1}^{k}\left(\prod_{i=1}^{j}\mathbb{E}X_{i}\right)P\left(N=j\right)=\sum_{j=1}^{k}\mu^{j}P\left(N=j\right)=\mathbb{E}\mu^{N}$$
The equality: $$\mathbb{E}\left(\prod_{i=1}^{j}X_{i}\mid N=j\right)=\mathbb{E}\prod_{i=1}^{j}X_{i}$$
is a consequence of the fact that the $X_{i}$ do not depend on $N$.
Actually we end up with an expression $\mathbb E\mu^N$ that depends on the distribution of $N$, as was to be expected.


text:
Q: Create boolean array by testing elements of another array I have a column of time array type (i.e. {06:00:00, 07:00:00, ...}) and want to compare each element of this array to see if it is between a from_time and to_time column (e.g. 09:00:00 in from_time and 18:00:00 in to_time), and then generate a boolean array in a new column (e.g. {True, False, ...}).

A: SELECT t.tbl_id, t.time_arr, a.bool_arr
FROM   tbl t, LATERAL (
   SELECT ARRAY (
      SELECT elem BETWEEN '09:00' AND '18:00'
      FROM   unnest(t.time_arr) WITH ORDINALITY u(elem, ord)
      ORDER  BY ord
      ) AS bool_arr
   ) a;

Requires Postgres 9.4.
SQL Fiddle with a simpler version for Postgres 9.3
There was a very similar question on dba.SE just yesterday. Answer with more details:

*

*Preserve order of array elements after join


text:
Q: Create directed Graph with movable nodes (with QT / Boost) I'm looking for a tool to create directed graphs where I can move the nodes around and expand / shrink the graph when I, for example, click on a node. I want to use the graph in a QT interface. I thought about trying the Boost Graph Library but it seems that I can only create an image file of the graph with it. I'm not that deep into BGL yet; so does anybody know if its possible to greate graphs with BGL where I can move the nodes around afterwards? And is it possible to use it in QT? Or are there other tools?

A: Try to remember a node-edge map doesn't inherently have any graphical representation. Hence why the Boost Graph Library may not provide the kind of GUI you want.
When you understand that part of the problem, your question closely resembles these questions:

*

*Recommendations for visualising a directed graph in a Web UI

*Java Directed Graph framework [closed]

*Open source libraries to design directed graphs

*Good User Interface for Directed Hierarchical Graphs
I've not personally seen an implementation of Qt which aims to be a directed graph user interface framework. However Qt would be quite capable, with it's QGraphicsScene class being a good starting point for you to look into.

A: Take a look at the Qt Visual Graph Editor project:
https://arsmasiuk.github.io/qvge/
Has base classes representing a graph + nodes/edges for inspiration. Supports reading and exporting various common graph markup formats (e.g. GraphViz files).

A: I know of the QuickQuanva and NodeGraphQt frameworks. The latter is written in Python, however.


text:
Q: find symmetric pairs using hash table(dictionary) in python I'm trying to get symmetric pairs with no duplicates, for example, from
L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

, I want to get like[(2,6), (3,5), (3,4)], finding symmetric pairs.
this is my full code,
L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

def find_symmetric_pairs(L):
    temp = {}
    temp_list = []
    for i in L:
        key, value = i
        for j in L:
            key_j, value_j = j
            if key == value_j and value == key_j:
                temp_list.append(tuple((key,value)))
    return temp_list

and also, I'm trying to implement this function by using python hashtable, how can I use hashtable?
The output looks like this
[(2, 6), (3, 5), (5, 3), (6, 2), (3, 4), (4, 3)]
but I want to show the output like above what I first told you...
[(2,6), (3,5), (3,4)]

A: You just need to add a check to see if the symmetric pair is already added to your result or not,
L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

res = set()

#Convert the list to a set
L = set(L)
# Iterate through the set
for t in L:
    # If the a tuple is present , and the reversed tuple is not in the result set already
    if (t[1], t[0]) in L and (t[1], t[0]) not in res:
        # Add it to result set
        res.add(t)

print(res)

The output will be
{(2, 6), (4, 3), (3, 5)}

Another approach is to reorder tuples so that first element is bigger then second, and count tuples via collections.Counter. The elements with count 2 will be the symmetric pairs
from collections import Counter

L=[(1,3), (2,6), (3,5), (4,7), (5,3), (6,2), (3,4),(4,3)]

#reorder tuple so that first element is bigger then second
L = [(t[1], t[0]) if t[0] < t[1] else t for t in L]

#Make a counter
c = Counter(L)

#Count elements with count 2
res = [key for key, value in c.items() if value == 2]
print(res)

The output will be
[(6, 2), (5, 3), (4, 3)]

A: There are no hash tables as such in Python, but you can use sets. The following combines the original set of tuples set(L) with a set of reversed tuples {(y, x) for x, y in L}. It later keeps only the pairs with the smaller first element:
pairs = set(L) & {(y, x) for x, y in L}
{(x,y) for x,y in pairs if x < y}
#{(2, 6), (3, 4), (3, 5)}

A: You could use a set if you want to disregard order. Specifically a frozenset will allow you to hash and therefore use Counter:
from collections import Counter
L_set_counter = Counter(map(frozenset, set(L)))

Now L_set_counter contains:
Counter({frozenset({2, 6}): 2, frozenset({3, 5}): 2, frozenset({3, 4}): 2, frozenset({1, 3}): 1, frozenset({4, 7}): 1})

And do find duplicates (v==2 to make it more specific, this is more generic):
dups = {k for k, v in L_set_counter.items() if v > 1}

And now dups contains:
{frozenset({3, 4}), frozenset({3, 5}), frozenset({2, 6})}


text:
Q: Passing focus from parent to children (as well as siblings) I have a search bar (the parent) that has 3 child components - location dropdown, calender(date picker) and duration dropdown. By default the location is selected to wherever the user's location is. I want a change of focus to date picker where the calendar dropdown is opened automatically after there's an interaction with the first dropdown (location dropdown) and same applies from the second input to the third input. How can I go about doing this?

Parent:
import React, { Component } from 'react';

import { Icon, Btn } from '@appearhere/bloom';

import Title from '../Title';
import LocationDropdown from '../LocationDropdown';
import AppearDateCalendar from '../AppearDateCalendar';
import DurationDropdown from '../DurationDropdown';

import css from './SegmentationBar.css';

import i18n from 'utils/i18n/i18n';

const t = i18n.withPrefix('client.apps.static.screens.home.header.segmentation');

type Props = {
  onLocationDropdownChange: Function,
  onDateChange: Function,
  onDurationChange: Function,
  onSubmit: Function,
  onMobileSearchClick: Function,
  fullSupport: boolean,
};

export default class SegmentationBar extends Component<Props> {
  render() {
    const {
      onLocationDropdownChange,
      onDateChange,
      onDurationChange,
      onSubmit,
      fullSupport,
    } = this.props;

    return (

        <Title />
        {fullSupport && (

              <LocationDropdown onDropdownChange={onLocationDropdownChange} />
              <AppearDateCalendar onDateChange={onDateChange} />
              <DurationDropdown onDropdownChange={onDurationChange} />

              <Icon name="search" />

        )}

    );
  }
}

Children:
1st dropdown:
import React, { Component } from 'react';
import i18n, { getCurrentLocale } from 'utils/i18n/i18n';

import { Icon } from '@appearhere/bloom';

import locationOrder from './locationOrder.json';
import locations from './locations.json';

import css from './LocationDropdown.css';

const t = i18n.withPrefix('client.apps.static.screens.home.header.segmentation.location');

type Props = {
  onDropdownChange: Function,
};

type Location = {
  key: string,
  name: string,
  country: string,
  placeId: string,
  searchString: string,
  priority: number,
};

class LocationDropdown extends Component<Props> {
  componentDidMount() {
    const selectedCity = this.findCitiesForCountry(locationOrder[getCurrentLocale()][0])[0];
    this.props.onDropdownChange(selectedCity.searchString, selectedCity.placeId);
  }

  citySorting = (a: Location, b: Location): number => {
    if (a.priority > b.priority) return 1;
    if (a.priority = b.name) return 1;
    return -1;
  };

  findCitiesForCountry = (countryKey: string): Array<Location> =>
    locations
      .filter((location: Location): boolean => location.country === countryKey)
      .sort(this.citySorting);

  handleDropdownChange = (event: SyntheticInputEvent<EventTarget>) => {
    const city = locations.find(
      (location: Location): boolean => location.key === event.target.value,
    );
    this.props.onDropdownChange(city.searchString, city.placeId);
  };

  renderSelectOptions = (countryKey: string): React.Node => {
    const cities = this.findCitiesForCountry(countryKey);
    return cities.map((city: Location): React.Node => (
      <option key={city.key} value={city.key}>
        {city.name}
      </option>
    ));
  };

  renderSelectOptionGroups = (): React.Node =>
    locationOrder[getCurrentLocale()].map((countryKey: string): React.Node => (
      <optgroup key={countryKey} label={t(countryKey)}>
        {this.renderSelectOptions(countryKey)}
      </optgroup>
    ));

  render() {
    return (

          <Icon name="search" />

        <select role="listbox" className={css.locationSelect} onChange={this.handleDropdownChange}>
          {this.renderSelectOptionGroups()}
        </select>

    );
  }
}

2nd input:
Calendar:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import i18n from 'utils/i18n/i18n';

import { DayPicker } from '@appearhere/bloom';
import moment from 'utils/moment/moment';
import cx from 'classnames';

import css from './AppearDateCalendar.css';

const t = i18n.withPrefix('client.apps.static.screens.home.header.segmentation.calendar');

type Props = {
  onDateChange: Function,
};

type State = {
  calendarOpen: boolean,
  month: moment,
  day: ?moment,
};

export default class AppearDateCalendar extends Component<Props, State> {
  state = {
    calendarOpen: false,
    month: moment(),
    day: undefined,
  };

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  handleClickOutside = (event: SyntheticMouseEvent<EventTarget>) => {
    const currentNode = ReactDOM.findDOMNode(this);
    if (currentNode && !currentNode.contains(event.target)) {
      this.setState({ calendarOpen: false });
    }
  };

  handleCalendarClick = () => {
    this.setState({ calendarOpen: !this.state.calendarOpen });
  };

  handleMonthChange = (_event: any, newMonth: moment) => {
    this.setState({ month: newMonth });
  };

  handleDaySelect = (_event, day: moment) => {
    this.props.onDateChange(day);
    this.setState({ day, calendarOpen: false });
  };

  dateDisplayText = (): string => {
    if (this.state.day) return this.state.day.format('Do MMM, YY');
    return t('choose_date');
  };

  render() {
    return (

{t('heading')}

{this.dateDisplayText()}

        {this.state.calendarOpen && (

            <DayPicker
              month={this.state.month}
              onInteraction={this.handleDaySelect}
              onMonthChange={this.handleMonthChange}
            />

        )}

    );
  }
}

3rd dropdown:
Duration:
import React, { Component } from 'react';
import i18n from 'utils/i18n/i18n';

import css from './DurationDropdown.css';

import durations from './durations.json';

const t = i18n.withPrefix('client.apps.static.screens.home.header.segmentation.duration');

type Props = {
  onDropdownChange: Function,
};

type Duration = {
  name: string,
  maxDuration: number,
  highValue: boolean,
};

export default class DurationDropdown extends Component<Props> {
  handleDropdownChange = (event: SyntheticInputEvent<EventTarget>) => {
    const durationIndex = event.target.value;
    const duration = durations[durationIndex];
    this.props.onDropdownChange(duration.maxDuration, duration);
  };

  renderDurationOptions = (): React.Node =>
    durations.map((duration: Duration, index: number): React.Node => (
      <option key={duration.name} value={index}>
        {t(duration.name)}
      </option>
    ));

  render() {
    return (

{t('heading')}

        <select role="listbox" className={css.durationSelect} onChange={this.handleDropdownChange}>
          <optgroup label={t('booking_duration')}>{this.renderDurationOptions()}</optgroup>
        </select>

    );
  }
}

A: You should read about React refs: https://reactjs.org/docs/refs-and-the-dom.html
You can create a ref per input, and pass it from your parent to the 3 children, and use ref.current.focus() in your dropdown handlers.


text:
Q: Is it possible to populate a datamodel using a form and send it to the controller from Razorpage? What is the best way to fill the field of a datamodel instance using a form on a Razorpage?
Is it possible to instantiate and submit a model directly from the Razorpage, or do i have to read each individual field of the form and assign them to a model instance in the controller?
Currently i am doing something like this: (not my actual code)
In the view:
<form method="post" action="some_action">
   <input type="text" name="name" />
   <input type="submit" value="submit" />
</form>

In the controller:
[HttpPost("some_action")]
Public IActionResult create_using_form()
{
  person p = new person();
  p.name = Request.Form["name"];
  /*do whatever with person, like save to a db*/
  return view();
}

I imagine there is a better solution, one where i dont have to populate every single field on my person object, one after the other. Any advice?

A: You don't need to deal with each field in the form separately. Just use strongly typed view by defining the data model by using @model.

Let say you have data model class DataModel.
Then short way:
public IActionResult Index()
{
    return View(new DataModel());
}

[HttpPost("some_action")]
public IActionResult create_using_form(DataModel model)
{
    if (ModelState.IsValid)
    {
        //...
    }
    return View("Index", model);
}

The Html.EditorForModel() helper was developed in ASP.NET Framework MVC, but it still has implementation in the ASP.NET Core MVC. The Html.EditorForModel() returns an HTML input element for each property in the model.
@model DataModel
<form method="post" action="some_action">
    @Html.EditorForModel()
    <input type="submit" value="OK" />
</form>


text:
Q: How to determine MIME-type of file by its content and URL via QT in Android? I have an URL of file like this content://com.android.providers.downloads.documents/document/msf%3A804. I use QMimeDatabase::mimeTypeForUrl to obtain MIME-type by content of file, but this method always return application/octet-stream MIME-type regardless of file content.
On iOS, the URL of file contains the file:// scheme and this way works fine, even if the file extension is missing. Probably, because QT treats it as a local file, whereas the other scheme does not.
How can I determine MIME-type of file by its URL to make it work like on iOS?


text:
Q: How does the Higgs mechanism generate mass for the $W$ and $Z$ gauge bosons? I came across this discussion point about how the Higgs mechanism generates mass for the $W$ and $Z$ gauge bosons (see attached problem below). Regarding the Higgs field factor $$\Phi^2 = \frac{1}{2}(v+h)^2$$ I think it is quite straight-forward, but I was unsure how to handle the $D_{\mu}$ expansion. Is it correct to use $$D_{\mu} = \partial_{\mu} + i \frac{g}{2}\tau W_{\mu} + i \frac{g'}{2}B_{\mu}$$ for the covariant derivative? I saw some calculated mass terms in this link (on page 9), but no explicit calculations.

Consider the kinetic term of the Higgs field $$\Phi\mathcal{L}=|D_{\mu}\Phi|^2=(D_{\mu}\Phi)^*(D^{\mu}\Phi)$$ and expand it along the minimum of the Higgs potential $$\Phi=\frac{1}{\sqrt{2}}\begin{pmatrix}0\\v+h\end{pmatrix}$$ where $v$ is the vacuum expectation value (VEV) and $h$ is the Higgs boson.

*

*Derive the coefficients of the operators representing the gauge boson masses $m_W$, $m_Z$ and $m_A$ in terms of the gauge couplings and $v$ (you can use the expressions of $A_{\mu}$ and $Z_{\mu}$ in terms of $B_{\mu}$ and $W_{\mu}^3$ without deriving them explicitly).

*Derive the coefficients of the trilinear and quadrilinear interactions between the gauge bosons $W$ and $Z$ and the $h$ boson in terms of the gauge boson masses and of $v$.

A: The covariant derivative is
$$
D_\mu\phi=\left(\partial_\mu+i\frac g2\tau^i W^i_\mu+i\frac {g'}2B_\mu\right)\phi
$$
up to normalization of the generators. Then when the $\mu^2$ term in the Higgs potential becomes positive, the Higgs field develops a constant VEV at the bottom of the potential which can be taken as
$$
\langle\phi\rangle=\frac1{\sqrt2}\begin{pmatrix}0\\v\end{pmatrix}
$$
Then fluctuations are parameterized by the Higgs boson $h$:
$$
\phi=\frac1{\sqrt2}\begin{pmatrix}0\\v+h\end{pmatrix}
$$
Finally, via a routine computation, we substitute the definition of the covariant derivative and the broken Higgs into the $|D^\mu\phi|^2$ term in the Lagrangian. If we wish to only determine the gauge boson masses, then we can safely ignore the dynamical $h$ in the Higgs interaction, since it will generate $h$-interactions rather than mass contributions at tree-level.
$$
|D^\mu\phi|^2=\left|\left(\partial_\mu+i\frac g2\tau^i W^i_\mu+i\frac {g'}2B_\mu\right)\frac1{\sqrt2}\begin{pmatrix}0\\v+h\end{pmatrix}\right|^2
$$
$$
\cong\frac {v^2}8 \left|\begin{pmatrix}g W_\mu^1-igW_\mu^2\\-gW_\mu^3+g'B_\mu\end{pmatrix}\right|^2\tag{modulo $h$-interactions}
$$
$$
=\frac{v^2g^2}8\left((W_\mu^1)^2+(W_\mu^2)^2\right)+\frac{v^2}8(gW_\mu^3-g'B_\mu)^2
$$
The field redefinitions
$$
W_\mu^\pm=\frac1{\sqrt2}(W_\mu^1\mp iW_\mu^2)
\\Z_\mu=\frac1{\sqrt{g^2+g'^2}}(gW_\mu^3-g'B_\mu)
\\A_\mu=\frac1{\sqrt{g^2+g'^2}}(gW_\mu^3+g'B_\mu)
$$
diagonalize the mass matrix, and we can immediately read the mass terms of the new fields:
$$
\frac12\left(\frac{gv}{2}\right)^2 \left(W_\mu^+\right)^2+\frac12\left(\frac{gv}{2}\right)^2 \left(W_\mu^-\right)^2+\frac12\left(\frac{v\sqrt{g^2+g'^2}}{2}\right)^2Z_\mu^2+0\cdot A_\mu^2
$$

Field
Mass

$W_\mu^+$
$gv/2$

$W_\mu^-$
$gv/2$

$Z_\mu$
$v\sqrt{g^2+g'^2}/2$

$A_\mu$
$0$

Note that a different choice of Higgs VEV would lead to exactly the same field content, albeit with a different diagonalization required to get there.


text:
Q: AWS Lambda Backlog for S3 events I am wondering how Lambda handles a backlog of S3 events when Lambda is throttled and can't keep up with events. Will S3 events be queued and for how long?
The hypothetical scenario is that a lambda function is being triggered by POST events on a S3 bucket and its concurrency limit is 10. Suppose there are suddenly a few million POST events...will those events be queued and how much time is allowed for the set of 10 lambda instances to process this steam of events?

A: I assume that the invocation (triggered by S3 Events Rule) follows the same behavior as you would trigger your Lambda through AWS SDK, AWS CLI, etc.
Which means that a lot of the few million POST events you mentioned in your hypothetical scenario will not be processed and even the retries will not work for all of the events.
As long as you didn't setup a DLQ (Dead Letter Queue) these events were discard and you dont have a chance to recover them.
I linked some articles to find more informations about the behavior of AWS Lambda.
AWS Lambda - Understanding Retry Behavior

Asynchronous invocation – Asynchronous events are queued before being
  used to invoke the Lambda function. If AWS Lambda is unable to fully
  process the event, it will automatically retry the invocation twice,
  with delays between retries.

AWS Lambda - Dead Letter Queues

AWS Lambda directs events that cannot be processed to the specified
  Amazon SNS topic or Amazon SQS queue. Functions that don't
  specify a DLQ will discard events after they have exhausted their
  retries.


text:
Q: Props not being passed from Parent to Child element I have a question regarding data passing between parent/child element.
The parent element StylePage retrieves data via SWR which retrieves the data without problem and the application is able to display it with a Text. Problem is that it isn't being passed to the child element (StyleCard). The same goes with currentAssets. What have I missed here that might cause the props not being passed to StyleCard?
// StylePage
export default function StylePage(): JSX.Element {
  const { data } = useSWR(`/api/styles/style-number/${styleNumber}`);

  const currentAssets = useMemo(() => {
    const result: IAsset[] = data?.assets?.map(x => {
      return {
            perspective_number: x.perspective.number,
            storage_url: x.file.storageUrl
          } as IAsset
    })
    return result;
  }, [data?.assets]);

  return (
    <Stack spacing={6}>
       <Stack ml="100px" minWidth="480px" maxWidth="480px">

        <StyleCard
           assets={currentAssets}               // Has value but doesn't display
           styleNumber={data?.styleNumber} />   // Has value but doesn't display
        <Text>{data?.name}</Text>               // Displays value

       </Stack>
     </Stack>
  );
}

// StyleCard
export interface IStyleCard{
   assets: IAsset[],
   styleNumber: number
}

export function StyleCard(
  props: IStyleCard
): JSX.Element {

  return (
    <Stack>
      <Text> Props Assets {JSON.stringify(props.assets)}</Text> // Props.assets is empty
      <Text> Props styleNumber {props.styleNumber}</Text>       // props.styleNumber is blank
    </Stack>
  );
}

Edit:
There's a global configuration SWRConfig (source) which is wrapped around the top layer component. That's why fetcher isn't specified in StylePage.
Also fixing a typo in the code sample.
    <SWRConfig
      value={{
        refreshInterval: 3000,
        fetcher: (url) =>
          axios
            .get(url)
            .then((res) => res.data),
      }}
    >

    ...

    </SWRConfig>


text:
Q: reading EMV card using PPSE and not PSE I'm trying to read the data off a contactless Visa Paywave card.
For the Paywave, I have to submit a SELECT using PPSE (2PAY.SYS.DDF01) instead of PSE (1PAY.SYS.DDF01).
The EMV book 1, section 11.3.4, table 43 only describes how to interpret the response for a successful SELECT command using PSE.  Does anyone know or can refer me to a source that shows how to process the data returned from a successful SELECT command using PPSE?
Here's my request APDU:
00A404000e325041592e5359532e444446303100

Here's the response:
6F2F840E325041592E5359532E4444463031A51DBF0C1A61184F07A0000000031010500A564953412044454249548701019000

I understand tag 84, tag 85, tag BF0C from the response.  According to the examples for reading PSE, I should be able to just send GET PROCESSION OPTIONS (to get the AIP and AFL) with PDOL = null after this successful response as follows: 80A80000830000.
But request 80A80000830000 returns error code 6985 - Command not allowed; conditions of use not satisfied.
I also tried reading all the files after successfully selecting the PPSE by traversing through every single SFI (0-30) and every single record (0-16) of each SFI.  Yes, I also did the 3 bit shift and bitwise-OR the SFI with 0x4.  But I got no data.
I'm stuck, any help that would point me into getting some info from my Paywave card would be appreciated!

A: Have you tried this tool from EMVLAB http://www.emvlab.org/emvtags/
Using that tool,
http://www.emvlab.org/tlvutils/?data=6F2F840E325041592E5359532E4444463031A51DBF0C1A61184F07A0000000031010500A564953412044454249548701019000

A: 2PAY.SYS.DDF01 is for contactless (e.g. NFC ) cards, while 1PAY.SYS.DDF01 is for contact cards.

*

*After successfully (SW1 SW2 = 90 00) reading a PSE, you should only search for the SFI (tag 88) which is a mandatory field in the FCI template returned.

*With the SFI as your start index, your would have to read the records starting from the start index until you get a 6A83 (RECORD_NOT_FOUND). E.g. if your SFI is 1, you would do a readRecord with record_number=1. That would probably be successful. Then you increament record_number to 2 and do readRecord again. The increament to 3 .... Repeat it until you get 6A83 as your status.

*The records read would be ADFs (at least 1). Then your would have to compare the read ADF Names with what your terminal support and also based on the ASI (Application Selection Indicator). At the end you would have a list of possible ADFs (Candidate list)
All the above steps (1-3) are documented in chapter 12.3.2 Book1 v4.3 of the EMV spec.
You would have to make a final selection (Chapter 12.4 Book1)
Read the spec book 1 chapter 12.3 - 12.4 for all the detailed steps.

A: You seem to have the flow mixed up a bit, you want to:

*

*Send 1PAY or 2PAY, it doesn't actually matter for all of the cards I've tested. This will return a list of the AIDs available on the card. Alternately you can just select an AID straight away if you know it's there but good practice would be to check first.

*Get the list of AIDs returned in response to 1PAY/2PAY, in PayWave's case this will probably be A0000000031010 if you sent 2PAY but you may get more if you send 1PAY.

*Select one of the AIDs sent back (or one you already know is on there).

*Then loop through the SFIs and records sending the Read Records command to get the data.
You don't have to send Get Processing Options before sending the Read Records command even though that's now a normal transaction flow goes.

A: I think the information you're looking for is available from this VISA website. But only if you're a registered and/or licensed partner of VISA.
EDIT: Looking at the resulting TLV struct under BF0C:
tag=0xBF0C, length=0x1A
    tag=0x61, length=0x18
        tag=0x4F, length=0x07, value=0xA0000000031010 // looks like an AID to me
        tag=0x50, length=0x0A, value="VISA DEBIT"
        tag=0x87, length=0x01, value=0x01

I would guess that you need to first select A0000000031010 before getting the processing options.

A: I was selecting application 2PAY.SYS.DDF01. when I should have been selecting AID = 0xA0000000031010.  It looks like there's no records under application 2PAY.SYS.DDF01.
But there was 1 record under application 0xA0000000031010.  After I got this application, I performed a READ RECORD, and the first record gave me the PAN and all the credit card info I wanted.
Thanks everyone for chiming in.


text:
Q: Nest + Swagger not recognizing endpoints or parameters I'm having an issue with Nest + Swagger. When I open my swagger docs I see all of the endpoints I expect but am having two issues:

*

*When I click on a method it expands all of the methods for that controller

*The post method says No parameters despite having a DTO defined for the body

Ultimately I think the issue is: Swagger + Nest is not creating unique operationId's for each method. My understanding is that methods will only fail to get unique operationId's when they are not sufficiently unique: 2 methods with identical call signatures for example.
In the past when I've had issues like this it was either because I was missing the @ApiTags decorator, or I had accidentally included duplicate endpoints.
In general it feels like I missed a step in configuring Swagger, or I didn't set it up properly with Fastify. I installed fastify-swagger but I'm not actually using it anywhere, but according the docs on Nest's site the route for the swagger JSON should be /api/json when using Fastify, which it is for me.

Things that didn't work:

*

*Annotating method with unique @ApiOperation

*Adding a addTag to the DocumentBuilder chain

*Deleting the swagger-ui-express and @nestjs/platform-express dependencies

*Removing all of the Fastify deps and switching to the Express equivalents

Update:
Adding @ApiOperation({ operationId: 'test' }) to a method does fix this, but I was under impression that @nest/swagger did this automatically. Are my methods not unique enough?
main.ts
async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );
  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector))); // allows automatic serialization
  app.enableCors();

  const config = new DocumentBuilder().setTitle('PIM API').build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

  await app.listen(process.env.APP_PORT || 3001);
}
bootstrap();

some controller
@ApiTags('chat-messages')
@Controller('chat-messages')
export class ChatMessagesController {
  constructor(
    private readonly service: ChatMessagesService,
  ) {}

  @Post()
  create(@Body() createChatMessageDto: CreateChatMessageDto) {
    return this.service.create(createChatMessageDto);
  }

  @Get(':stream_id')
  findByStreamId(@Param('stream_id') streamId: string) {
    return this.service.findByStreamId(streamId);
  }

ChatMessageDto
export class CreateChatMessageDto {
  constructor(partial: Partial<CreateChatMessageDto>) {
    Object.assign(this, partial);
  }

  @IsString()
  value: string;

  @IsRFC3339()
  timestamp: Date;

  @IsNotEmpty()
  streamId: string;
}

Swagger JSON
{
    "/chat-messages":{
       "post":{
          "operationId":"ChatMessagesController_",
          "parameters":[

          ],
          "responses":{
             "201":{
                "description":"",
                "content":{
                   "application/json":{
                      "schema":{
                         "$ref":"#/components/schemas/ChatMessage"
                      }
                   }
                }
             }
          },
          "tags":[
             "chat-messages"
          ]
       }
    },
    "/chat-messages/{stream_id}":{
       "get":{
          "operationId":"ChatMessagesController_",
          "parameters":[

          ],
          "responses":{
             "200":{
                "description":"",
                "content":{
                   "application/json":{
                      "schema":{
                         "type":"array",
                         "items":{
                            "$ref":"#/components/schemas/ChatMessage"
                         }
                      }
                   }
                }
             }
          },
          "tags":[
             "chat-messages"
          ]
       }
    }
 }

A: Did you try putting @ApiProperty in your dto ?
Like this:
export class CreateChatMessageDto {
  constructor(partial: Partial<CreateChatMessageDto>) {
    Object.assign(this, partial);
  }
  @ApiProperty()
  @IsString()
  value: string;

  @ApiProperty()
  @IsRFC3339()
  timestamp: Date;

  @ApiProperty()
  @IsNotEmpty()
  streamId: string;
}

This allows Swagger to see the properties.
This is what NestJs recommends in their documentation See here


text:
Q: Sending Notification To IOS And Android using Google Cloud Messaging in PHP I am trying to send notifications to both ios and android from my php server. I didn't get any proper documentation for sending notifications to ios via google cloud messaging. Could you please me in integrating this.

A: You can check this link for the API it provides (HTTP will fit you the best)
https://firebase.google.com/docs/cloud-messaging/server#implementing-the-http-server-protocol
And check this one for some examples on how to send to different devices, devices groups etc.
https://firebase.google.com/docs/cloud-messaging/send-message
Besides this, you gonna need to set up the the mobile apps in Firebase Console
https://firebase.google.com/support/guides/launch-checklist


text:
Q: How can I access website on Mac localhost PHP server from an iPhone on the same network? My Mac's IP is 192.168.1.122, the server is on port 8000. I've tried to connect to it from my iPhone with
http://192.168.1.122:8000/index.php
http://<name>.local:8000/index.php
both of the above without the "http://"

Note that going to
http://<name>.local

works, showing a page that says "It works!"
How can I view the site file on the iPhone?
EDIT: http://localhost:8000/index.php works on the Mac as expected

A: Figured it out based on a similar but different question:
Open the PHP server using the command
$ php -S 0.0.0.0:8000

Then, you can access it from any browser on any device connected to the same network by typing in host computer's IP:8000, NOT 0.0.0.0:8000


text:
Q: XmlDocument.LoadFromUriAsync suddenly stops working and always returns an exception? This method:
var xmlDocument = await XmlDocument.LoadFromUriAsync(new Uri("your XML url here"));

Suddenly stops working and always returns an exception:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
Additional information: Error HRESULT E_FAIL has been returned from a call to a COM component.
Is there another way to load xml document?

A: You can use Asynchronous XmlReader to read xml from uri link:
    private async void ReadXml(string uri)
    {
        using (XmlReader reader = XmlReader.Create(uri, new XmlReaderSettings() { Async = true }))
        {
            while (await reader.ReadAsync())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "NodeName")
                    {
                        string nodeContent = reader.ReadElementContentAsString();
                    }
                }
            }
        }
    }


text:
Q: Pivot geometry which is not comparable I have one query which I'm making pivot but in this table I have "geometry" data type which is not comparable. How can I fix this issue.
I'm receiving the following error:

Msg 488, Level 16, State 1, Line 14
      Pivot grouping columns must be comparable. The type of column "GEOM" is "geometry", which is not comparable.

Query what I have tried:
SELECT es.Extraction_Date,
       es.Table_Name,
       es.Extraction_Type,
       es.Feature_Count
FROM Extraction_Statistics es
PIVOT(SUM(es.Feature_Count)
      FOR es.Extraction_Type IN ([Start], [Insert], [Update], [Delete])) AS PivotTable;

A: You can use a sub-select instead of the full table to exclude the column GEOM on the PIVOT:
SELECT
    PivotTable.Extraction_Date,
    PivotTable.Table_Name,
    [Start], [Insert], [Update], [Delete]
FROM (
    SELECT Extraction_Date, Table_Name, Extraction_Type, Feature_Count
    FROM Extraction_Statistics
) es PIVOT (
    SUM(es.Feature_Count)
    FOR es.Extraction_Type IN ([Start], [Insert], [Update], [Delete])
) AS PivotTable;

demo on dbfiddle.uk (comparison between your query and this solution)
You also have to fix some issues with your current SELECT statement:

*

*On the SELECT you can only use columns from the pivot table (here PivotTable). The table defined as es isn't available after the pivot.

*Columns used for the pivot you can't use on the SELECT (here Feature_Count and Extraction_Type). Use the pivot columns instead: [Start], [Insert], [Update] and [Delete]


text:
Q: EXPECT_EQ and overloading error I'm using the google test function EXPECT_EQ to run a test case for a function. The function, find returns a list<MAN> and takes in a string of the name to find. Here's my test function:
TEST_F(test_neighborhood, find) {
    list<Man> test;
    test.push_back(Man("username", "John", "Smith", 1, 1, ""));
    EXPECT_EQ(neighborhood.find("John"), test);
}

I learned that I must include bool operator ==(Man const & left, Man const & right); from my last post: EXPECT_EQ Error which looks like this:
#include <string>
#include <queue>
#include <iostream>
#include <algorithm>

using namespace std;

class Man {
    ...
};
bool operator ==(Man const & left, Man const & right);

But I get the error
Undefined symbols for architecture x86_64:
  "operator==(Man const&, Man const&)", referenced from:
      testing::AssertionResult testing::internal::CmpHelperEQ<std::__1::list<Man, std::__1::allocator<Man> >, std::__1::list<Man, std::__1::allocator<Man> > >(char const*, char const*, std::__1::list<Man, std::__1::allocator<Man> > const&, std::__1::list<Man, std::__1::allocator<Man> > const&) in test_neighborhood.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [run] Error 1

If anyone could help explain the problem it'd be much appreciated!
EDIT - My code for Class Man:
class Man {

  private:

    string username;
    string firstname;
    string lastname;
    int gender;
    int age;
    string tagline;

  public:

    Man();
    Man(string _username, string _firstname, string _lastname,
           int _gender, int _age, string _tagline);

    string get_username();
    string get_firstname();
    string get_lastname();
    int get_gender();
    int get_age();
    string get_tagline();
    string get_info();

    bool set_username(string _username);
    bool set_firstname(string _firstname);
    bool set_lastname(string _lastname);
    bool set_gender(int _gender);
    bool set_age(int _age);
    bool set_tagline(string _tagline);
    bool set_info(string _username, string _firstname, string _lastname,
                  int _age, string _tagline, int _gender);

    // added this function in, but still getting the same error
    bool operator==(const Man& _x, const Man& _y) const {
            return (_x.username == _y.username) && (_x.firstname == _y.firstname) && (_x.lastname == _y.lastname) && (_x.gender == _y.gender) && (_x.age == _y.age) && (_x.tagline == _y.tagline);
    }

};

A: You either haven't implemented the equality operator (that's just a declaration you've copied) or you're not compiling the .cpp file that you've implemented it in.
The compiler sees the declaration for the function and is happy to continue compiling, but the linker is not finding the function in the compiled code.


text:
Q: Automatically build resource class based of XML in Java In Android applications, resources are specified in xml documents, which automatically are built into the R class, readily accessible within the source code as strongly typed.
Is there any way I could use a similar approach for a regular Java desktop application?
What I'd like to accomplish, is both the removal of strings from the code (as a separation of "layers", more or less) and to make it easy to add support for localization, by simply telling the program to choose the xml file corresponding to the desired language.
I've googled around a bit, but the things I'm looking for seem to be drowning in results about parsing or outputting xml, rather than tools utilizing xml to generate code.

A: Eclipse's message bundle implementation (used by plugins for example) integrates with the Externalize Strings feature and generates both a static class and a resource properties file for your strings:
http://www.eclipse.org/eclipse/platform-core/documents/3.1/message_bundles.html
For this integration to work Eclipse needs to see org.eclipse.osgi.util.NLS on the class path. From memory, the dependencies of the libraries it was available in were a little tricky for the project I used this approach in, so I just got the source and have it as a stand-alone class in my core module (see the comments for more on that).
It provides the type safety you're looking for and the IDE features save a lot of time. I've found no downsides to the approach so far.
Edit: this is actually what ghostbust555 mentioned in the comments, but not clear in that article that this isn't limited to Eclipse plugins and you refer to your resources via static members of a messages class.
I haven't seen any mention of others using this approach with their own applications, but to me it makes complete sense given the IDE integration and type safety.

A: I'm not sure if this is what you mean but check out internationalization- http://netbeans.org/kb/docs/java/gui-automatic-i18n.html

A: Are you looking for something that parses XML files and generates Java instances of similar "struct-like" objects, like JAXP, and JAXB?

A: I came across ResGen which, given resource bundle XML files generates Java files that can be used to access the resources in a type-safe way.
http://eigenbase.sourceforge.net/resgen/


text:
Q: Require to add content to a bug report using the (Android) app It seems some users experience trouble, specifically with the Android app. They fail making a good bug report here since they just hit the Report an Issue button in the app and then Post Your Question here in MSE.
The don't seem to understand they end up on another Q/A site where they have to form their question so everybody can understand it, not just the developer with the error logs.
We often see such questions in nothing more than the minimal required body that is auto-created by the app itself, like this one:

Can we enforce that with the footer automatically inserted, users still need to add some explanation? Maybe a smart regular expression on the question body is enough.


text:
Q: Failed to click and navigate to next page for certain website-VBA I want to navigate and choose menu bar from this website. For your information, I was able to get the selected ID of the element but don't have any clue on how to make the page is success when clicking the menu. I am using IE11 and macros to makes things work. Here is my code:
Dim IEap As InternetExplorer,htmldoc, el as variant
Set IEap= New InternetExplorer
IEap.navigate("http://fisis.fss.or.kr/fss/fsiview/indexw.html"): IEap.visible= True: DoEvents: Sleep 6000 '''navigate URL
Set htmldoc= IEap.document
For each el in htmldoc.getelementsbytagname("div")
    If ee.ID = "mainframe_ChildFrame0_form_div_submenu00_div_submenu_menu_02_menu02_04TextBoxElement" Then '''want to click "금융통계정보" to navigate next page
    ee.Focus: ee.Click '''im trying this- Failed
    ee.FireEvent ("onclick") ''''this also -Failed
next el

Is there any special method other than this? Could you please share your suggestion if you don't mind? As this is my first time facing the complicated website like this. Thanks for your help :)
P\S: Avoid to using GUI or API method. Thx


text:
Q: Benefits of a suspended state in threads? I'm tyring to answer a question, a professor purposed us.

Threads usually have states Running, Ready, and Blocked. Suppose we wanted to add a Suspended state to maximize processor utilization through admitting a larger number of threads requiring more memory than available in the process' address space.Does the above make sense? If it does, explain why and explain what benet(s) we obtain. If it doesnot, explain why not.

The suspended state seems pretty stupid to me because synchronization would just be a terrible experience. In any case where you might want to suspend, going into a blocked state is probably a 10x better idea because of this. And on top of that isn't processor already utilized as best as it can be because when one thread gets blocked, another gets scheduled. By putting in a suspend state that you explicitly go into, you are pretty much manually controlling the scheduling. I'm really confused as to what benefits it would provide. Any ideas?

A: I completely agree with you, synchronization is not possible until you are not limited to threads start point synchronization. where you just create a thread in suspended state, and allow it to continue only when parent process raises a flag. But apart of this, synchronization is not possible with suspended thread model.
I also think blocking is a better than hanging up thread in suspended queue. Processor is already fully utilized, and It is not really beneficial anyway to put thread in suspended state until you are using it for some special purpose. Debuggers use suspended thread state, so that they can alter/break/trace thread's state. This shows exactly how we can use suspended state.
You are right, You are somewhat manually controlling thread's scheduling process and that makes It a terrible idea.


text:
Q: How to fix the 'ValueError: input tensor must have rank 3'? Currently I'm trying to run a Autoencoder in combination with CNN for IRIS data, but after a search on Google and Stackoverflow I wasn't able to find the solution for my problem.
Totally I have many problems with  data dimensions in the first layer of all networks. Please give me  good resources to understand it.
x =tf.expand_dims(X_scaled, axis=-1)
y_train=np_utils.to_categorical(y,num_classes=3)
print("Shape of y_train",y_train.shape)#(150,3)
print(x.shape)#(150,4,1)
inputdata = keras.Input(x.shape,name="data")
encoding_layer1  = layers.Conv1D(16, 3, activation='relu', padding='same')(inputdata)
encoding_layer1  = layers.MaxPooling1D(2, padding='same')(encoding_layer1 )
encoding_layer2 = layers.Conv1D(8, 3, activation='relu', padding='same')(encoding_layer1 )
encoding_layer2 = layers.MaxPooling1D(2, padding='same')(encoding_layer2)
bottleneck= layers.Conv1D(4, 3, activation='relu', padding='same')(encoding_layer2)
decoding_layer2 =layers.BatchNormalization()(decoding_layer2)
decoding_layer3=layers.Conv1DTranspose(8,3, strides=2, activation='relu', padding='same')
(decoding_layer2)
decoding_layer4 =layers.BatchNormalization()(decoding_layer3)
# d =layers.Conv1DTranspose(16,3, activation='relu', padding='same')(d)
decoded =layers.Conv1D(16, 3, activation='sigmoid', padding='same')(decoding_layer4)

model = keras.Model(inputs=inputdata, outputs=decoded )
autoencoder = keras.Model(inputdata, decoded)
autoencoder.compile(optimizer='adam', loss="mse")
autoencoder.summary()


text:
Q: AWS ECS Task Definition with terraform and efs - Unknown volume I'm trying to persist container data and for that I want to mount a volume. Here is my task definition which throws the unknown volume error despite declaring it.

aws_ecs_task_definition.wordpress: Creating... Error: ClientException: Unknown volume 'wordpress-volume'.

    locals {
      username = jsondecode(data.aws_secretsmanager_secret_version.wordpress.secret_string)["username"]
      password = jsondecode(data.aws_secretsmanager_secret_version.wordpress.secret_string)["password"]
    }

    resource "aws_ecs_task_definition" "wordpress" {
      family                = "wordpress"
      container_definitions = jsonencode([{
        name = "wordpress"
        image = "wordpress"
        essential = true
        cpu = 256
        memory = 512
        entryPoint = [ "sh", "-c"]
        command = ["ls -la /var/www/html"]
        volumes = [{
          name = "wordpress-volume"
          efsVolumeConfiguration = {
            fileSystemId = aws_efs_file_system.wordpress.id
          }
        }]
        mountPoints = [{
          sourceVolume = "wordpress-volume"
          containerPath = "/var/www/html"
          readOnly = false
        }]
        environment = [{
          name = "WORDPRESS_DB_HOST"
          value = "127.0.0.1"},
        {
          name = "WORDPRESS_DB_USER"
          value = local.username
        },
        {
          name = "WORDPRESS_DB_PASSWORD"
          value = local.password
        },
        {
          name = "WORDPRESS_DB_NAME"
          value = "wordpressdb"
        }]
        portMappings = [{
          protocol = "tcp"
          containerPort = 80
          hostPort = 80
        }]
      }])
      network_mode = "awsvpc"
      requires_compatibilities = ["FARGATE"]
      execution_role_arn =  aws_iam_role.ecs_task_execution_role.arn
      task_role_arn = aws_iam_role.ecs_task_role.arn
      cpu = 1024
      memory = 3072
    }

A: Your volumes definition isn't supposed to be inside container_definitions but is part of aws_ecs_task_definition resource arguments.
So, you should move this part outside:
 volumes = [{
      name = "wordpress-volume"
      efsVolumeConfiguration = {
         fileSystemId = aws_efs_file_system.wordpress.id
      }
 }]

to
resource "aws_ecs_task_definition" "wordpress" {
...
  volume {
      name  = "wordpress-volume"
      efs_volume_configuration {
        file_system_id = aws_efs_file_system.wordpress.id
      }
  }
...
}

see the docs:

*

*https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition#volume-block-arguments

*https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_TaskDefinition.html
And container definition docs:

*

*https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDefinition.html


text:
Q: php array of dictionaries I have multiple functions inside my php that look like this
function linkExtractor($html){
    $doc = new DOMDocument();
    $last = libxml_use_internal_errors(TRUE);
    $doc->loadHTML($html);
    libxml_use_internal_errors($last);
    $xp = new DOMXPath($doc);

    $result = array();
    foreach ($xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' infaa ')]") as $node)
        $result[] = trim($node->textContent);
    return $result;
}

And I am using this to turn them into json:
echo json_encode(array("info" => linkExtractor($html),
"dates" => linkExtractor2($html),
"names" => linkExtractor3($html),
"images" => linkExtractor4($html),
"genres" => linkExtractor5($html)
));

But this is returning the json like this:
{
"name":["melter",...],
"date":["05/24/14",...],
"image":["pictu.jpg",...],
"genre":["art",...],
"info":["Lorem ipsum",...]
}

I am looking to batch them so the first of each result is put into a curly brackets like this:
[
{
"name": "melter",
"date": "05/24/14",
"image": "pictu.jpg",
"genre": "art",
"info": "Lorem ipsum"
},
...
]

How can I do this?

HTML snippet:

art

05/24/14

melter

  Lorem ipsum

A: I guess the arrays returned by the linkextractor functions are the same length.
$arr = array();

$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);

for ($i=0; $i<count($info); $i++) {
    $arr[] = array("info" => $info[$i], "date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i]);
}

echo json_encode($arr);

A: Assuming each array has the same number of elements and assuming you extract them in the same order, you can loop like that:
$count = count($names);
$result = array();
for ($i=0; $i<$countà; ++$i) {
    $item = new stdClass;
    $item->name = $names[$i];
    $item->date = $dates[$i];
    // ...
    $result[] = $item;
}
echo json_encode($result);

However, what you are doing is highly inefficient and you should rethink your parsing strategy to extract all the information in a single pass.


text:
Q: jquery tablesorter plugin with mixed date format not working in IE/Safari, does work in FF,O,C Not sure what the exact issue is..basically, am using the tablesorter jquery plugin, trying to sort with 2 different types of date format listings in the column. I need the end result to be a chronological sort (obviously), just like it's doing in FF now. Any insight is greatly appreciated.
http://developer.erg.com/~bzaks/test2.html

A: One of the nice things about the tablesorter plugin is that is will evaluate the column data and pick the best parser. Mixed date formats will still get parsed as dates.
Check out this jsFiddle and see how the Date column works.
Debugging the sort shows that the dates get parsed by the usLongDate parser, and that parser parses and converts the date string to a time integer to sort it correctly.