text:
Q: Alterations with a integer in c++ This is easy for you. I am busy with a test using c++. I have 2 values:
0 and 1

I can find random number between. Now i want to alternate between them. If i get "1" in step one then in step two I want to get "0" and in step three "1" again where it alternate
step1 = 1
step2 = 0
step3 = 1
step4 = 0

I tried increment and decrements
  int value;
  if(value == 0)
  {
      value = value + 1;
  }
  else if(value == 1)
  {
      value = value -1;
  }

This code does not work. If it sees a 0 it will become 1 but the next step the value will be 1 again.

A: If you really only ever need 0 and 1:
unsigned int value = 0;

while (1) {
   value = (value + 1) & 1;
   // do whatever is needed with value;
}

This works because in binary 0 + 1 = 1, and 1 + 1 = 10. The '& 1' portion tells us to always take the last bit.

A: Wild guess: You are using floating point types (doubleor float) to represent those numbers. You can't compare those types using the == operator, you need to take their precision into account.
Take a look at this question on how to compare floating point types.

A: put in a bool switch with your if statements, eg
bool firstHit = false;
if(value == 0 && firstHit == false)
{
  value = value + 1;
  firstHit = true;
}
else if(value == 1 &&firstHit == true)
{
  value = value -1;
  firstHit = false;
}

A: Your code is fine dude. I tested it, and its working.
#include <iostream>

using namespace std;

int main ()
{

    int value=1; //Say first step

  for (int i=0 ; i <= 10; i++ )
{
    if(value==0)
    {
        value=value+1;
    }
    else if (value==1)
    {
        value=value-1;
    }
         cout << "Step "<<i<<": "<<value<<"\n";
}

  return 0;
}

A: The code you're showing doesn't initialize value to anything.
Other than that,
if(value == 0)
  {
      value = value + 1;
  }
  else if(value == 1)
  {
      value = value -1;
  }

This looks like it should work fine if you just want to alternate between 1 & 0, as it will switch it every time you iterate through it.

A: Simplest  :
value = 1 - value;

There's a <g> before the colon, but the system software seems to not want to display it.


text:
Q: Jquery-Mobile taphold specific area on image I have an image and I want to make taphold events for specific areas of the image.  The image scales to 100% width of the page.
Is there any possible way in Jquery-Mobile to to get this done?  I've been looking everywhere and can't seem to find a way of getting around this.
Thank you in advance

A: Got to use image mapping to solve this problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with animate defining number of pixels This code produces no result. I need the variable, as the number is different each time the user clicks. Is it not possible to define the number of pixels this way? Thanks for any help.
$(document).ready(function () {
    $("#logo").click(function () {
        var num = (whatever);
        $("#slideshow").animate({left: "-=num + 'px'"}, 2000);
    });
});

A: You're probably getting an error for passing a string that is not a valid unit value, you need to concatenate the value of your variable like this
$("#slideshow").animate({left: '-=' + num}, 2000);

Also you don't need to specify pixels, any number without unit is treated like pixels


text:
Q: merged ntfs partitions, missing "Program Files" directories Nowhere can I seem to be able to find how to resolve this situation in-place.
What happened:
Before,
C: ~= 90GB, freshly installed Win 8.1 Enterprise, 64bit
D: ~= 880GB, also ntfs. Mainly for data files.  Still contained folders from nonworking Win8.0, from when this was formerly the C: drive.
Manual chkdsk for C and D went fine in the Advanced Tools, Command Prompt bootup option. No errors.
Next, used Minitool Partition Magic to merge the adjacent D: into C:, as the subdir C:\D
Made sure order was correct, i.e. the C:\Windows is the same before and after, and other files originally directly under C:\ are still there, NOT under C:\D now.
After:
Win8.1 loads, but most icons from installed programs (to C:) are blank.
"C:\Program Files" and  "C:\Program Files (x86)" and maybe other folders are totally missing from explorer.exe's view AND cmd.exe run as Administrator.
However, the free vs. used disk space add up to about what should be from the C: and D: before the merge.
This leads me to believe the allocated files & folders ARE still written on the disk.
My hypothesis is that somehow, the ntfs permissions/ownerships/ACLs got screwed, possibly imposing onto those disappeared folders mappings from the old D: MFT that no longer exists.
Maybe the current SYSTEM/Administrator/TrustedInstaller/User/...? accounts suddenly can't see whatever ID somehow got linked to the missing folders?  If so, how to restore?  How to get a root-like view of the C: drive with no regard for ownerships or ACLs?
All research seems to point to using tools to undeleting files or scraping unallocated space; nothing seems to come close to fixing the messed up security-descriptors scenario.
Manually running chkdsk /f c: after the fact ended with no errors detected.  Also did sfc /scannow
NOTES

*

*the old C: partition was right after the EFI partition, earlier in the disk than the old D.

*Had recovery/forensic tools installed like R-Studio, which are all inaccessible now, as they were under the old "C:\Program Files" or "C:\Program Files (x86)"

*a User-level program like WinDirStat run against the C: in the post-merge Windows 8.1 doesn't reveal enough space taken by files to be consistent with the "free space" listed by running dir from a command shell.  All the more compelling reason for my suspicions that from an ntfs point of view, the fs structure is fine and the folders are not really gone. Except even the "SYSTEM" account in Windows 8.1 can't see them.  However, I could be wrong. Any other ideas?

A: For others hitting these possibly rare circumstances:
I was right in my suspicion that the missing folders were still on disk, albeit invisibly.
"Program Files\", "Program Files (x86)\", and "ProgramData\"  were found entirely intact in the hidden c:\found.000
(I suspect that resulted from an automatic chkdsk preceding a boot back into Windows, after the partitioning software's batch job had run.)
I should have known to check...wish I had known before I let Windows self-heal imperfectly with sfc, which created barebones copies of all three above, and left me with a lot of careful file merging and manual link resolution later.
Many other files (from the older D: partition, now merged into C:) listed owners similar to
Account Unknown(S-1-5-21-580982140-4090956935-1935414389-1001)
which was no surprise.
Commands like
icacls * /grant:r everyone:f /t

and
takeown /F .

helped re-gaining access to those.


text:
Q: Cannot read property 'checked' of undefined React I'm making a litte app(a list of topics) where i use checkbox to delete some topic but when i start the app the console said "Cannot read property 'checked' of undefined" i read on some post that it could be cause i rewrite the check box bur i don't see where.
can you help ?

import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Topics } from '../api/topic.js';
import Topic from './Topic.jsx';

class AppTopic extends Component {

  toggleChecked() {
      // Set the checked property to the opposite of its current value
      Topics.update(this.props.topic._id, {
        $set: { checked: !this.props.topic.checked },
      });
    }

    deleteThisTopic() {
      Topics.remove(this.props.topic._id);
    }

  renderTopics() {
    return this.props.topics.map((topic) => (
      <Topic key={topic._id} topic={topic} />
    ));
  }

  render() {

    // Give tasks a different className when they are checked off,
    // so that we can style them nicely in CSS
    const topicClassName = this.props.topic.checked ? 'checked' : '';

      return (

        <button className="delete" onClick={this.deleteThisTopic.bind(this)}>
          ×
        </button>

        <input
          type="checkbox"
          readOnly
          checked={this.props.topic.checked}
          onClick={this.toggleChecked.bind(this)}
        />
        {this.renderTopics()}

      );

    }
  }

  AppTopic.propTypes = {
  topics: PropTypes.array.isRequired
};

export default createContainer(() => {
  return {
    topics: Topics.find({}).fetch(),
  };
}, AppTopic);

A: here is ../api/topic.js

import { Mongo } from 'meteor/mongo';

export const Topics = new Mongo.Collection('topics');

and ./Topic.jsx

import React, { Component, PropTypes } from 'react';
import { Topics } from '../api/topic.js';

export default class Topic extends Component {
  render() {
    return (

{this.props.topic.text}  ARN:  {this.props.topic.arn} <button>S'inscrire</button>

  );
  }
}

Topic.propTypes = {

  topic: PropTypes.object.isRequired,
};


text:
Q: Using multiple clauses - Prolog I have a prolog program that contains details on course modules, students, and the modules they are attending. The program is as follows:
module(42, mod_details('Vocal Skills', 'Dawn Upshaw')).
module(53, mod_details('Physics', 'Dave Jones')).
module(64, mod_details('Maths', 'John Richards')).
module(75, mod_details('History', 'El Capitan')).

student('Bruce Wayne', student_det('100', '2')).
student('Clarke Kent', student_det('200', '3')).
student('Scott Summers', student_det('300', '1')).
student('Richard Kimble', student_det('400', '2')).

attends(100, 42).
attends(300, 42).
attends(400, 42).
attends(200, 53).
attends(300, 53).
attends(300, 64).
attends(100, 75).
attends(200, 75).
attends(300, 75).
attends(400, 75).

print_studentnos_for_modno(ModNo):-
        attends(SNo, ModNo),
    write(SNo).

print_studentnos_for_modtitle(ModTitle):-
    module(ModNo, mod_details(ModTitle, Lect)),
    attends(SNo, ModNo),
    write(SNo).

is_a_student(StudentName):-
    student(StudentName, student_det(SNo, Year)).

print_students_lectured_by(Lect):-
    module(ModNo, mod_details(ModTitle, Lect)),
    attends(SNo, ModNo),
    student(StudentName, student_det(SNo, Year)),
    write(StudentName), write(' '),
    write(SNo).

The last clause, print_students_lectured_by(Lect), is supposed to print out the names of the students followed by their student number. However, it only gives a false answer.
I am extremely new at this so would appreciate any advice on how to amend my clause.
Many Thanks
Andy

A: student('Bruce Wayne', student_det('100', '2'))

should be
student('Bruce Wayne', student_det(100, 2))

and similarly for the rest of the students.
NOTE: Haven't tried this out myself


text:
Q: Android activity class gives NullPointerException My problem is that one specific activity in my app can't be launched for some reason, and it throws:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
All other launching code that looks like this work fine, the problem is ONLY when I'm launching Player1. The class surely exists, and I can't understand what is the problem.
I'm launching an activity called Player1 from an activity called ChooseLevel. When some button is pressed, the call is:
Intent intent = new Intent(ChooseLevel.this, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();

The logs show that the error is in: Player1.onCreate(Player1.java:50)
The code in line Player1:50 is:
   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player1);

    changeIndex = 0;
    cards = new ArrayList<Card>(8);
    score = (TextView) findViewById(R.id.score_text);
    message = (TextView) findViewById(R.id.msg_text);
    timer = (TextView) findViewById(R.id.timer);
    timer.setText(String.valueOf(definitions.TIMER_START)); # LINE 50

    Bundle b = getIntent().getExtras();

    ...
}

When this launching code runs, I get this in my logs:
33:04.338 18302-18302/com... D/AndroidRuntime: Shutting down VM
01-18 10:33:04.338 18302-18302/com... E/AndroidRuntime: FATAL EXCEPTION: main
           Process: com..., PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../com....Player1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        at com....Player1.onCreate(Player1.java:50)

EDIT:
I found my answer, it had to do with some object that I had in my Player1.onCreate() method. In a wierd way, android-studio raised the exception regarding getClass(). If someone knows why this happend, please share :)

