#include <bits/stdc++.h>
using namespace std;
const int maxn = 510;
const int Mod = 1e9 + 7;
int n, m, S;
char s[maxn];
int ri() {
  int s = 0, w = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') w = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    s = (s << 1) + (s << 3) + (c ^ 48);
    c = getchar();
  }
  return s * w;
}
int las, cnt, fa[maxn];
char c[maxn];
int zzm[maxn][6], f[maxn][(1 << 16) + 10];
void FWT_OR(int *A, int opt) {
  for (int mid = 1; mid < S; mid <<= 1) {
    for (int j = 0; j < S; j += (mid << 1)) {
      for (int k = 0; k < mid; k++) {
        (A[j + k + mid] += (A[j + k] * opt + Mod) % Mod) %= Mod;
      }
    }
  }
}
void FWT_AND(int *A, int opt) {
  for (int mid = 1; mid < S; mid <<= 1) {
    for (int j = 0; j < S; j += (mid << 1)) {
      for (int k = 0; k < mid; k++) {
        (A[j + k] += (A[j + mid + k] * opt + Mod) % Mod) %= Mod;
      }
    }
  }
}
vector<int> G[maxn];
int tmpa[(1 << 16) + 10], tmpb[(1 << 16) + 10];
void OR(int x) {
  int a = G[x][0], b = G[x][1];
  memcpy(tmpa, f[a], sizeof f[a]);
  memcpy(tmpb, f[b], sizeof f[b]);
  FWT_OR(tmpa, 1);
  FWT_OR(tmpb, 1);
  for (int i = 0; i < S; i++) tmpa[i] = 1ll * tmpa[i] * tmpb[i] % Mod;
  FWT_OR(tmpa, -1);
  for (int i = 0; i < S; i++) {
    (f[x][i] += tmpa[i]) %= Mod;
  }
}
void AND(int x) {
  int a = G[x][0], b = G[x][1];
  memcpy(tmpa, f[a], sizeof f[a]);
  memcpy(tmpb, f[b], sizeof f[b]);
  FWT_AND(tmpa, 1);
  FWT_AND(tmpb, 1);
  for (int i = 0; i < S; i++) tmpa[i] = 1ll * tmpa[i] * tmpb[i] % Mod;
  FWT_AND(tmpa, -1);
  for (int i = 0; i < S; i++) {
    (f[x][i] += tmpa[i]) %= Mod;
  }
}
void dfs(int x) {
  if (G[x].size() == 0) {
    if (c[x] == '?') {
      for (int tmp = 0; tmp < 4; tmp++) {
        int tmps = 0;
        for (int i = 0; i < m; i++) tmps += (zzm[i][tmp] << i);
        (f[x][tmps] += 1) %= Mod;
        tmps = 0;
        for (int i = 0; i < m; i++) tmps += ((!zzm[i][tmp]) << i);
        (f[x][tmps] += 1) %= Mod;
      }
      return;
    }
    if ('A' <= c[x] && c[x] <= 'D') {
      int tmps = 0;
      for (int i = 0; i < m; i++) tmps += (zzm[i][c[x] - 'A'] << i);
      (f[x][tmps] += 1) %= Mod;
    }
    if ('a' <= c[x] && c[x] <= 'd') {
      int tmps = 0;
      for (int i = 0; i < m; i++) tmps += ((!zzm[i][c[x] - 'a']) << i);
      (f[x][tmps] += 1) %= Mod;
    }
    return;
  }
  for (int v : G[x]) dfs(v);
  if (c[x] != '&') OR(x);
  if (c[x] != '|') AND(x);
}
signed main() {
  scanf("%s", s + 1);
  n = strlen(s + 1);
  m = ri();
  S = (1 << m);
  cnt = las = 1;
  for (int i = 1; i <= n; i++) {
    if (s[i] == '(')
      G[las].push_back(++cnt), fa[cnt] = las, las = cnt;
    else if (s[i] == ')')
      las = fa[las];
    else
      c[las] = s[i];
  }
  for (int i = 0; i <= m - 1; i++)
    for (int j = 0; j <= 4; j++) zzm[i][j] = ri();
  dfs(1);
  int res = 0;
  for (int i = 0; i < m; i++) res = res + (zzm[i][4] << i);
  printf("%d\n", f[1][res] % Mod);
  return 0;
}