A: use context,getApplicationContext()orgetActivity()`
Intent intent = new Intent(context, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();


text:
Q: Computing singular value decomposition via Matlab script Let $A = \begin{pmatrix} 10&20\\ -3 & 4  \end{pmatrix}$.
I want to compute the svd decomposition $A=USV'$ via matlab, but I do not want to use the function svd.
First of all, I have to compute the vector $U$ and $V$, so:
A=[10 20;-3 4];
 [U,D]=eig(A*A');
 [V,D]=eig(A'*A);
The problem is that my matrix $D$ has the property  $D(1,1)<D(2,2)$. In order to find my matrix $S$ I have to type:
S=sqrt(diag([D(2,2) D(1,1)]))
But, since I reverted the order of the elements from the diagonal matrix, I also have to swap the columns of $U$ and $V$ in order to maintain the correspondence beetween the eigevectors and the eigenvalues previously computed:
V(:,[1 2])=V(:,[2 1]);
U(:,[1 2])=U(:,[2 1]);
And the result is:
U*S*V'
But the result (shown below) its not equal to $A$!
$\begin{pmatrix} -10&-20\\ +3 & -4  \end{pmatrix}$.
EDIT:
Computing the SVD decomposition through the matlab function svd
[U1,S1,V1]=svd(A)
we can note some differences:
From my computation
$U = \begin{pmatrix} -0.9946 & 0.1036
\\ -0.1036  & -0.9946  \end{pmatrix}$ and from matlab: $U1 = \begin{pmatrix} -0.9946 & -0.1036
\\ -0.1036  & 0.9946  \end{pmatrix}$ we see that the difference its in the second eigenvector of $AA'$ since they are multiples of $-1$ to each other.
A similar difference happens beetween $V$ and $V1$, in this case, however, the first eigenvector of $A'A$ are multiple of $-1$ to each other.
I thought that $U$ and $V$ should be just an orthogonal matrix whose columns are constitued by, respectively, eigenvectors of $AA'$ and $A'A$. And the matrices $U$ and $V$ that I computed satisfies these conditions, so why am I having this wrong result?
Sorry for the long post..


text:
Q: Bootstrap Function Declaration I was taking a look through the bootstrap JS source and I came across something that I haven't seen before:
+function ($) { "use strict";
//...
}(window.jQuery);

What's the deal with the + in front of the function declaration? Is it to mitigate some potential minification problems or something?
I believe that placing a + before an expression type converts the result of the expression to a number, but I don't see what the relevance of that would be here.
Thanks for anybody who can shed some light on this for me.

A: That is so that the function declaration is a function expression, so that it can be executed immediately.
Usually that is done by putting parentheses around it:
(function ($) { "use strict";
//...
}(window.jQuery));

or:
(function ($) { "use strict";
//...
})(window.jQuery);


text:
Q: Yet another issue with BGL Deserialization I'm trying to both serialize and deserialize the data in a graph format. The definition of my graph is the following one.
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/directed_graph.hpp>
#include <boost/graph/adj_list_serialize.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/binary_object.hpp>

class VFull {
public:
    VFull();
    unsigned int id, hash, year;
    std::string ip, organization;
    VFull(unsigned int id, unsigned int hash, unsigned int year, std::string ip, std::string organization);
    template<class Archive> void serialize(Archive & ar, const unsigned int version);
};

class EFull {
public:
    EFull();
    template<class Archive> void serialize(Archive & ar, const unsigned int version);
};

class GFull {
public:
    template<class Archive> void serialize(Archive & ar, const unsigned int version);
};

//Defining the graph data structure. Using the vecS specification
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,VFull,EFull,GFull> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor result_vertex_descriptor;
typedef boost::graph_traits<graph_t>::edge_descriptor result_edge_descriptor;

It seems to me that I have no problems in the serialization process, while I have some issues in the deserialization part. In fact, I have no linking errors until this piece of code is added to my source:
#include <iomanip>
#include <iostream>
#include <fstream>
{
    std::ifstream file(path,std::ios_base::binary);
    boost::archive::binary_iarchive store{file};
    store >> graph; // Deserialization part that triggers the error
}

I tried to read some questions here and to read the Boost manual, but they didn't solve my problem. In particular, I have this error:
Undefined symbols for architecture x86_64:
  "void EFull::serialize<boost::archive::binary_iarchive>(boost::archive::binary_iarchive&, unsigned int)", referenced from:
      void boost::serialization::access::serialize<boost::archive::binary_iarchive, EFull>(boost::archive::binary_iarchive&, EFull&, unsigned int) in boostOthers.cpp.o
  "void GFull::serialize<boost::archive::binary_iarchive>(boost::archive::binary_iarchive&, unsigned int)", referenced from:
      void boost::serialization::access::serialize<boost::archive::binary_iarchive, GFull>(boost::archive::binary_iarchive&, GFull&, unsigned int) in boostOthers.cpp.o
  "void VFull::serialize<boost::archive::binary_iarchive>(boost::archive::binary_iarchive&, unsigned int)", referenced from:
      void boost::serialization::access::serialize<boost::archive::binary_iarchive, VFull>(boost::archive::binary_iarchive&, VFull&, unsigned int) in boostOthers.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

By the way, I'm serializing and deserializing strings and unsigned ints, "native data types" that seems to be supported by boost:
//VERTICES
VFull::VFull() { }
VFull::VFull(unsigned int i, unsigned int h, unsigned int y, std::string p, std::string o) :
    id{i}, hash{h}, year{y}, ip{p}, organization{o} {

}
template<class Archive> void VFull::serialize(Archive &ar, const unsigned int version) {
    ar & 'i'; ar &  id;
    ar &  'h'; ar & hash;
    ar & '1'; ar & ip;
    ar & '2'; ar & organization;
    ar & '3'; ar & year;
    ar & '/';
}
///////

//EDGES
EFull::EFull() { }
template<class Archive> void EFull::serialize(Archive &ar, const unsigned int version) {
    char waste = 'e';
    ar & waste; }
///////

//GRAPH SIGNATURE
template<class Archive> void GFull::serialize(Archive &ar, const unsigned int version) {
    std::string waste = "GBLS";
    ar & waste;
}
///////

EDIT Yes, I am linking my source code to both BGL and Boost's serialization. This is acheived through this part of CMake script:
find_package( Boost REQUIRED COMPONENTS graph serialization )
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED OFF)
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIRS} ..some other stuff..)
TARGET_LINK_LIBRARIES(mycode ${Boost_LIBRARIES})

A: Since the serialization method is a template, it should be put in the .h file and not in the .cpp part.


text:
Q: bash, detecting mp4 files if [ -f *.mp4 ]; then
        for file in *.mp4; do
                ffmpeg2theora -v 8 --nometadata  "$file"
                rm -f "$file"
        done
fi

if [ -f *.avi ]; then
        for file in *.avi; do
                ffmpeg2theora -v 8 --nometadata  "$file"
                rm -f "$file"
        done
fi

I can't figure out why if [ -f *.mp4 ]; then is not detecting mp4 files, i use this method it to find .avi, .epub, .chm and some other extensions and it works perfectly. I wonder me if it is because of the 4. i also tried by doing if [ -f *."mp4" ]; then but it didn't work.
I find weird that  for file in *.mp4; do detects .mp4 files and if [ -f *.mp4 ] not!

A: Use the bash option nullglob to allow globs to expand to zero elements. This way, the loop will simply not run if there are no matching files:
shopt -s nullglob
for file in *.mp4; do
    ffmpeg2theora -v 8 --nometadata  "$file" && rm -f "$file" || \
        echo Problem transcoding "$file"
done

As for [ -f *.mp4 ], it only works correctly if there is exactly one matching file, because then it expands to [ -f myfile.mp4 ].
If there are no matching files, it may still work (without nullglob) because it ends up checking for a file with an asterisk in the name, which hopefully doesn't exist.
If there are multiple files, it fails, because [ -f file1.mp4 file2.mp4 file3.mp4 ] is not valid test syntax.

A: if [ -f *.mp4 ]; then

There is no expansion inside the test. The test is looking for a file named *.mp4 which doesn't exist. What you should do it:
for i in *.mp4; do
    <do something>
done

Here expansion will provide all files with .mp4 extensions in the present working directory. You can also you find /path/to/dir -type f -name "*.mp4" to get your filenames as well. (note: this expects .mp4 files to be present in the directory. If not, i=*.mp4. You are safer doing:
find /path -type f -name "*.mp4" | while read i; do
    <do whatever>
done


text:
Q: If state is reachable in time T_1, then it is reachable in time $T > T_1$ Consider a Linear Time System with the admissble control set
$$U = \left\{ u: R \rightarrow R^m \;|\;\text{u is integrable in any finite interval} \right\} $$.
Show that, if starting on $x_0=0$ we can reach a state $x_1$ in time $T_1$, then we can reach this state in any time $T \geq T_1$. That is, if there is a trajetory linking $0$ to $x_1$ in time $T_1$, there is a trajetory linking those states in any time greater than $T_1$
My attempt: We have that
$$x_1 = x(T_1) = \int_0^{T_1} e^{sA} B u(s) ds$$
where
$$x'(t)=Ax(t)+Bu(t), \; x_0 = 0 \text{ and } u \in U$$
I need to show that for any $T\geq T_1, \; \exists \bar{u} \in U$ such that
$$x_1 = x(T) = \int_0^Te^{sA}B\bar{u}(s)ds$$
I had the following ideas:
1. $$\bar{u}(s)=\left\{\begin{matrix} u(s), s \in [0, T_1] \\ 0, s\in (T_1, T] \end{matrix}\right.$$
2. The gramian of controlabillity is defined as
$$Q_T = \int_0^Te^{sA}BB^te^{sA^t} ds $$
and the state $x_1$ is reachable iff $\exists \eta$ such that $x_1 = Q_T \eta$, ie, $x_1 \in \text{Im }Q_T$
In this case, we know that
$$x_1 = Q_{T_1}\eta = \int_0^{T_1} e^{sA}BB^te^{sA^t}\eta\; ds$$
So I thought that
$$\bar{u}(s)=\left\{\begin{matrix} B^te^{sA^t}\eta, s \in [0, T] \\ -B^te^{sA^t}\eta, s\in (T_1, T] \end{matrix}\right.$$
I would like to know if both approaches are correct and, if not, what is wrong with them.
Thanks in advance!


text:
Q: Is there a Quick Search Tool in IntelliJ iDEA? In STS (Spring Tool Suite) version, We have this quick search plugin (Ctrl+Shift+L) that quickly spawns a dialog box that progressively displays all found occurences of the text provided in the project. Is there such thing in IntelliJ IDEA?
A good description of the plugin can be found here:
http://spring.io/blog/2013/07/11/eclipse-quick-search

A: You can use shortcut key: Shift+Shift. You have to press double shift button

A: You can use the following shortcuts for helping you to navigate throughout your code:
 Ctrl + N  - Search for classes
Ctrl + Shift + N - Search for file name
Ctrl + Shift + Alt + N - Search for symbol name
Using a mixture of those you'll be able to find places in your program.
Ctrl + Shift + F
Allows you to search within the path
Shift + Shift brings up the "Search Anywhere" popup

A: I want this feature too, and it's not quite there, but could be.
The best you can do is to train your fingers as follows:

*

*Ctrl+H

*type your search text

*If the preview tab isn't showing, do Ctrl+Page Down
The problem is that you can't open just the file that you want, unless, you type enough that there is only one match which will open if you select:

*

*Options: Result options: Skip results tab when only one occurrence is found

This will open the file instead of showing the results
It's also handy to set up File mask(s) to only the files that are relevant to you (for example for me I want results in .ts (for Typescript including TSX, but not .js)

A: "Find in Path" is probably what you're looking for. It is probably bound to ctrl+shift+f or cmd+shift+f, depending on your key bindings and whether you are on Mac / Windows / or Linux. It can also be found under the "Edit", "Find" menu.

A: The thing that makes quick search in eclipse so awesome is the snappy as-you-type result feedback.
You can get this in intellij w/ ctrl+shift+f or cmd+shift+f as others mentioned, but to truly emulate the eclipse quick search plugin you will want to switch to the Preview tab (in version 15, anyway).


text:
Q: Integer expression expected giving for below script in the if statement......This `expr $num%$i` gives % when used with echo...Why so? #!/bin/bash
echo "Enter a number"
read num
i=2
res=true
while [ $i -le $num ]
do
       if [ `expr $num%$i` -eq 0 ]
       then
               res=false
       fi
       i=`expr $i + 1`
done

echo "$res"

This expr $num%$i in if statement gives % when used with echo....Why so?
Enter a number
6
./4.sh: line 8: [: 6%2: integer expression expected
./4.sh: line 8: [: 6%3: integer expression expected
./4.sh: line 8: [: 6%4: integer expression expected
./4.sh: line 8: [: 6%5: integer expression expected
./4.sh: line 8: [: 6%6: integer expression expected
true

Why the expr is not evaluating as per modulo operator

A: Simple solution, separate the args and the operator with spaces, eg:
num=6
i=2

# wrong

$ if [ `expr $num%$i` -eq 0 ]; then echo 'equal'; fi
-bash: [: 6%2: integer expression expected

# right

$ if [ `expr $num % $i` -eq 0 ]; then echo 'equal'; fi
equal

# or

$ if [ $(( num % i )) -eq 0 ]; then echo 'equal'; fi
equal

# or

$ if (( num % i == 0 )); then echo 'equal'; fi
equal


text:
Q: Filter datatable with Linq by a decimal list in c# I have got a datatable and I want to filter by a value. This is working:
 var result = datatable.AsEnumerable()
    .Where(r => r.Field<decimal?>("decimal_col") == 1);

Now I want to filter by a list of decimals. I have tried to put contains but it is not working. This is the list:
var list = new List<decimal>() { 8, 3, 2, 1 };

And this is what I want, but it is not working:
var result = datatable.AsEnumerable()
        .Where(r => r.Field<decimal?>("decimal_col").Contains(list));

Any help?

A: You need to use list.Contains(). The syntax is List<T>.Contains(item) (Note the difference, In the query in OP, it was in correctly given as item.Contains(list))
var result = datatable.AsEnumerable()
        .Where(r => list.Contains(r.Field<decimal?>("decimal_col")));

You can read more on the syntax of List.Contains here

A: You're checking if the value "contains" the list.  It's the other way around.  The list would "contain" the value:
list.Contains(r.Field<decimal?>("decimal_col"))


text:
Q: Can't seem to replicate this timetable I'm trying to replicate this table in latex.

But, I can't get it to be correctly typeset.
This is the result:

All the months get jumbled and I can't seem to make them all the same size.
And this is the code I have so far:
\documentclass[11pt,a4paper]{article}
\usepackage[utf8x]{inputenc}
\usepackage{ucs}
\usepackage[left=3.00cm, right=3.00cm, top=2.50cm, bottom=2.50cm]{geometry}
\usepackage{booktabs,multirow,array,ragged2e,float,graphicx}
\begin{document}
\begin{table}[H]
    \centering
    \label{tab:501}%
    \resizebox{\textwidth}{!}{%
        \def\arraystretch{1.3}
        \begin{tabular}{@{}p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|p{1,5cm}|@{}}
            \cmidrule(l){2-13}
            & \textbf{Jan}                                    & \textbf{Fev}                                   & \textbf{Mar}                                  & \textbf{Abr}                                 & \textbf{Mai}                       & \textbf{Jun}                      & \textbf{Jul}                      & \textbf{Ago}                           & \textbf{Set}                          & \textbf{Out}     & \textbf{Nov}     & \textbf{Dez}    \\ \midrule
            \multicolumn{1}{|c|}{\textbf{2013}} & \multicolumn{12}{c|}{\begin{tabular}[c]{@{}c@{}}Medicina Interna\\ HSM\end{tabular}}                                                                                \\ \midrule
            \multicolumn{1}{|c|}{\textbf{2014}} & \multicolumn{12}{c|}{\begin{tabular}[c]{@{}c@{}}Endocrinologia, Diabetes, Metabolismo e Nutrição\\ HSM\end{tabular}}                                                                                \\ \midrule
            \multicolumn{1}{|c|}{\textbf{2015}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Laboratório de Endocrinologia\\ HSM\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Endocrinologia Pediátrica\\ HSM\end{tabular}} & \multicolumn{8}{c|}{\begin{tabular}[c]{@{}c@{}}Endocrinologia, Diabetes, Metabolismo e Nutrição\\ HSM\end{tabular}}                                                                                \\ \midrule
            \multicolumn{1}{|c|}{\textbf{2016}} & \multicolumn{4}{c|}{\begin{tabular}[c]{@{}c@{}}Endocrinologia, Diabetes, Metabolismo e Nutrição\\ HSM\end{tabular}}                                                                             & \multicolumn{3}{c|}{\begin{tabular}[c]{@{}c@{}}Medicina Nuclear Oncologia Tiroideia\\ IPOLFG\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}Imagiologia\\ HSM\end{tabular}} & \multicolumn{3}{c|}{Endocrinologia da Reprodução HSM} \\ \midrule
            \multicolumn{1}{|c|}{\textbf{2017}} & \multicolumn{5}{c|}{Endocrinologia, Diabetes, Metabolismo e Nutrição HSM}                                                                                & \multicolumn{2}{c|}{Endocrinologia Diabetes e Metabolismo EMC}        & \multicolumn{5}{c|}{Endocrinologia, Diabetes, Metabolismo e NutriçãoHSM}                                                               \\ \bottomrule
    \end{tabular}}
\end{table}
\end{document}

I have tried using other packages but the end result is usually like the one above. Is there any magical package to do this kind of stuff?
Thanks in advance.

A: You need quite a big text width for making a decent table.
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[brazil]{babel}
\usepackage[margin=1cm]{geometry}
\usepackage{array}

\newlength{\monthwidth}
\newlength{\yearwidth}
\AtBeginDocument{% after fonts have been set
  \settowidth{\yearwidth}{\textbf{0000}}%
  \setlength{\monthwidth}{\dimexpr(\textwidth-\yearwidth-26\tabcolsep-14\arrayrulewidth)/12\relax}%
}
\newcommand{\multicell}[2]{% #1 = cols to span, #2 = contents
  \multicolumn{#1}{c|}{%
    \parbox{\dimexpr#1\monthwidth+\numexpr2*(#1-2)\relax\tabcolsep+\numexpr#1-1\relax\arrayrulewidth\relax}{%
      \centering\vspace*{3pt}\hspace{0pt}#2\par\vspace*{3pt}%
    }%
  }%
}

\begin{document}

\begin{center}
\footnotesize
\begin{tabular}{ |p{\yearwidth}| *{12}{>{\centering\arraybackslash}p{\monthwidth}|} }
\cline{2-13}
\multicolumn{1}{c|}{}
& \textbf{Jan} & \textbf{Fev} & \textbf{Mar} & \textbf{Abr} & \textbf{Mai} & \textbf{Jun}
& \textbf{Jul} & \textbf{Ago} & \textbf{Set} & \textbf{Out} & \textbf{Nov} & \textbf{Dez} \\
\hline
\textbf{2013} & \multicell{12}{Medicina Interna\\ HSM} \\
\hline
\textbf{2014} & \multicell{12}{Endocrinologia, Diabetes, Metabolismo e Nutrição \\ HSM} \\
\hline
\textbf{2015} & \multicell{2}{Laboratório de Endocrinologia \\ HSM}
                    & \multicell{2}{Endocrinologia Pediátrica \\ HSM}
                    & \multicell{8}{Endocrinologia, Diabetes, Metabolismo e Nutrição \\ HSM} \\
\hline
\textbf{2016} & \multicell{4}{Endocrinologia, Diabetes, Metabolismo e Nutrição \\ HSM}
                    & \multicell{3}{Medicina Nuclear Oncologia Tiroideia \\ IPOLFG}
                    & \multicell{2}{Imagiologia \\ HSM}
                    & \multicell{3}{Endocrinologia da Reprodução \\ HSM} \\
\hline
\textbf{2017} & \multicell{5}{Endocrinologia, Diabetes, Metabolismo e Nutrição \\ HSM}
                    & \multicell{2}{Endocrinologia Diabetes e Metabolismo \\ EMC}
                    & \multicell{5}{Endocrinologia, Diabetes, Metabolismo e Nutrição \\ HSM} \\
\hline
\end{tabular}
\end{center}

\end{document}


text:
Q: How to capture delimiters also as tokens in result Below is the code for creating tokens based on delimiters. This will give the tokens but will not consider delimiters in token result. If we want to include the delimiters also in result, what should be the approach.
StringTokenizer tr=
new StringTokenizer("Will you come, yes/no",",/");
while (tr.hasMoreElements( ))
System.out.println(tr.nextElement( )+",");

So output should be tokens as:
Will, ,you, ,come, ,yes,/,no,
(Instead of just will,you,come,yes,no,)

A: / is not coming as one of the tokens because it is not surrounded by the delimiter. If you want it to be parsed as one of the tokens then you can surround it with delimiters.
Here is the code snippet:
public static void main (String[] args)
{
    String sample = "Will you come,yes/no";
    StringTokenizer tr = new StringTokenizer(sample.replace(" ",",").replace("/",",/,"),",");
    while (tr.hasMoreElements())
        System.out.println(tr.nextElement() + ",");
}

Output:
Will,
you,
come,
yes,
/,
no,


text:
Q: Skip database on import of MySQL dumpfile I created a dumpfile with this command:
mysqldump -p3307 --quick -u root --password="password" --all-databases > all_databases04292011.sql

I then attempted to import this dumpfile into a new MySQL server, however it fails trying to write to the information_schema database. Is there a way to skip this database on import?

A: You can write a program editing the all_databases04292011.sql dumpfile, to delete all the records in information_schema database.
It is not that hard, since the dumpfile is well structured.
Just open all_databases04292011.sql using your favourite editor, then find
--
-- Current Database: `information_schema`
--

Delete every line below this until you see the next
--
-- Current Database: `xxxxxx`
--


text:
Q: Count hours between times I asked a similar question a few days ago but didn't quite get an answer for what I'm looking for, specifically with SQL (the question is Check if time in a database surpasses specific hour).
Basically, I've got the following query:
    SELECT DAYNAME(arrivalTime) AS day, COUNT(*) AS count
    FROM bookings
    WHERE HOUR(arrivalTime) = 13
    AND DAYNAME(arrivalTime) = 'Monday'

This will count the number of entries there are for bookings that start at 13:00 on a Monday. How do I change this so that each hour from the arrival time to the pick up time is counted?
For example, if I had the arrivalTime - pickupTime as 13:00 - 17:00 then 13:00, 14:00, 15:00 and 16:00 would all count this as an entry.
Had a couple of suggestions but didn't really manage to get far with them.
Edit:
The calendar I'm making:

My database:

Samples and expected outputs:
arrivalTime - pickupTime

13 - 15 (hours 13, 14 are counted)

10 - 14 (hours 10, 11, 12, 13 are counted)

16 - 17 (hours 16 are counted)

13 - 17 (hours 13, 14, 15, 16 are counted)

11 - 12 (hours 11 are counted)

Basically, right now it's simply counting the number of entries that have arrivalTime as X. So if we have 10 entries that start at 13:00 on a Monday, on my HTML table that I linked it will have the number 10 next to 13:00. I want to make it that each hour is counting how many bookings actually go over then.
To make it easier to visualise, this is simply put a dog kennel. We're checking to see how many dogs are in the kennel at each hour. Thus, if there's a booking from 13:00 - 15:00 it shouldn't just add a +1 to 13:00 but also to 14:00 as the time overlaps. Maybe a little bit more complex than I thought it'd be.
Edit 2:
Right now I've got this query in my function
SELECT DAYNAME(arrivalTime) AS day, COUNT(*) AS count
FROM bookings
WHERE HOUR(arrivalTime) = $hour
AND DAYNAME(arrivalTime) = '$dayname'

In HTML I pass the values like so

10:00

   (<?php $var->get_CalendarCount($conn,10,'Monday'); ?>)

A: You mean like this?
SELECT DAYNAME(arrivalTime) AS day, COUNT(arrivalTime) AS count
  FROM bookings
  WHERE TIME(arrivalTime) BETWEEN '13:00:00' AND '17:00:00'
  AND DAYNAME(arrivalTime) = 'Monday'

Or if you need only 13, 14, 15, 16, 17 then:
SELECT DAYNAME(arrivalTime) AS day, COUNT(arrivalTime) AS count
  FROM bookings
  WHERE (TIME(arrivalTime) BETWEEN '13:00:00' AND '17:00:00')
  AND MINUTE(TIME(arrivalTime)) = 0
  AND SECOND(TIME(arrivalTime)) = 0
  AND DAYNAME(arrivalTime) = 'Monday'

// EDIT to answer comment
So you need to count bookings between (example) 13:00 - 17:00 from periods 13:00 - 13.59, 14.:00 - 14:59 etc?
SELECT DAYNAME(arrivalTime) AS day, COUNT(arrivalTime) AS count, CONCAT(HOUR(arrivalTime), ':00 - ', HOUR(arrivalTime) + 1, ':00') as Hours
  FROM bookings
  WHERE (HOUR(arrivalTime) BETWEEN '13' AND '17')
  AND DAYNAME(arrivalTime) = 'Monday'
  GROUP BY HOUR(arrivalTime);

// EDIT 2
Unfortunately I don't have time now to fix the query I wrote, but it would be easier to use a function instead of single select (make select for each one hour period).
But there are two things:

*

*If you want it for each hour from ex: 10:00 - 17:00: (ex: 10:00 - 10:59), it would be all records with pickupTime OR arrivalTime between 10:00 AND 10:59

*if you want then total from this period ex 10:00 - 17:00, it won't be a sum, cuz there will be duplicates, ex: 10:00 - 10:59 may contain same records as 11:00 - 11:59.

// EDIT 3
Check if this function will satisfy your needs, when you call it for any cell of your calendar. If you want to return x instead of zero, simply put if and return char. It should work for 10:00 - 10:59 (one hour periods) or 10:00 - 16:59 (total period)
CREATE FUNCTION fn_getCount(p_dayName VARCHAR(10), p_fromHour INT, p_toHour INT)
  RETURNS INT
BEGIN
  DECLARE v_count INT;

  SELECT COUNT(b.arrivalTime) INTO v_count
    FROM bookings b
    WHERE
      ((HOUR(b.arrivalTime) BETWEEN p_fromHour AND p_toHour - 1) OR
      (HOUR(b.pickupTime) BETWEEN p_fromHour AND p_toHour - 1) OR
      (HOUR(b.arrivalTime) < p_fromHour AND HOUR(b.pickupTime) > p_toHour - 1)) AND
      DAYNAME(b.arrivalTime) = p_dayName;

  RETURN v_count;
END;

Call it like this:
SELECT fn_getCount('Saturday', 14, 17);

I don't know php, I know .NET, but if you want a whole table returned by the server, you can simply make a stored procedure which call this function wherever needed and call the procedure from PHP. I am not an expert but if you want whole calendar returned by the Server, you would have to create pivot table
// EDIT 4 (30-11-2015 00:04)
Here you have Function for single cell and stored procedure which generates entire calendar, I have added function to evaluate first day of a week for supplied date, because you need to provide date as well cuz otherwise it will return all Mondays, not only the one from the week you are interested in.
Function to evaluate single cell:
DELIMITER $$
DROP FUNCTION IF EXISTS fn_getCount;
CREATE FUNCTION fn_getCount(p_weekDate DATE, p_dayName VARCHAR(10), p_fromHour INT, p_toHour INT)
  RETURNS INT
BEGIN
  DECLARE v_count INT;

  SELECT COUNT(b.arrivalTime) INTO v_count
    FROM bookings b
    WHERE
      ((HOUR(b.arrivalTime) BETWEEN p_fromHour AND p_toHour - 1) OR
      (HOUR(b.pickupTime) BETWEEN p_fromHour AND p_toHour - 1) OR
      (HOUR(b.arrivalTime) < p_fromHour AND HOUR(b.pickupTime) > p_toHour - 1)) AND
      DAYNAME(b.arrivalTime) = p_dayName AND
      (DATE(b.arrivalTime) BETWEEN fn_firstDayOfWeek(p_weekDate) AND DATE_ADD(fn_firstDayOfWeek(p_weekDate), INTERVAL 6 DAY));

  RETURN v_count;
END$$
DELIMITER ;

Function to return date of Monday for the week from which we provided a date as parameter.
DELIMITER $$
DROP FUNCTION IF EXISTS fn_firstDayOfWeek;
CREATE FUNCTION fn_firstDayOfWeek(day DATE)
  RETURNS DATE
BEGIN
  RETURN SUBDATE(day, WEEKDAY(day));
END$$
DELIMITER ;

Procedure to generate entire calendar as pivot table:
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_GetCalendar;
CREATE PROCEDURE sp_GetCalendar(
  p_weekDate DATE,
  p_fromHour INT,
  p_toHour INT
)
BEGIN
  DECLARE v_currHour INT;
  DROP TEMPORARY TABLE IF EXISTS Calendar;
  CREATE TEMPORARY TABLE Calendar
  (
    Hours VARCHAR(30),
    Monday VARCHAR(30),
    Tuesday VARCHAR(30),
    Wednesday VARCHAR(30),
    Thursday VARCHAR(30),
    Friday VARCHAR(30),
    Saturday VARCHAR(30),
    Sunday VARCHAR(30)
  );

  SET v_currHour = p_fromHour;
  START TRANSACTION;
  WHILE (v_currHour < p_toHour) DO
    INSERT INTO Calendar (Hours, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
      VALUES (
        CONCAT(v_currHour, ':00 - ', v_currHour + 1, ':00'),
        CASE WHEN fn_getCount(p_weekDate, 'Monday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Monday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Tuesday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Tuesday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Wednesday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Wednesday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Thursday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Thursday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Friday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Friday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Saturday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Saturday', v_currHour, v_currHour + 1) END,
        CASE WHEN fn_getCount(p_weekDate, 'Sunday', v_currHour, v_currHour + 1) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Sunday', v_currHour, v_currHour + 1) END);
    SET v_currHour = v_currHour + 1;
  END WHILE;
  INSERT INTO Calendar (Hours, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
    VALUES (
      CONCAT('Total: ', p_fromHour, ':00 - ', p_toHour, ':00'),
      CASE WHEN fn_getCount(p_weekDate, 'Monday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Monday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Tuesday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Tuesday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Wednesday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Wednesday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Thursday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Thursday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Friday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Friday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Saturday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Saturday', p_fromHour, p_toHour) END,
      CASE WHEN fn_getCount(p_weekDate, 'Sunday', p_fromHour, p_toHour) = 0 THEN 'x' ELSE fn_getCount(p_weekDate, 'Sunday', p_fromHour, p_toHour) END);
  COMMIT;

  SELECT * FROM Calendar;
  DROP TEMPORARY TABLE IF EXISTS Calendar;
END$$
DELIMITER ;

Call them for testing like this:
CALL sp_GetCalendar('2015-11-07', 10, 17);

SELECT fn_getCount('2015-11-07', 'Saturday', 10, 17);

SELECT fn_firstDayOfWeek('2015-11-07');

Output:

Code might be a little bit redundant, but I am really short on time.

A: I guess you need to count even there is no booking in a particular Hour. You need a Hour's table to do this.
SELECT H.day_name AS day,
       Count(b.arrivaltime) AS count
FROM   hour_table H
       LEFT OUTER JOIN bookings B
                    ON h.day_name = Dayname(arrivaltime)
                       AND h.hours = Hour(arrivaltime)
WHERE  h.hours BETWEEN 13 AND 17
       AND h.day_name = 'Monday'
GROUP  BY H.day_name

Edit : If you don't want to count every booking between X and Y. Then you need conditional Aggregate. Something like this
Count(case when h.hours BETWEEN 13 AND 17 then b.arrivaltime .. end) AS count

Can add full answer when there is enough information in question


text:
Q: different regex behaviour on different devices I'm having a strange bug when I try to check an EditText (I want the text to be an IBAN, like FR76 2894 2894 2894 289), so I'm doing this (overriding my edit text's onTextChanged):
// format with IBAN regex
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    editText.setText(editText.getText().toString().replaceAll(" ", "")
            .toUpperCase().replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 "));
}

I'm doing a comparison with two different Android phones: an Asus Zenfone and an Honor 5C.
Both devices have the same bevahiour on first char typed (valid only if it's a letter). But then, when I type a second letter (text should be FR after this):
Honor 5C: (expected behaviour)

Asus Zenfone: (wrong behaviour)

Any idea?
Thanks for your help.

A: As you can see in the documentation, it seems like a bad idea to call setText from onTextChanged:

This method is called when the text is changed, in case any subclasses
  would like to know. Within text, the lengthAfter characters beginning
  at start have just replaced old text that had length lengthBefore.
It is an error to attempt to make changes to text from this callback.

Have you tried using a TextWatcher, on your EditText? For instance:
editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // This is only a sample code trying to reproduce your current behavior.
        // I did not test it.
        String iban = s.toString().toUpperCase().replaceAll(" ", "");
        String compactIban = iban.replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ");
        s.replace(0, s.length(), compactIban);
      }
    });


text:
Q: Elementary question | Possible ways to divide 8 pens amongst 4 girls? So I have a simple  combinatorics question which I am trying to explain to students I am tutoring but I am not sure which formula is used in the solution and how to explain it to my mentees.

If 8 pens are to be divided amongst 4 girls:
(a) How many divisions are possible?
(b) What if we gave each girl at least one pen?

Solution a
\begin{align}
\frac{11!}{8!3!}
\end{align}
Solution b
\begin{align}
\frac{7!}{4!3!}
\end{align}
Could you please show where the solution comes from? I think it is of the form:
\begin{align}
\frac{(n + r - 1)!}{n!(r-1)!},
\end{align}
but I could be wrong.

A: Imagine you have $8$ pens and $3$ sticks - this is $11$ objects in total.
The total number of ways to arrange this (non-distinct) objects is given by $\binom{11}{3}$.
So what? Well, if you read an arrangement from left to right, give all the pens to the left of the first stick to girl 1. Give the pens between stick 1 and stick 2 to girl 2, between stick 2 and stick 3 to girl 3 and the pens to the right of stick 3 to girl 4.
If there are no pens in any of the partitions, the corresponding girl gets no pens.
As each combination is different, this is then the number of ways to split $8$ pens into $4$ girls.
If every girl is to receive at least one pen, do this first, and so now there are only $7$ pens remaining, and so we use $\binom{7}{3}$ instead to do the same trick.


text:
Q: Why does npm sometimes use a different version from elsewhere in the dependency tree rather than install a required module? I'm well aware npm dependencies are tree shaped, and that two different modules can load two different versions of a dependency at the same time.
So when I see an npm error like:
npm WARN unmet dependency /somedir/node_modules/gulp-browserify
/node_modules/browserify/node_modules/module-deps
requires stream-combiner@'~0.1.0' but will load /somedir/node_modules
/gulp-browserify/node_modules/browserify/node_modules/stream-combiner,
which is version 0.0.4

Why doesn't npm install the module-deps dependency (stream-combiner@'~0.1.0') underneath module_deps/node_modules/stream-combiner?
Or, more generally: why does npm sometimes not install a module where it is needed, using a different version on that module from elsewhere in the dependency tree instead?


text:
Q: JavaFX terminate background task I have external Processor.process(...) heavy method that can be running for a long time (tens of minutes) in normal case.
I want to show some loading screen with 'Cancel' button and run that Processor in background. I want to stop executing background task when 'Cancel' button clicked.
The problem is that I have a single call to Processor.process(...).
If I had some task in a loop, I would do checks like if( isCancelled() ){ break; } or similar on each iteration.
Is there any way to terminate|kill that heavy background task? Let's assume that Processor.process(...) is very long 'atomic' operation (I just don't want to change all the logic deep behind it to accomplish this single task)
Here is how I start loading screen and background task:
private void handleProcess(ActionEvent event) {

    SomeService service = new SomeService();
    // ... configuring service

    Stage loadingStage = new Stage();
    // ... configuring 'loading' stage

    service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

        @Override
        public void handle(WorkerStateEvent t) {
            @SuppressWarnings("unchecked")
            Entity entity = (Entity) t.getSource().getValue();
            // ... do some stuff
            loadingStage.close();
        }
    });

    service.start();     // launch background process
    loadingStage.show(); // show 'loading' screen
}

UPDATED Here is Service for background job:
private static class SomeService extends Service<Entity> {
    private Thread threadToStopOnCancel;         // added
    // fields, getters, setters omitted

    protected Task<Entity> createTask() {

        // _params initialization omitted
        return new Task<Entity>() {
            protected Entity call() throws IOException {
                 threadToStopOnCancel = Thread.currentThread();    // added
                 return Processor.process(_params);
            }
        };
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void cancelled() {
        if (threadToStopOnCancel != null) { threadToStopOnCancel.stop(); }  // added
        super.cancelled();
    }

For now, I call service.cancel(); from loading screen. But it just sets the service's state to 'CANCELED', and the task is still working in background.

A: In your service definition you can override the cancelled() method or pass an EventHandler to the setOnCancelled() method.
See here.


text:
Q: Show that $f(x,y) = (x,1+y)$ is not linear I understand why functions like df/dx and integral of x are linear functions but I dont understand the format of this question and how to set the problem up based on what's given:

In order to prove this is not liner I have to show that f(ax+y) does not equal af(x)+f(y). How would I set that up in this case?

A: You can also try to see if it satisfies $f(A+B) = f(A)+f(B)$.  Here, let:
$$A = \begin{pmatrix} 1 \\ 0\end{pmatrix},\quad B = \begin{pmatrix} 0 \\ 1\end{pmatrix}$$
We get that:
$$f(A+B) = \begin{pmatrix} 1\\2\end{pmatrix}$$
but,
$$f(A)+f(B) = \begin{pmatrix} 1 \\1\end{pmatrix}+\begin{pmatrix} 0 \\ 2\end{pmatrix} = \begin{pmatrix} 1 \\ 3\end{pmatrix}\neq f(A+B)$$
The easiest way to see this is just that $f(0)\neq 0$, but you can use the linearity condition (as I showed above).

A: Linear functions always send the origin to itself. $f(0,0) = (0,0)$ must be true for $f$ to be linear.
Your example is in fact an affine function, which basically means a linear function translated from the origin. Yes, the terminology is not quite the easiest to picture. Functions that describe lines that do not go through the origin are affine, but not linear.


text:
Q: PyQT5 'QPoint' object has no attribute 'pos' i have some problem on pyQT5. In the TextArea section, when I right click a word, I want to open a menu and print the synonyms of the word there. I found a sample menu function but I get the error in the header (PyQT5 'QPoint' object has no attribute 'pos'). What does this stem from? Is there another way I can follow?
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton,QTextEdit
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
                             QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
                             QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu)

from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import *
from PyQt5 import QtGui
from PyQt5.QtGui import QPainter, QColor, QPen,QCursor

class MainWindow(QMainWindow):
    fileName=""
    def __init__(self):
        QMainWindow.__init__(self)
        #self.setStyleSheet("background-color: white;")
        self.setMinimumSize(QSize(1080, 720))
        self.setWindowTitle("Simurg")
        self.choose_file_button()
        self.textareaMain()
        self.textareaSimurg()
        self.selectItem()
        self.chooseSimurgFunciton()
        text=QPlainTextEdit()
        outputText = QTextEdit()

    def chooseSimurgFunciton(self):
        pybutton = QPushButton('Fonksiyonu Uygula', self)
        pybutton.resize(150,32)
        pybutton.move(460, 5)

    def choose_file_button(self):
        pybutton = QPushButton('Dosya Sec', self)
        pybutton.clicked.connect(self.chooseFile)
        pybutton.resize(100,32)
        pybutton.move(10, 5)

    def chooseFile(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        self.text.setPlainText(open(self.fileName).read())
        if self.fileName:
            print(self.fileName)
        print('Clicked Pyqt button.')

    def textareaMain(self):
        self.text = QPlainTextEdit(self)
        self.text.insertPlainText("Ana yazı buraya gelecek.\n")
        self.text.move(10,60) #1.para sol sağ 2. para alt-üst
        self.text.resize(525,450)
        #yazıldıkça veriyi çek.
        self.text.textChanged.connect(
            lambda: print(self.text.document().toPlainText()))
        self.text.selectionChanged.connect(self.handleSelectionChanged)

    def handleSelectionChanged(self):
        cursor = self.text.textCursor()
        print ("Selection start: %d end: %d" %
           (cursor.selectionStart(), cursor.selectionEnd()))
        string=str(self.text.document().toPlainText())
        print("\033[1;31m"+string[cursor.selectionStart():cursor.selectionEnd()]+"\033[0m")
        word=string[cursor.selectionStart():cursor.selectionEnd()]
        redColor = QColor(255, 0, 0)
        blue = QColor(0, 0, 255)
        self.outputText.setTextColor(redColor)
        self.outputText.insertPlainText(" "+word)
        self.outputText.setTextBackgroundColor(blue)
        self.outputText.insertPlainText(" selam ")
        self.text.setContextMenuPolicy(Qt.CustomContextMenu)
        self.text.customContextMenuRequested.connect(self.showMenu)

    def showMenu(self,event):
        contextMenu = QMenu(self)
        newAct = contextMenu.addAction("New")
        openAct = contextMenu.addAction("Open")
        quitAct = contextMenu.addAction("Quit")
        action = contextMenu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAct:
            self.close()

    def textareaSimurg(self):
        self.outputText = QTextEdit(self)
        self.outputText.insertPlainText("Simurg sonucu buraya gelecek. Altı çizili bir şekilde.\n")
        self.outputText.move(545,60) #1.para sol sağ 2. para alt-üst
        self.outputText.resize(525,450)

    def selectItem(self):
        self.combo_box = QComboBox(self)
        self.combo_box.setGeometry(150,5,300,30)
        geek_list = ["Lütfen Bir Fonksiyon Seçin","Kelime Türkçe Mi?","Doğru Bilinen Yanlışlar","Özne-Yüklem İlişkisi"]
        self.combo_box.addItems(geek_list)
        self.combo_box.setCurrentIndex(0)
        self.combo_box.currentIndexChanged.connect(self.selectionchange)

    def selectionchange(self,i):
        print ("Items in the list are :")
        for count in range(self.combo_box.count()):
            print (self.combo_box.itemText(count))
        print ("Current index",i,"selection changed ",self.combo_box.currentText())
        if(i==2):
            metin=self.text.document().toPlainText()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv) #def
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

A: The QWidget::customContextMenuRequested signal passes a QPoint as its parameter, so the argument to showMenu is also a QPoint.
Change the definition of showMenu to (untested)...
def showMenu(self,pos):
    contextMenu = QMenu(self)
    newAct = contextMenu.addAction("New")
    openAct = contextMenu.addAction("Open")
    quitAct = contextMenu.addAction("Quit")
    action = contextMenu.exec_(self.mapToGlobal(pos))
    if action == quitAct:
        self.close()


text:
Q: Contact Form 7 - acceptance error message position Is there a way to specify the location of the error message for Acceptance?

Here is my code in the form:

[acceptance agree box]I have read and accept the privacy policy.

What I want to do is to place the error message at the purple box(as the image indicated.)

A: I had this same problem and I found that this code worked for me. You will have to find the class of the form-control wrap element that is wrapping your input. Mine was named 'accept-terms'. Yours might be named something different.
CSS:
.wpcf7-form-control-wrap.accept-terms input {
  float: left;
  margin-right: 10px;
  display: inline-block;
  clear: both;
}

.wpcf7-form-control-wrap.accept-terms span.wpcf7-not-valid-tip {
  float: left;
  clear: both;
  margin-top: 10px;
}

input[type="submit"] {
  clear:both;
}

Form Setup:
[acceptance accept-terms] Your checkbox or acceptance box

[submit class:cta-button "Send"]

Here is what it looked like before
Here is what it looks like after


text:
Q: Error loading main.py to MicroPython on NodeMCU Lilin V3 I have a NodeMCU board and I'm trying to use it for IoT. I'm using mac and this is the commands I'm using to install MicroPython:
esptool.py --port /dev/cu.usbserial-110 erase_flash esptool.py --port /dev/cu.usbserial-110 --baud 115200 write_flash --flash_size=detect 0 sp8266-512k-20220618-v1.19.1.bin
The installation looks to work fine, I can even access the REPL but then, to load the main.py file I want it to run, I do:
ampy --port /dev/cu.usbserial-110 -b 115200 put main.py
And I get the following error:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/bin/ampy", line 8, in <module>
    sys.exit(cli())
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/ampy/cli.py", line 264, in put
    board_files.put(remote, infile.read())
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/ampy/files.py", line 223, in put
    self._pyboard.exec_("f.write({0})".format(chunk))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/ampy/pyboard.py", line 279, in exec_
    raise PyboardError('exception', ret, ret_err)

I have tried to reset the board many times, be sure that the screen command I used to connect the REPL is not in progress anymore, and even different baud rates, but nothing is working...
Any idea?
Thank you so much!


text:
Q: Angular Material 2 : How to overwrite Dialog max-width to 100vw? I am trying to create 100% width Dialog. But As the original settings, it is restricted to 80vw.
.mat-dialog-container{
  max-width:80vw;
}

I have tried following ways to overwrite this value. But they weren't successful.
.mat-dialog-container {
  max-width: none;
  width: 100vw;
  height: 100vh;
}

And
.mat-dialog-container {
    max-width: none !important;
}

Someone please advise me how to overwrite 80vw to 100vw. Thank you.

A: Easiest way to solve this:
const dialogRef = this.dialog.open(MyDialogComponent, {
        width: '100vw',
        maxWidth: '100vw',
    }
)

A: Add a css class in your global styles.css e.g.
.full-width-dialog .mat-dialog-container {
  max-width: 100vw !important;
}

.. then provide the panelClass to your dialog:
this.dialog.open(MyDialogComponent, {panelClass: 'full-width-dialog'})

Read this documentation.

A: you can set default options:
 { provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { maxWidth: '95vw', hasBackdrop: true } },

A: I need to do this with CSS because I need it bootstrap responsive. This worked for me with NgMaterial 12.2.0
    ***in my code
    this.dialog.open(TaskItemModalComponent, {
          panelClass:'d2x-dialog-panel',
          data: taskItem,
          disableClose: true
        });

    ***in my styles.scss
    .d2x-dialog-panel {
      max-width: 450px !important;
    }

  @include for-xsmall() {
        .d2x-dialog-panel {
        max-width: 100vw !important;
    }
  }

A: Try to use the property name directly as below:
this.dialog.open(MyDialogComponent, {maxWidth: '100vw !important'});

This works for me in Angular 7.

A: I prefer to set things in css, then I can use different settings for responsive design.
I found myself having to use !important just to circumvent the default 90vw.
Turns out if you put maxWidth: undefined it won't do that.
dialog.open(DialogChoicesComponent, { ...options, maxWidth: undefined });

As for setting css that's a whole other topic, but you can set a backdropClass and panelClass and style them as you wish.

A: You can achieve by two ways:

*

*create a css class className and set max-width: 100vw ( don't restrict with mat-dialog-container because sometime cdk-overlay selector max-width is different.

*Pass as a property or config on the time of Dialog open
this.dialog.open(MyComponent, {maxWidth: '100vw'}); and do not forget to set actual width.

A: Are you using material design and trying to override default class?
You need to use more specific css rule. Target this from parent element and then try, !important may also be helpful.


text:
Q: Как сделать сколько пользователь раз нажал столько и срабатывала функция а не 1 раз Есть код, мне нужно что бы все это дело работало неограниченное количество раз. Я в принципе могу влаживать функцию в функцию к примеру раз 10,ну это понятное дело что бред. Нужно что бы работало столько раз сколько я пожелаю нажать. Поможет кто с такой детской задачей?
   let div = document.querySelector('.div-1');
    div.ondblclick = function f1(){
      div.classList.add('active');

      div.ondblclick = function f1(){
        div.classList.remove('active');
      }
    }

A: Попробуйте варианты:
let div = document.querySelector('.div-1');

div.ondblclick = function f1(){
  div.classList.toggle('active');
}

let div = document.querySelector('.div-1');

div.ondblclick = function f1(){
  if (div.classList.contains('active')) div.classList.remove('active');
  else div.classList.add('active');
}


text:
Q: What does Paul mean about "terrible purpose"? In Dune book 1, there are various mention of "terrible purpose" in the thinking of Paul and he also mention quite a few times that he didn't want the "jihad" to happen. What is this whole thing about?

The thought was both reassuring and frustrating. Somewhere ahead of him on this path, the fanatic hordes cut their gory path across the universe in his name. The green and black Atreides banner would become a symbol of terror. Wild legions would charge into battle screaming their war cry: "Muad'Dib!" It must not be, he thought. I cannot let it happen. But he could feel the demanding race consciousness within him, his own terrible purpose, and he knew that no small thing could deflect the juggernaut.

A: As the quotation you included states, Paul foresees that hordes of fanatical followers will rampage across the galaxy, wreaking terrible destruction in his name under the guise of religious beliefs centered around him.  His "terrible purpose" is to be the focus that creates this religious "holy war" (i.e. jihad).
The reasons why this jihad is inevitable are clarified later in the book, and explained in more detail in later books.

 Essentially, as the Kwisatz Haderach, Paul's mastery of prescience and the inner voices of his genetic memory guide him on to establish the beginnings of the Golden Path, which dictates events that shape the role and destiny of humanity for thousands of years, with the ultimate goal of saving them from an unnamed deadly menace that would otherwise destroy all of human kind.  Paul understands to an undisclosed extent that this sole path to survival for the species will entail horrible deeds, terrible suffering, and general oppression and misery of the vast majority of humans.


text:
Q: Get total count of distance with overlapping ranges excel I am trying to find a way to calculate the total distance from overlapping ranges. I have attached an image to help explain this. Essentially I want to know how much of my given range has an object on it.

Using the example above with my total range being 35. There is an object from 0-5 and 3-15. Meaning there is an object from 0-15. And From 20-27, 27-32, 17-24, meaning this object is 17-32.
Giving us:
0-15 = 15
17-32 = 15
=a total distance of 30 out of my total range of 35.
Being able to get a total distance would be enough, otherwise if there is a way to merge the ranges that overlap and then I can calculate from there.
I am using Excel or PowerBI to do this so a solution in either of these would be very helpful. Have seen some solutions using dates but they seem to only work for 2 dates and not more. My data will potentially have 100s of records.
Thanks

A: Let's count the lengths of all subranges Not Overlapped by any Object, and then subtract this value from the total length of the entire range.
Important! As long as the objects in the table are listed in an arbitrary order, the formula will give an incorrect result. Therefore, first sort the table in ascending column To
Now, from the beginning of each object, subtract the end of the previous object. Let's do this not for one cell, but for the entire range at once:

(I added rows with the beginning of the range and its end for clarity)
We are not interested in overlapping areas, so we will get rid of negative numbers using the IF() function. The total sum of positive values will be obtained using the {SUM()} function (as an Array Function!):
{=SUM(IF(B3:B8-C2:C7>0;B3:B8-C2:C7;0))}
For the value set in question, this will return 5
Now 35(end) - 0(start) - 5 = 30

A: A different way to do it would be to collect the left sides of the "20-27" type expressions and find their minimum (MIN) and do the same for the right side and find their maximum (MAX). Subtract the minimum from the maximum and add 1 for the number of cells used in all the ranges, counting each one only once.
It will NOT account for gaps as probably JohnSUN's approach will though I read the problem as gaps not being something to consider possible.
For example, using the latest and the greatest:
=VALUE(MAX(VALUE(TEXTAFTER(IF(C4:E4="",$C$4,C4:E4),"-"))+1) - MIN(VALUE(TEXTBEFORE(IF(C4:E4="",$C$4,C4:E4),"-"))))

which, very strangely, insists upon changing formatting to Text upon pressing Enter! Changing formatting back to General and coercing the change with F2-Enter does then give a result and that result cell can be copied and pasted without further aggravation, though editing it... and no obvious reason why such a thing can and does happen.
So, for entries in the range C4:E4, it gives the total distance. One could widen that range to include as many inputs as one wishes. And cells in the input range can be empty.
For the values themselves, something slightly different:
=INDIRECT(  "A"  &  MIN(VALUE(TEXTBEFORE(IF($C$4:$E$4="",$C$4,$C$4:$E$4),"-")))  &  ":A"  &  MAX(VALUE(TEXTAFTER(IF($C$4:$E$4="",$C$4,$C$4:$E$4),"-"))))

where one would place whatever column letter was needed for a column of data, or reverse the logic for row data (so finding columns instead of rows).
For that matter, one could use the latter formula inside a ROWS function to find only the total distance.
Not as elegant, and will not notice gaps, but, different, and perhaps easier to apply in related, but differing circumstances. Perhaps.
Also, it would be a BEAST of an approach if one has not the latest text manipulation functions. Highly affected also by users not sticking to using the hyphen...


text:
Q: Center caption but ignore certain parts of TikZ picture Consider the following MWE:
\documentclass[a4paper]{scrartcl}

\usepackage{mathtools}
\usepackage{amssymb}

\usepackage[compatibility=false]{caption}
\usepackage[list]{subcaption}

\usepackage{fancyvrb}

\usepackage{tikz}
\usetikzlibrary{patterns, fit, positioning, calc, shapes.arrows}

\usepackage[active, tightpage, floats, displaymath]{preview}

\mathtoolsset{%
  mathic=true
}

% Vectors and matrices
\renewcommand*{\vec}[1]{\mathbf{#1}}
\newcommand{\mat}[1]{\mathbf{#1}}
\newcommand{\trans}{\intercal}

% Operators
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator*{\argmax}{arg\,max}

\begin{document}
\begin{figure}
  \centering
  \captionsetup[subfigure]{margin={2.5cm, 0cm}}
  \begin{subfigure}[b]{0.60\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:the] (the) {\(\mat W\)};
      \node[draw, rectangle, right=of the, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, right=of cat, label=below:sat] (sat) {\(\mat W\)};

      \node[draw, rectangle, fit=(the.west) (the.east), pattern=vertical lines, above=of the] (in_the) {};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in_cat) {};
      \node[draw, rectangle, fit=(sat.west) (sat.east), pattern=vertical lines, above=of sat] (in_sat) {};

      \node[draw, rectangle, fit={($(cat.west) + (-8pt,0pt)$) ($(cat.east) + (8pt,0pt)$)}, pattern=vertical lines, above=2cm of cat] (in) {};
      \node[draw, rectangle, above=of in, label=above:mat] (out) {\(\vec b\), \(\mat U\)};

      \node[left=of the, outer sep=0] (embed) {embed};
      \node[above=2cm of embed, outer sep=0] (concatenate) {concatenate};
      \node[above=1cm of concatenate, outer sep=0] {softmax};

      \foreach \word in {the, cat, sat}{%
        \draw[->] (\word) -- (in_\word);
        \draw[->] (in_\word) -- (in);
      }

      \draw[->] (in) -- (out);
    \end{tikzpicture}
    \caption{CBOW model}\label{fig:cbow}
  \end{subfigure}
  \captionsetup[subfigure]{margin={0cm,0cm}}
  \begin{subfigure}[b]{0.35\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in) {};
      \node[draw, rectangle, above=2cmof in, label=above:on] (on) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, left=of on, label=above:sat] (sat) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, right=of on, label=above:the] (the) {\(\vec b\), \(\mat U\)};

      \draw[->] (cat) -- (in);
      \foreach \word in {sat, on, the}{%
        \draw[->] (in) -- (\word);
      }
    \end{tikzpicture}
    \caption{Skip\=/gram model}\label{fig:sg}
  \end{subfigure}
  \caption{\protect\Verb+Word2Vec+ with vocabulary size \(V\), context
    size \(C\), and embedding size \(N\)}
\end{figure}
\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:

Which typesets into:

As you can see, I have "centered" the "(a) CBOW model" caption by using \captionsetup[subfigure]{margin={2.5cm, 0cm}}.  My question is: is it possible not to have to do this?  Or at least somehow calculate the correct width by which I need to offset the caption?

A: You can use \useasboundingbox in TikZ to set the dimension of the picture. TikZ will then ignore everything after that command for calculating the picture size. With (current bounding box) you can reference the size of the picture so far. As long as you draw everything, which should count for the paper size, before the line \useasboundingbox (current bounding box) the picture will have the desired size.
Additionally, an empty subfigure is needed to allow for the overlap to the left. So it has to be the first. Of course the width of the left (well, now middle) subfigure has to be adjusted.
\documentclass[a4paper]{scrartcl}

\usepackage{mathtools}
\usepackage{amssymb}

\usepackage[compatibility=false]{caption}
\usepackage[list]{subcaption}

\usepackage{fancyvrb}

\usepackage{tikz}
\usetikzlibrary{patterns, fit, positioning, calc, shapes.arrows}

\usepackage[active, tightpage, floats, displaymath]{preview}

\mathtoolsset{%
  mathic=true
}

% Vectors and matrices
\renewcommand*{\vec}[1]{\mathbf{#1}}
\newcommand{\mat}[1]{\mathbf{#1}}
\newcommand{\trans}{\intercal}

% Operators
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator*{\argmax}{arg\,max}

\begin{document}
\begin{figure}
  \centering
% no longer needed
%  \captionsetup[subfigure]{margin={2.5cm, 0cm}}
  %empty subfugure to allow for overlap to the left
  \begin{subfigure}[b]{0.15\textwidth}
  \mbox{}
  \end{subfigure}
  \begin{subfigure}[b]{0.40\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:the] (the) {\(\mat W\)};
      \node[draw, rectangle, right=of the, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, right=of cat, label=below:sat] (sat) {\(\mat W\)};

      \node[draw, rectangle, fit=(the.west) (the.east), pattern=vertical lines, above=of the] (in_the) {};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in_cat) {};
      \node[draw, rectangle, fit=(sat.west) (sat.east), pattern=vertical lines, above=of sat] (in_sat) {};

      \node[draw, rectangle, fit={($(cat.west) + (-8pt,0pt)$) ($(cat.east) + (8pt,0pt)$)}, pattern=vertical lines, above=2cm of cat] (in) {};
      \node[draw, rectangle, above=of in, label=above:mat] (out) {\(\vec b\), \(\mat U\)};

      % set the picture size to everything drawn so far
      \useasboundingbox (current bounding box);

      % not taken into account for the picture size
      \node[left=of the, outer sep=0] (embed) {embed};
      \node[above=2cm of embed, outer sep=0] (concatenate) {concatenate};
      \node[above=1cm of concatenate, outer sep=0] {softmax};

      % this belongs to the main part, but it doesn't increase its size
      % otherwise it must be moved before \useasboundingbox
      \foreach \word in {the, cat, sat}{%
        \draw[->] (\word) -- (in_\word);
        \draw[->] (in_\word) -- (in);
      }

      \draw[->] (in) -- (out);
    \end{tikzpicture}
    \caption{CBOW model}\label{fig:cbow}
  \end{subfigure}
% no longer needed
%  \captionsetup[subfigure]{margin={0cm,0cm}}
  \begin{subfigure}[b]{0.35\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in) {};
      \node[draw, rectangle, above=2cmof in, label=above:on] (on) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, left=of on, label=above:sat] (sat) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, right=of on, label=above:the] (the) {\(\vec b\), \(\mat U\)};

      \draw[->] (cat) -- (in);
      \foreach \word in {sat, on, the}{%
        \draw[->] (in) -- (\word);
      }
    \end{tikzpicture}
    \caption{Skip\=/gram model}\label{fig:sg}
  \end{subfigure}
  \caption{\protect\Verb+Word2Vec+ with vocabulary size \(V\), context
    size \(C\), and embedding size \(N\)}
\end{figure}
\end{document}

A: This is a (relatively) less simple method than my original (relatively) simple answer, which is a bit more flexible and ever so slightly better tested. It requires etoolbox and xparse. (You could easily dispense with the latter, if desired, but it is convenient.)

*

*As I've set things up, this modifies all tikzpicture environments.

*

*It could be broadened to include \tikz macros, if required.

*If the global impact is undesirable, remove the every picture definition and simply use mark out in the optional argument to tikzpicture.

*It allows adjustment for material on the left, right, both or neither.
The only requirement for the simple case based on the MWE is to insert \tikzmarkerwest at the point in the picture where you want to mark the left of the part of the picture which \caption should use to place the caption. If you don't use the macro at all in the picture, the code just falls back to the left of the picture's bounding box, when the picture is complete. This happens in the second subfigure in the example.
The code of the first subfigure is rearranged, so that everything which \caption should ignore comes after the first part of the picture. \tikzmarkerwest is then inserted to mark the left side at this point.
...
      \foreach \word in {the, cat, sat}{%
        \draw[->] (\word) -- (in_\word);
        \draw[->] (in_\word) -- (in);
      }
      \draw[->] (in) -- (out);

That's everything we want \caption to use for placement, so mark the left of the picture now.
      \tikzmarkerwest

Now we put the stuff to the left of that point, which \caption should ignore.
      \node[left=of the, outer sep=0] (embed) {embed};
      \node[above=2cm of embed, outer sep=0] (concatenate) {concatenate};
      \node[above=1cm of concatenate, outer sep=0] {softmax};

Now we finish the picture and add the caption and label as usual.
    \end{tikzpicture}
    \caption{CBOW model}\label{fig:cbow}

For material on the right, \tikzmarkereast can be used instead of, or as well as, \tikzmarkerwest.
In some cases, it is inconvenient or impossible to rearrange the code in a picture in this way. It just can't be drawn easily, if at all, in the order required. For this reason, \tikzmarkereast and \tikzmarkerwest support an optional argument. If specified, this should be a coordinate in round brackets, as usual for coordinates. In this case everything to the right or left of the specified coordinate will be ignored when placing the caption.
The code which supports this defines the macro \tikzmarkerwest as follows.
\NewDocumentCommand \tikzmarkerwest { D () {current bounding box.west} } {%
  \coordinate (tikz marker west) at (#1);
  \let\tikzmarkerwestdefault\relax
}

This creates a coordinate (tikz marker west) in the appropriate place. It then makes sure that \tikzmarkerwestdefault does nothing successfully.
\tikzmarkereast is defined in the same way.
\NewDocumentCommand \tikzmarkereast { D () {current bounding box.east} } {%
  \coordinate (tikz marker east) at (#1);
  \let\tikzmarkereastdefault\relax
}

We make sure \tikzmarkerwestdefault and \tikzmarkereast are defined. By default, they do nothing.
\NewDocumentCommand \tikzmarkerwestdefault {} {}
\NewDocumentCommand \tikzmarkereastdefault {} {}

Now for the TikZ code.
\tikzset{%

The style mark out adds code to be executed at the beginning and end of the current picture, if given in the optional argument to the environment, or of all pictures, if configured as below.
  mark out/.style={%
    execute at begin picture={%
      \RenewDocumentCommand \tikzmarkerwestdefault {}
      {%
        \coordinate (tikz marker west) at (current bounding box.west);
      }%
      \RenewDocumentCommand \tikzmarkereastdefault {}
      {%
        \coordinate (tikz marker east) at (current bounding box.east);
      }%
    },

This redefines our \tikzmarkerwestdefault and \tikzmarkereastdefault macros to create coordinates (tikz marker west) and (tikz marker east) at the left and right of the current bounding box. These are just definitions, overriding the default empty ones. They don't actually create any coordinates yet.
    execute at end picture={%
      \tikzmarkerwestdefault
      \tikzmarkereastdefault

At the end of the picture, we execute \tikzmarkerwestdefault. If \tikzmarkerwest has been called within the picture, this will do nothing successfully. Otherwise, it will create the marker at the left of the current bounding box, which is the final bounding box for the picture. Similarly for \tikzmarkereastdefault.
      \path let \p1=(tikz marker west), \p2=(current bounding box.west), \n1={\x1-\x2} in \pgfextra{\xdef\myadjustwest{\n1}} ;

This calculates the difference between the x part of the (tikz marker west) coordinate and the x part of the coordinate at the left of the current bounding box. Typically, this will be 0pt. But, if \tikzmarkerwest has been called, the distance of the marker node from the left of the current bounding box may be non-zero. (Indeed, if the macro has been called, this will presumably be the case as that's the only reason to use the macro.)
Now we do the same for (tikz marker east) and the right of the current bounding box.
      \path let \p1=(tikz marker east), \p2=(current bounding box.east), \n1={\x2-\x1} in \pgfextra{\xdef\myadjusteast{\n1}} ;
    },
  },

  every picture/.style={mark out},

This line applies the mark out style to all TikZ pictures. If this causes problems, remove it and add mark out to the pictures you want it for.
}
\newlength\myadjustwest
\newlength\myadjusteast

Make sure \myadjustwest and \myadjusteast are available regardless.
\AfterEndEnvironment{tikzpicture}{%
  \captionsetup{margin={\myadjustwest,\myadjusteast}}%
}{\typeout{OK!}}{\typeout{Oh, no!}}

This adapts the end of all tikzpicture environments to modify the \caption correctly. You should substitute meaningful messages for yourself in place of OK! and Oh, no!, if you use this.
The following example set illustrates the basic possibilities. If you want to place the caption relative to, say, a shaded rectangle, you can't (at all easily) shade part of it, then another part and then another part, marking the bounding box in between stages appropriately. Therefore, for this case, we use the optional arguments for \tikzmarkerwest and/or \tikzmarkereast, to get positions for captions focusing on the red end of the visible light spectrum, the blue end and an in-between bit left-of-centre.
For the reds ...
...
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.4] (r);
      \tikzmarkereast(r)
...

For the blues ...
...
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.6] (b);
      \tikzmarkerwest(b)
...

For the innards ...
...
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.1] (a) coordinate [pos=.5] (b);
      \tikzmarkereast(b)
      \tikzmarkerwest(a)
...

Complete code:
% arara: pdflatex
\pdfminorversion=7
% ateb: https://tex.stackexchange.com/a/377652/ addaswyd o gwestiwn d125q: https://tex.stackexchange.com/q/377476/
\documentclass[a4paper]{scrartcl}
\usepackage{mathtools,amssymb}
\usepackage[compatibility=false]{caption}
\usepackage[list]{subcaption}
\usepackage{fancyvrb,tikz,etoolbox,xparse}
\usetikzlibrary{patterns, fit, positioning, calc}
\usepackage[active, tightpage, floats, displaymath]{preview}
\mathtoolsset{%
  mathic=true
}
\NewDocumentCommand \tikzmarkerwest { D () {current bounding box.west} } {%
  \coordinate (tikz marker west) at (#1);
  \let\tikzmarkerwestdefault\relax
}
\NewDocumentCommand \tikzmarkerwestdefault {} {}
\NewDocumentCommand \tikzmarkereast { D () {current bounding box.east} } {%
  \coordinate (tikz marker east) at (#1);
  \let\tikzmarkereastdefault\relax
}
\NewDocumentCommand \tikzmarkereastdefault {} {}
\tikzset{%
  mark out/.style={%
    execute at begin picture={%
      \RenewDocumentCommand \tikzmarkerwestdefault {}
      {%
        \coordinate (tikz marker west) at (current bounding box.west);
      }%
      \RenewDocumentCommand \tikzmarkereastdefault {}
      {%
        \coordinate (tikz marker east) at (current bounding box.east);
      }%
    },
    execute at end picture={%
      \tikzmarkerwestdefault
      \tikzmarkereastdefault
      \path let \p1=(tikz marker west), \p2=(current bounding box.west), \n1={\x1-\x2} in \pgfextra{\xdef\myadjustwest{\n1}} ;
      \path let \p1=(tikz marker east), \p2=(current bounding box.east), \n1={\x2-\x1} in \pgfextra{\xdef\myadjusteast{\n1}} ;
    },
  },
  every picture/.style={mark out},
}
\newlength\myadjustwest
\newlength\myadjusteast
\AfterEndEnvironment{tikzpicture}{%
  \captionsetup{margin={\myadjustwest,\myadjusteast}}%
}{\typeout{OK!}}{\typeout{Oh, no!}}

% for the examples
\definecolor{wave start}{wave}{380}
\definecolor{wave violet}{wave}{400}
\definecolor{wave indigo}{wave}{445}
\definecolor{wave blue}{wave}{475}
\definecolor{wave green}{wave}{510}
\definecolor{wave yellow}{wave}{570}
\definecolor{wave orange}{wave}{590}
\definecolor{wave red}{wave}{650}
\definecolor{wave end}{wave}{780}
\pgfdeclareverticalshading{wave}{100bp}{% manual 1088; xcolor manual; does not work to use wave model directly (?); https://science-edu.larc.nasa.gov/EDDOCS/Wavelengths_for_Colors.html
  color(0bp)=(wave start);
  color(25bp)=(wave start);
  color(27bp)=(wave violet);% 400 nm
  color(33bp)=(wave indigo);% 445nm
  color(37bp)=(wave blue);% 475nm
  color(41bp)=(wave green);% 510nm
  color(49bp)=(wave yellow);% 570nm
  color(51bp)=(wave orange);% 590nm
  color(59bp)=(wave red);% 650nm
  color(75bp)=(wave end);% 780nm
  color(100bp)=(wave end)
}
\begin{document}
\begin{figure}
  \centering
  \begin{subfigure}[b]{0.60\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, label=below:the] (the) {\(\mathbf{W}\)};
      \node[draw, right=of the, label=below:cat] (cat) {\(\mathbf{W}\)};
      \node[draw, right=of cat, label=below:sat] (sat) {\(\mathbf{W}\)};
      \node[draw, fit=(the.west) (the.east), pattern=vertical lines, above=of the] (in_the) {};
      \node[draw, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in_cat) {};
      \node[draw, fit=(sat.west) (sat.east), pattern=vertical lines, above=of sat] (in_sat) {};
      \node[draw, fit={($(cat.west) + (-8pt,0pt)$) ($(cat.east) + (8pt,0pt)$)}, pattern=vertical lines, above=2cm of cat] (in) {};
      \node[draw, above=of in, label=above:mat] (out) {\(\mathbf{b}\), \(\mathbf{U}\)};
      \foreach \word in {the, cat, sat}{%
        \draw[->] (\word) -- (in_\word);
        \draw[->] (in_\word) -- (in);
      }
      \draw[->] (in) -- (out);
      \tikzmarkerwest
      \node[left=of the, outer sep=0] (embed) {embed};
      \node[above=2cm of embed, outer sep=0] (concatenate) {concatenate};
      \node[above=1cm of concatenate, outer sep=0] {softmax};
    \end{tikzpicture}
    \caption{CBOW model}\label{fig:cbow}
  \end{subfigure}
  \begin{subfigure}[b]{0.35\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, label=below:cat] (cat) {\(\mathbf{W}\)};
      \node[draw, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in) {};
      \node[draw, above=2cmof in, label=above:on] (on) {\(\mathbf{b}\), \(\mathbf{U}\)};
      \node[draw, left=of on, label=above:sat] (sat) {\(\mathbf{b}\), \(\mathbf{U}\)};
      \node[draw, right=of on, label=above:the] (the) {\(\mathbf{b}\), \(\mathbf{U}\)};
      \draw[->] (cat) -- (in);
      \foreach \word in {sat, on, the}{%
        \draw[->] (in) -- (\word);
      }
    \end{tikzpicture}
    \caption{Skip\=/gram model}\label{fig:sg}
  \end{subfigure}
  \caption{\protect\Verb+Word2Vec+ with vocabulary size \(V\), context size \(C\), and embedding size \(N\)}
\end{figure}

\begin{figure}
  \centering
  \begin{subfigure}{.33\linewidth}
    \centering
    \begin{tikzpicture}
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.4] (r);
      \tikzmarkereast(r)
    \end{tikzpicture}
    \caption{Reds.}
  \end{subfigure}\hfill
  \begin{subfigure}{.33\linewidth}
    \centering
    \begin{tikzpicture}
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.6] (b);
      \tikzmarkerwest(b)
    \end{tikzpicture}
    \caption{Blues.}
  \end{subfigure}\hfill
  \begin{subfigure}{.33\linewidth}
    \centering
    \begin{tikzpicture}
      \shade [shading=wave, shading angle=90] (0,0) rectangle ++(\linewidth,1) coordinate [pos=.1] (a) coordinate [pos=.5] (b);
      \tikzmarkereast(b)
      \tikzmarkerwest(a)
    \end{tikzpicture}
    \caption{Innards.}
  \end{subfigure}\par
  \caption{Main figure}
\end{figure}
\end{document}

A: First, I did not edit my first answer, because it might be useful for some people as it is.
This new answer calculates the margins for the caption. For this there are some macros in the preamble. And then three commands have to be placed. They are all without any arguments.
In the picture the main part (i.e. the part under which the caption should be centered) must be drawn first. Then \pgfremembermainx has to be inserted. It set coordinates to remember the outermost x-positions so far. After that the parts overlapping the main part to the left and the right have to be drawn.
Right at the end, just before \end{tikzpicture}, the command \pgfgetoverlap must be placed. It calculates the overlap (relative to the main part) to both sides and stores them in the dimen registers \overlapleft and \overlapright. Both are set global, so they can be used after the tikzpicture. Note: everything drawn after \pgfgetoverlap would not be taken into account for calculating the overlap.
And finally between the tikzpicture and the caption the margins are set with \captionsetmargins. Its effect is local since it's in the subfigure environment. It should not be used outside the environment, because it would set the margins for all captions since the optional argument ([subfigure]) can't be used here. Of course this only works after the picture, because the overlaps are not known before it.
\documentclass[a4paper]{scrartcl}

\usepackage{mathtools}
\usepackage{amssymb}

\usepackage[compatibility=false]{caption}
\usepackage[list]{subcaption}

\usepackage{fancyvrb}

\usepackage{tikz}
\usetikzlibrary{patterns, fit, positioning, calc, shapes.arrows}

\usepackage[active, tightpage, floats, displaymath]{preview}

\mathtoolsset{%
  mathic=true
}

% Vectors and matrices
\renewcommand*{\vec}[1]{\mathbf{#1}}
\newcommand{\mat}[1]{\mathbf{#1}}
\newcommand{\trans}{\intercal}

% Operators
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator*{\argmax}{arg\,max}

%---------------------------------------------------------------------
% code for automatic setting of caption margins
\makeatletter
\newdimen\overlapleft
\newdimen\overlapright

\newcommand{\pgfremembermainx}{%
    \coordinate (main west) at (current bounding box.west);
    \coordinate (main east) at (current bounding box.east);
}
\newcommand{\pgfgetoverlap}{%
    \pgfextractx{\@tempdima}{%
        \pgfpointdiff{\pgfpointanchor{current bounding box}{west}}%
                     {\pgfpointanchor{main west}{center}}%
    }%
    \global\overlapleft=\@tempdima
    \pgfextractx{\@tempdima}{%
        \pgfpointdiff{\pgfpointanchor{main east}{center}}%
                     {\pgfpointanchor{current bounding box}{east}}%
    }%
    \global\overlapright=\@tempdima
}
\newcommand{\captionsetmargins}{%
    % no additional calculation required here
    \captionsetup{margin={\overlapleft,\overlapright}}%
}
\makeatother
%---------------------------------------------------------------------

\begin{document}
\begin{figure}
  \centering
% not needed here
%  \captionsetup[subfigure]{margin={2.5cm, 0cm}}
  \begin{subfigure}[b]{0.60\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:the] (the) {\(\mat W\)};
      \node[draw, rectangle, right=of the, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, right=of cat, label=below:sat] (sat) {\(\mat W\)};

      \node[draw, rectangle, fit=(the.west) (the.east), pattern=vertical lines, above=of the] (in_the) {};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in_cat) {};
      \node[draw, rectangle, fit=(sat.west) (sat.east), pattern=vertical lines, above=of sat] (in_sat) {};

      \node[draw, rectangle, fit={($(cat.west) + (-8pt,0pt)$) ($(cat.east) + (8pt,0pt)$)}, pattern=vertical lines, above=2cm of cat] (in) {};
      \node[draw, rectangle, above=of in, label=above:mat] (out) {\(\vec b\), \(\mat U\)};

      % remember the x-coordinates of the main part
      \pgfremembermainx
      % \useasboundingbox was here in the first answer

      % not taken into account for the picture size
      \node[left=of the, outer sep=0] (embed) {embed};
      \node[above=2cm of embed, outer sep=0] (concatenate) {concatenate};
      \node[above=1cm of concatenate, outer sep=0] {softmax};

      % this belongs to the main part, but it doesn't increase its size
      % otherwise it must be moved before \pgfremembermainx
      \foreach \word in {the, cat, sat}{%
        \draw[->] (\word) -- (in_\word);
        \draw[->] (in_\word) -- (in);
      }

      \draw[->] (in) -- (out);

      %for testing, if it also works with overlap to the right
      %\node[draw, right= of sat] {t};

      % must be right before \end{tikzpicture}, everything after it
      % would not be taken into account for the calculation of the overlap
      \pgfgetoverlap
    \end{tikzpicture}
    % setting the caption margins
    % moving this here sets the margin locally (only for the current environment)
    % and here the computed values for the margins are known
    \captionsetmargins
    \caption{CBOW model}\label{fig:cbow}
  \end{subfigure}
% no longer needed
%  \captionsetup[subfigure]{margin={0cm,0cm}}
  \begin{subfigure}[b]{0.35\textwidth}
    \centering
    \begin{tikzpicture}[>=latex, shorten >=2pt, shorten <=2pt]
      \node[draw, rectangle, label=below:cat] (cat) {\(\mat W\)};
      \node[draw, rectangle, fit=(cat.west) (cat.east), pattern=vertical lines, above=of cat] (in) {};
      \node[draw, rectangle, above=2cmof in, label=above:on] (on) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, left=of on, label=above:sat] (sat) {\(\vec b\), \(\mat U\)};
      \node[draw, rectangle, right=of on, label=above:the] (the) {\(\vec b\), \(\mat U\)};

      \draw[->] (cat) -- (in);
      \foreach \word in {sat, on, the}{%
        \draw[->] (in) -- (\word);
      }
    \end{tikzpicture}
    \caption{Skip\=/gram model}\label{fig:sg}
  \end{subfigure}
  \caption{\protect\Verb+Word2Vec+ with vocabulary size \(V\), context
    size \(C\), and embedding size \(N\)}
\end{figure}
\end{document}