How to input text from a file and output to another

Question: I am trying to take the string text from a text file input.txt, and line by line output that same text to an output file output.txt
I have tried this:
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
    FileReader FR = new FileReader("C:\\FileLocation\\inputhashes.txt");
    BufferedReader BR = new BufferedReader(FR);
    PrintWriter PW = new PrintWriter("C:\\FileLocation\\outputtest.txt");
    for (int i = 0; i < 8 ; i++) {
        PW.println(BR.readLine());
    }
}

However this does
not work and I am unsure why, the outputtest.txt file is completely empty.
When I try
 System.out.println(BR.readLine());

The console displays the correct results that I expect.
Comment: Try closing your files.
Comment: Also, you should watch your code formatting.  I've fixed it for you; see how much easier to read it is?
Comment: Ok thanks, ive tried that and still no luck
Comment: @kquinn, Please post what exactly you've tried.
Answer: The following code copy the content from one file to another, as mentioned by @Robert Harvey you may not be closing your files properly.
        BufferedReader reader = Files.newBufferedReader(Paths.get("C:\\Users\\ngueno\\Desktop\\File 1.txt"));
        BufferedWriter writer = Files.newBufferedWriter(Paths.get("C:\\Users\\ngueno\\Desktop\\File 2.txt"), StandardOpenOption.WRITE);

        String line;

        while( (line = reader.readLine()) != null ) {
            writer.write(line);
        }

        reader.close();
        writer.flush();
        writer.close();

Answer: File inputFile = new File("inputFilePath");
File outputFile = new File("outputFilePath");

String output;
StringBuilder stringBuilder = new StringBuilder();

try (BufferedReader buffRead = new BufferedReader(new FileReader(inputFile))) {

    String line;
    while ( (line = buffRead.readLine()) != null) {
        stringBuilder.append(line + "\n");
    }
    output = stringBuilder.toString();
} catch (Exception e) {
    // handle exception
}

try (BufferedWriter buffWrite = new BufferedWriter(new FileWriter(outputFile))) {
    buffWrite.write(output);
} catch (Exception e) {
    // handle exception
}


Mark New Nodes in Views via Template

Question: I have a portfolio view that displays all items in the portfolio. The fields are set via template so I do not have access to the fields area in views to select the parameter there, I have to do it within my node template.
The issue is I can't figure out what code to stick in there to display the "New" tag if the visitor has not yet viewed the node.
This is the code I have in the template:

<a href="<?php print $node_url?>"><?php print $title;?>

  <?php print strip_tags(render($content['field_portfolio_categories'])); ?>

I have googled and found the info here (https://api.drupal.org/api/drupal/includes!theme.inc/function/theme_mark/7) but I just can't figure out how to translate it to what code I put in my actual template file to make it happen.
Thank you so much for your help.

Thank you for your answer!  I am primarily a themer and php just is not my strong suit.
I have changed my code to be:

<a href="<?php print $node_url?>"><?php print $title;?>

  <?php print strip_tags(render($content['field_portfolio_categories'])); ?>
  <?php
    if (node_last_viewed($node->nid) > 0) {
       print '' .  theme('mark', array('type' => MARK_NEW)) . '';
    }
  ?>

This code displays the "new" text, but only if I am logged in as the administrator and it displays on all items, not just ones I have not visited yet.  Any ideas?
Answer: <?php print theme('mark', array('type' => node_mark($node->nid, $node->changed))); ?>

this is how it is done on the content overview page. give it a try, it will display read for anonymous users' - probably ..,
here's the code from node_mark, where node_last_viewed is used:
function node_mark($nid, $timestamp) {
  global $user;
  $cache = &drupal_static(__FUNCTION__, array());

  if (!$user->uid) {
    return MARK_READ;
  }
  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;
}

so for you maybe this could be used (statistics module needs to be enabled)
 <?php
      if (node_last_viewed($node->nid) == 0) {
        print '' .  theme('mark', array('type' => MARK_NEW)) . '';
      }

best to call this theme function (and any logic) in the preprocess method, and use a variable in the template ..
Comment: I edited my question above.
Comment: Ok, I now get the "new" text, but only if I am logged in as an admin and it is showing new for all items, even if I have visited the node or not.  Any ideas?
Comment: this only works for logged in users, and it did not work because i did the if-check wrong .. node_last_viewed returns a timestamp or 0 .. - i edited the code above
Comment: if you need anonymous hits counted - give [nodeviewcount](https://www.drupal.org/project/nodeviewcount) a try

Mark New Nodes in Views via Template


How to display a page of a taxonomy term differently from the default view?

Question: I activated the "Taxonomy term" view to customize the time display. I want to display some terms from another differently. How to do this ?
I have cloned my view "Taxonomy term" and applied to it a criterion of filtering by type of content displaying only my "sujet". Then I customized its display.
The problem, when the cloned view is enabled, all terms show a blank page.
Answer: Maybe you should check Taxonomy Views Integrator

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice


./configure doesn't work on python 3.8.2 on windows

Question: I am trying to execute the code:
<code>./configure \
        --prefix "$(dirname $(pwd))" \
        --with-openssl=$(openssl version -d | sed  -r 's/OPENSSLDIR: "([^"]*)"/\1/') \
    && make && make install
popd
</code>
this error is recived:
<code>  File "<ipython-input-7-f69304efaff4>", line 1
    ./configure
    ^
SyntaxError: invalid syntax
</code>
Does anyone know how to fix it?
Answer: This code should be executed in bash shell, not python
Comment: when i try to execute it on the shell the error "'.' is not recognized as an internal or external command,
operable program or batch file." is shown
Comment: there should be a file named configure, and probably you are using Windows and command is for UNIX
Comment: Do you know any equivalent to windows?
Answer: It should be executed in bash shell but as i am using windows it was not possible.
In this code i was trying to install FreeTDS and after download the stable realease and the binaries for windows I was able to install it by using the windows powershell to run the .ps1 file


Follow up on example computation of $\mathrm{Tor}_n$

Question: I have a follow up question on this question of mine:
I can't reconstruct how I got $\operatorname{Im}{d_1^\ast} = 0$ from the following chain:
$$0 \to \mathbb Z \otimes_{\mathbb Z} (\mathbb Z / 2 \mathbb Z) \xrightarrow{d_1^\ast = \cdot 284 \otimes id} \mathbb Z \otimes_{\mathbb Z} (\mathbb Z / 2 \mathbb Z) \xrightarrow{d_0^\ast=0} 0$$
Now I think $\operatorname{Im}{d_1^\ast}  = 284 \mathbb Z \otimes N$ and $\operatorname{Ker}{d_0^\ast}  = \mathbb Z \otimes (\mathbb Z / 2 \mathbb Z)$.
And then $Tor^1 (\mathbb Z / 284 \mathbb Z, \mathbb Z / 2 \mathbb Z) = (\mathbb Z \otimes \mathbb Z / 2 \mathbb Z) / (284 \mathbb Z \otimes \mathbb Z / 2 \mathbb Z) $.

Is
$$\operatorname{Im}{d_1^\ast}  = 284 \mathbb Z \otimes (\mathbb Z / 2 \mathbb Z) $$
 and
$$\operatorname{Ker}{d_0^\ast}  = \mathbb Z \otimes (\mathbb Z / 2 \mathbb Z) \cong \mathbb Z / 2 \mathbb Z$$ correct ?
And what does $(A \otimes B) / (C \otimes D)$ look like? Is it isomorphic to $(A/C) \otimes (B/D)$? Thanks for your help.
Comment: Basically, do not use $C \otimes D$ to mean a subgroup of $A \otimes B$ even if $C \leq A$ and $D \leq B$. Even if enough modules are flat that you could get a monomorphism, it can be dangerous to think like this. For instance, what is $2\mathbb{Z} \otimes \mathbb{Z}/2\mathbb{Z}$? As a tensor product, it is an abelian group of order 2. As a subgroup of $\mathbb{Z} \otimes \mathbb{Z}/2\mathbb{Z}$ it has order 1.
Comment: Dear Matt, I don't understand your remark about needing to do other things before you simplify.  When computing Tor, you take a free resolution of one of your modules, which involves terms like $\mathbb Z^n$.  You then tensor with your second module, say $N$.  The very first step is to replace all the expressions $\mathbb Z^n \otimes_{\mathbb Z} N$ by $N^n$; so in your case you certainly will want to replace all that $\mathbb Z\otimes_{\mathbb Z} \mathbb Z/2$'s by $\mathbb Z/2$'s.  Once you have the terms of the complex computed, you will then want to describe the maps, and then compute ...
Comment: Dear Matt, The only tensor products you seem to have in sight are of the form $\mathbb Z\otimes N$.  Since I imagine that the tensor product is also taking place over $N$, these are canonically isomorphic to $N$, and so can certainly be simplified.  Regards,
Comment: ... their kernels and images explicitly; not in terms of objects expressed in convoluted terms by various unsimplified tensor products.  Regards,
Comment: Your last paragraph might not be a good idea to consider. There are several problems with it. If you keep track of the maps, then things are better.
Comment: @JackSchmidt Thank you, but I do not understand your last sentence, I'm sorry. What do you mean by keeping track of the maps?
Comment: @JackSchmidt Oh, ok, right. So I guess, if I get $(A \otimes B) / (C \otimes D)$ for $Tor^n$ then I should just leave it as is and cannot simplify it any further. And what about my new results for $Im$ and $Ker$? Did I manage to get it right?
Comment: Dear @MattE, I'm sorry, I forgot to replace $N$ with $\mathbb Z / 2 \mathbb Z$. I have done so now.
Comment: Dear Matt, But you are still writing things like $\mathbb Z\otimes_{\mathbb Z} (\mathbb Z/2\mathbb Z)$ and $(\mathbb Z/248 \mathbb Z)\otimes_{\mathbb Z} (\mathbb Z/2\mathbb Z)$, without simplifying them.  It seems that you should review how to compute tensor products before going too much further in trying to compute higher Tors.  Regards,
Comment: Dear @MattE, well I know that $(\mathbb Z / n \mathbb Z) \otimes (\mathbb Z / m \mathbb Z) \cong \mathbb Z / \mathrm{gcd}(n,m) \mathbb Z$. Do I really have to simplify all of them, always? (using this knowledge, $\mathbb Z\otimes_{\mathbb Z} (\mathbb Z/2\mathbb Z) \cong \mathbb Z / 2 \mathbb Z$ and $(\mathbb Z/248 \mathbb Z)\otimes_{\mathbb Z} (\mathbb Z/2\mathbb Z) \cong \mathbb Z/2\mathbb Z$)
Comment: In any case, before I simplify I first need to know whether I got $Ker$ and $Im$ right this time.
Comment: Actually, I'm quite sure they are correct.
Answer: Your description of the image is not correct.
You would do well to heed Jack Schmidt's warning in the comments: although
$248\mathbb Z$ is a submodule of $\mathbb Z$, this is no longer true once you
tensor with $\mathbb Z/2$.  So your description of the image is not only incorrect, but the candidate image you have written down is not a subobject of the target.
I think you would also do well to follow my advice in the comments above, and to simplify the various tensor products in your complex , and then describe the maps in terms of the simplified objects, before you try to
 compute its cohomology.
Comment: @MattN : Dear Matt, Your chain complex in the comments is correct, and so is your computation of $Tor_1$.  This is right way to go --- simplify everything in sight, at which point you can hope that the relevant images and kernels are easy to compute, as they were in this example.  [Sorry, I wrote cohomology rather than homology just out of habit; I'm used to thinking of things as cochain complexes.]  Best wishes,
Comment: Dear MattE, thank you so much for your help and patience. I have tried again, here is what I did:

(The ring over which we tensor is $\mathbb Z$.) I start with
$$ 0 \to \mathbb Z \otimes \mathbb Z / 2 \mathbb Z \to \mathbb Z \otimes \mathbb Z / 2 \mathbb Z \to 0$$

Then I used $R \otimes_R M \cong M$ to get
$$ 0 \to \mathbb Z / 2 \mathbb Z \to \mathbb Z / 2 \mathbb Z \to 0$$

Then I used the isomorphism $R \otimes_R M \cong M$, $m \mapsto 1 \otimes m$, to compute the new maps:
$$ m \in \mathbb Z / 2 \mathbb Z \mapsto 1 \otimes z \mapsto 284 \otimes z \mapsto 284z \equiv_2 0$$
Comment: So that the new chain complex is
$$ 0 \to \mathbb Z / 2 \mathbb Z \xrightarrow{0} \mathbb Z / 2 \mathbb Z \to 0$$
Comment: From which I compute the homology (I thought it was homology groups, but maybe it's cohomology?) as
$$ Tor^1 (M,N) =  \mathrm{Ker}(0) / \mathrm{Im}(0)  = \mathrm{Ker}(0) = \mathbb Z / 2 \mathbb Z$$
Comment: Is this correct? Again, I apologise for the typos in my OP yesterday, it was a long day.
Comment: Dear @MattE, thank you very much for checking my computation and teaching me how to compute $\mathrm{Tor}$.


What is the expected number of times you need to flip a coin before you see 2 heads? The heads do not need to be in a row

Question: My attempt:
The 2nd head must appear last in the sequence of k flips. Therefore the first head can appear in any of the first k-1 flips. The number of ways the first head appearing in the first k-1 flips is ${k-1\choose 1} = (k-1)$. Each sequence has a $ p^{k-1} $ chance of appearing
$$P(X=k)=(k-1)p^{k-1}p = (k-1)p^k = (k-1)(.5)^k$$
Now when I try to calculate the expected value:
$E(X) = \sum\limits_{x = 1}^{\infty}x(x-1)(.5)^x\ $.
After entering some large values of x, it seems $E(X) = 4$
Is this correct?
Comment: Hint: how long should it take to see the first head?
Comment: If you are at all interested in probability, it would be a good idea to get some practice in summing series like the one for $E[X]$ that you have shown, and yes, it can be _proved_ that your sum for $E[X]$ does have value $4$ without resorting to "entering large values of $x$" whatever that means.
Comment: Have a look at this answer https://math.stackexchange.com/a/102683/620244
Answer: Your answer is correct, but your derivation does not quite get there.  Suppose we let $K_1$ be the number of flips until the first head, $K_2$ be the number of additional flips until the next head, and so on.  Then we have $K_1,K_2,K_3,... \sim \text{IID Geom}(p)$ and so the number of flips until the $n$th head is:
$$S_n = \sum_{i=1}^n K_i \sim \text{NegBin}(n,p).$$
The full distribution of this quantity can be found easily enough, but the expectation is even simpler:
$$\mathbb{E}(S_n) = \mathbb{E} \bigg(  \sum_{i=1}^n K_i \bigg) =  \sum_{i=1}^n \mathbb{E}(K_i) =  \sum_{i=1}^n \frac{1}{p} = \frac{n}{p}.$$
In your case you have assumed that $p = 1/2$ and you want to find the expected number of flips until the second head, which is $\mathbb{E}(S_2) = 2 / p = 4.$


Pessimistic locking is not working properly with reload

Question: Pessimistic locking is not working properly with reload (used in the test cases). with_lock and reload is not working correctly together and test cases are getting failed. If I removed the with_lock then test cases work fine.
def method_name1
  self.with_lock do
    attributes["amount_used"] = get_total_amount_used
    attributes["updated_at"] = Time.now.utc
    Product.where(:id => self.id).update_all(attributes)
  end
end

I have written unit test cases using FactoryGirl. It calls the method_name1 which recalculate the total after the used amount. If you check the first Test case 1: total = 600 and amount_used = -200 (-ve means reducing), now total should be 400.00. Similarly for "Test case 2", After running "Test case 1" total is 400.00. amount_used = 200 (+ve means add), total should be 600.00. But Test Case 2 is saying 800.00.
context 'description' do
  before(:each) do
    @product.total = 600
    @product.method_name1
  end

  it 'is updated automatically if valid' do
    @product.amount_used = -200
    @product.save
    @product.reload
    should eq('400.0')       #Working
  end

  it 'is not changed if invalid' do
    @product.amount_used = 200
    @product.save
    @product.reload
    should eq('600.0')      #Not Working
  end
end

Error For Test Case 2:
Failure/Error: should eq('600.0')
   expected: "600.0"
        got: "800.0"

   (compared using ==)

Answer: Test result 800 is the correct answer.
before(:each) do
  @product.total = 600
  @product.method_name1
end

before(:each) means this piece of code will be executed before running each example so 600 + 200 is 800. If you want it to run only once then you have to use before(:all) then this piece of code will run only once before running both examples.
You can see more on this in the official documentation.
Comment: In addition I'd like to say that the order of your tests should not matter. Always build your tests to be independent of each other.


group differences means and standard deviation

Question: The mean and standard deviation of the mass of owls in group 1 is 3.124(3.806) kg. The mean and standard deviation of the mass of owls in group2 is 6.295(4.015) kg.
Can I say that although the mean 6.295 vs 3.124 indicates a difference in mass between these two groups, large standard deviations indicate that this difference between groups may not be that significant?
Answer: Of course, statistical significance depends on sample
sizes, which you do not provide. How many owls in each group?
If sample sizes are as large as $n_1 = n_2 = 50,$ then it seems the difference
in means is statistically significant at the 5% level.
I say "seems" because I show only one rough computation via simulation,
using your sample means and SDs as population means and SDs.
[But this is backed up by more careful computations, not shown.]
If you know sample sizes, as well as means, and standard deviations, then
you can use standard formulas to do a formal t test and get an
exact answer. [If you don't know the sample sizes,
maybe you can pretend they are both 30 and see what
happens.]
I recommend using a Welch 2-sample t test because I know of no reason to believe that the two populations have equal variances.
<code>set.seed(2021)
x1 = rnorm(50, 3.124, 3.806)
x2 = rnorm(50, 6.295, 4.015)
t.test(x1,x2)

        Welch Two Sample t-test

data:  x1 and x2
t = -2.0843, df = 94.492, p-value = 0.03983
alternative hypothesis:
 true difference in means is not equal to 0
95 percent confidence interval:
 -3.21332540 -0.07811769
sample estimates:
mean of x mean of y
 3.184425  4.830147
</code>


How to read multiple lines of string from stdin in C?

Question: I am a novice in C programming. Suppose I want to read multiple lines of string from stdin. How can I keep reading until a line only containing EOL?
example of input
1+2\n
1+2+3\n
1+2+3+4\n
\n (stop at this line)

It seems that when I hit enter(EOL) directly, scanf won't execute until something other than just EOL has been entered. How can I solve that problem?
I'll be really grateful if someone can help me with this. Thank you.
Comment: Use `fgets`. `scanf` is a bad choice in many cases.
Comment: @ShellCode If post was tagged posix, then `getline()` is a viable choice, else we could suggest any implementation specific solution.
Comment: Use fgetc.  When you see two consecutive `\n`, stop.
Comment: Personally I would use [getline(3)](https://man7.org/linux/man-pages/man3/getline.3.html) and stop when it returns 1.
Comment: @ShellCode `getline()` in not part of the standard C library.
Comment: @chux-ReinstateMonica and what's wrong with it not being part of the standard  C lib ? It's in the POSIX standard
Answer: If you want to learn C, you should avoid scanf.  The only use cases where scanf actually makes sense are in problems for which C is the wrong language.  Time spent learning the foibles of scanf is not well spent, and it doesn't really teach you much about C.  For something like this, just read one character at a time and stop when you see two consecutive newlines.  Something like:
#include <stdio.h>

int
main(void)
{
        char buf[1024];
        int c;

        char *s = buf;

        while( (c = fgetc(stdin)) != EOF && s < buf + sizeof buf - 1 ){
                if( c == '\n' && s > buf && s[-1] == '\n' ){
                        ungetc(c, stdin);
                        break;
                }
                *s++ = c;
        }
        *s = '\0';
        printf("string entered: %s", buf);
        return 0;
}

Comment: When `'\n'` is the first character read, code does not stop.
Comment: I'm not convinced that the could should terminate when the first character is a newline, but that's appropriate as an exercise left for the reader. :)
Comment: Agreed - some detail left out of OP's post.
Answer:
to read multiple lines of string from stdin. How can I keep reading until a line only containing EOL?

Keep track of when reading the beginning of the line.  If a '\n' is read at the beginning, stop
getchar() approach:
bool beginning = true;
int ch;
while ((ch = getchar()) != EOF) {
  if (beginning) {
    if (ch == '\n') break;
  }
  // Do what ever you want with `ch`
  beginning = ch == '\n';
}

fgets() approach - needs more code to handle lines longer than N
#define N 1024
char buf[N+1];
while (fgets(buf, sizeof buf, stdin) && buf[0] != '\n') {
  ; // Do something with buf
}

Answer: If you need to read one character at a time then you can with either getchar or fgetc depending upon whether or not you're reading from stdin or some other stream.
But you said you were reading strings, so I'm assuming fgets is more appropriate.
There are primarily two considerations:

maximum line length
whether or not to handle Windows versus non-Windows line endings

Even if you are a beginner--and I won't go into #2 here--you should know you can defend against it. I will at least say that if you compile on one platform and read from stdin from a redirected file from another platform, then you might have to write a defense.
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main (int argc, char *argv[]) {
    char buf[32];  // relatively small buf makes testing easier
    int lineContinuation = 0;
    // If no characters are read, then fgets returns NULL.
    while (fgets(buf, sizeof(buf), stdin) != NULL) {
       int l = strlen(buf); // No newline in buf if line len + newline exceeds sizeof(buf)
       if (buf[l-1] == '\n') {
          if (l == 1 && !lineContinuation) {
             break; // errno should indicate no error.
          }
          printf("send line ending (len=%d) to the parser\n", l);
          lineContinuation = 0;
       } else {
          lineContinuation = 1;
          printf("send line part (len=%d) to the parser\n", l);
       }
    }
    printf("check errno (%d) if you must handle unexpected end of input use cases\n", errno);
}


Choosing 80 from 100

Question: First question, i hope i follow the rules accordingly
I tried choosing 80 numbers from the ${{1,...,100}}$ set in two ways:
The first is 100 choose 80:
$$\binom{100}{80} = 535983370403809682970$$
The other way is as follows:
For each maximum value, choose all possible ways completing the set to 80 numbers (thus choosing the 79 numbers remaining from the set, ending in the highest number left):
$$\sum_{i=1}^{20}\binom{100-i}{79} = 535983370403809682969$$
What am i misssing? which set did i leave out?
Thank you.
Comment: You left off $\{1,2,\cdots, 80\}$.
Answer: You're missing $i = 21$ which corresponds to $80$ being the largest.

Choosing 80 from 100


ArrayAdapter Causes ClassCastException

Question: I have an AutoCompleteTextView inside a RelativeLayout inside a FrameLayout.  I want to populate the completion list using a class declared as follows:
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
 ...
 public AutoCompleteAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    data = new ArrayList<String>();
 }
 ...
}

I attached the adapter as follows:
AutoCompleteTextView tv = (AutoCompleteTextView) v.findViewById(R.id.editTextClient);
    AutoCompleteAdapter adapter = new AutoCompleteAdapter(getActivity(), R.layout.fragment_main_right);
    tv.setAdapter(adapter);

where R.layout.fragment_main_right is the enclosing FrameLayout mentioned above.  When I start to input text, I get a ClassCastException with the following message: "android.widget.FrameLayout cannot be cast to android.widget.TextView".  I understand this to mean that the second parameter in the ArrayAdapter constructor should be the id of something derived from a TextView.  All the examples show this parameter as being the enclosing layout.  Can someone clear up my confusion?
Comment: This should explain the reason for the cast exception http://stackoverflow.com/questions/9280965/arrayadapter-requires-the-resource-id-to-be-a-textview-xml-problems/9282069#9282069 . Also that layout that you pass to the adapter is the row layout and you probably don't want to use the layout containing the actual auto complete widget.
Comment: post and read your stacktrace.
Answer: For the second parameter in your adapter constructor, pass in android.R.layout.simple_dropdown_item_1line or android.R.layout.simple_list_item_1 instead.
The hint is given away that it expects a textview by the name of the parameter: textViewResoureceId.

ArrayAdapter Causes ClassCastException


Get column collection or charset type ( latin1_swedish_ci or utf8_general_ci )

Question: How to get column information with charset type.
Like : utf8_general_ci , latin1_swedish_ci , latin1_german1_ci , latin1_spanish_ci , utf8_german2_ci
I have tried :
1. DESC table_name
2. DESCRIBE table_name
3. SHOW COLUMNS FROM table_name
4. EXPLAIN table_name
Answer: You can get the information from information_schema.COLUMNS or using SHOW CREATE TABLE name


Increase supported devices android store

Question: Count of supported devices of my android app is only 380 instead of 4500+ ;
Here is part of my manifest
<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:glEsVersion="0x00030000" android:required="true" />
    <permission
        android:name="*.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="*.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />

Project build target is Google APIs 4.3 and added as library  google-play-service_lib.
So what's wrong and what to do to make Google play let app to be visible for more devices?
Thanks
Answer: <uses-feature android:glEsVersion="0x00030000" android:required="true" />

That limits the app to devices with that version of open GL.  3.0 is only supported on devices with Android 4.3 or higher, which is a small percentage of all devices.  If you need OpenGL 3.0, you're limited to just those 400ish devices.
Also note that not all 4.3 devices will support it, it also requires software driver and hardware support
Comment: Thanks , 4038 supporting devices now )


What's a twizzle?

Question: My wife's made me watch a lot of ice dancing in the past, and have no recollection of any reference to a "twizzle".  This year, it seems like it's standard jargon that any enthusiast should know.
What exactly is a "twizzle"?
Answer: A twizzle is when a skater executes a rotational turn with one foot while continuing to move across the ice simultaneously(1). This term is most common in ice dancing than other forms of ice skating.
Answer: Twizzles need to be continuous in movement and in rotation. For instance in a single forward Twizzle, a skater would make a full rotation from forward to forward in either direction. The desired tracing on the ice would look like a tight double three turn (forward-backward-forward edge) and if the rotation would not be fluid it would be just this turn. In other words a Twizzle is a cross between a spin and a three turn. It is more fluid than consecutive three turns but neither centred nor loopy as a spin.

What's a twizzle?


Why is betting on yourself in a sporting event considered unethical?

Question: I understand all the problems that a sports player betting against themselves can cause, but what is the harm caused by betting for oneself or one's team to win  (note I am not saying win by X points, just win).
In players contracts, they could have clauses for getting X money with each win, how would this be different than a player putting X money on a game, and winning if they win?
Note:  The reason I am just saying winning is because if something such as winning by X points was done, the player would be trying for that goal, compared to the goal of winning (which would be the same goal even if he was not betting)
Answer: The problem isn't being on yourself to win - it's on the matches when you don't bet on yourself. Consider a situation where I bet on myself to win in 9 out of 10 matches, but then didn't bet on the 10th match. Am I going to try quite as hard, knowing that I'm (effectively) getting paid less for a win?
Answer: First for NFL, MLB, NCAA, NBA, and other US sports entities it is outlawed because of player's involvements with bookies and betting rings.  MLB isn't worried about a pitcher that wants to bet on himself against a bad team.  MLB is afraid that the pitcher will make relationships with bookies, could possibly lose money, and then play differently or provide inside information to pay off debts.
With team sports in general it isn't about betting on yourself or why didn't you bet on yourself, it is just the hovering cloud of impropriety too.  For instance Pete Rose bet on his team many many times.  When he was a manager did he overuse his bullpen to gain a win on bet day?
Second point is that players can bet on themselves in some sports.  Depending on the country you are in it can be legal to wager on yourself on tennis (heard many players doing this on tour), golf, and boxing - and I am sure there are many more.
Answer: I partially agree with you. But I think they're not allowed to because people would watch and see when they DON'T bet on themselves to win. Then of course  that would be noticed by everyone making bets and mess with the gambling world, plus it's suspicious when you don't bet on yourself. That could definitely be used as evidence in court of someone shaving points on a game or throwing it. "Your honor. He bet on himself every single game except this one. And this is the 1 game he lost." That looks extremely suspicious.


How to debug or explore an unknown object or array too big for Drupal's debug()?

Question: I'm trying to see what variables I have available in a $vars object in a Views hook. Unfortunately, like many Drupal object, this one is huge and attempting to output it using the Drupal debug() function (with or without the 3rd boolean argument) causes the server to crash with an out of memory error.
Note that this is after increasing the memory limit quite high, the memory limit isn't the problem here (UPDATE: I later discovered the array output was over 370 megabytes!).
What's the least intensive (fewest contrib modules, patches, custom code, 3rd party libraries etc) way to explore the contents of a Drupal object like this that's too big for Drupal's debug()?
Answer: Devel
Devel module provides dd() command which is very useful for dumping very large object. Just run dd($vars) in the middle of code, it'll dump any object to the temporary file in your Drupal temp folder (temporary://drupal_debug.txt).

XDebug
Use XDebug PHP extension, so var_dump() will be replaced by xdebug_var_dump() so your big dump won't consist circular dependencies and would be limited only by specific depth.

Alternatively use TVarDumper, array_slice, serialize or json_encode, so check below for further details:

Using print_r and var_dump with circular reference at SO
Comment: Nice, +1. For anyone wondering how to locate their temporary directory, see [this question](http://drupal.stackexchange.com/questions/30113/configuring-the-temporary-directory) - tldr; it's a setting configured by Drupal under Home » Administration » Configuration » Media » File system - that said, for now I'll stick to my tree walking method, the text file exported by `dd()` for this variable is 370mb!
Answer: Here's a very quick and reliable way to explore any object or array (here named $vars) one layer at a time:
  debug( array_keys((array)$vars), 'vars: '.  gettype($vars), false);

array_keys() gives only the names of the keys, giving you enough info to see where you need to go in the tree, regardless of what those keys contain.
Since you might not know if this variable is an array or an object, casting it as an array with (array) makes array_keys() work on either. You'll need to know which it is for the syntax for the next step, so that's ouput in the Drupal debug() title string with gettype().

Then you can simply choose a likely-looking from the output and walk up the tree. For example on seeing that $vars is an array which contains a relevant-looking key field:
  debug( array_keys((array)$vars['field']), 'field: '.  gettype($vars['field']), false);

Then on learning that $vars['field'] was an object containing a relevant-looking property items:
  debug( array_keys((array)$vars['field']->items), 'items: '.  gettype($vars['field']->items), false);

...and so on.


React, maintain the state of a component on history change

Question: I created a React app, in which I defined the classic style with left-side menu, title, footer and main content.
In the side menu I then defined the navigation, listing the various items that compose it with the <List>, <ListItem>, etc components of the @ material-ui package.
Having therefore the main item of the menu, with the sub-items inside, by default I start that each main item is closed.
When I click on it it changes the status and then opens, showing the sub-items.
So when I click on a sub-entry I am redirected to the correct route via history.push ().
However, I have the following problem.
Landed on the landing page, I would like to keep the state of the side menu so that it stays open, which is currently not the case.
Do you have any suggestions or advice? Did I do something wrong in the code or in the way to set the status?

MY CODE:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import ListSubheader from '@material-ui/core/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Collapse from '@material-ui/core/Collapse';
import history from './../../history';
import SettingsApplicationsIcon from '@material-ui/icons/SettingsApplications';
import LocalLibraryIcon from '@material-ui/icons/LocalLibrary';
import ContactMailIcon from '@material-ui/icons/ContactMail';
import CreditCardIcon from '@material-ui/icons/CreditCard';
import VisibilityIcon from '@material-ui/icons/Visibility';
import DashboardIcon from '@material-ui/icons/Dashboard';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import StarBorder from '@material-ui/icons/StarBorder';
import ListAlt from '@material-ui/icons/ListAlt';

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
  nested: {
    paddingLeft: theme.spacing.unit * 3,
  },
});

class NestedList extends React.Component {
  state = {
    open1: false,
    open2: false,
    open3: false,
    open4: false,
    open5: false,
    open6: false,
  };

  handleClick(id) {
    if (id === 1) {
      this.setState(state => ({ open1: !state.open1 }));
    } else if (id === 2) {
      this.setState(state => ({ open2: !state.open2 }));
    } else if (id === 3) {
      this.setState(state => ({ open3: !state.open3 }));
    } else if (id === 4) {
      this.setState(state => ({ open4: !state.open4 }));
    } else if (id === 5) {
      this.setState(state => ({ open5: !state.open5 }));
    } else if (id === 6) {
      this.setState(state => ({ open6: !state.open6 }));
    }

  };

  render() {
    const { classes } = this.props;
    const admin = 1;
    const url = window.location.pathname;

    if (admin === 1) {
      return (
        <List>
          <ListItem button selected={(url === '/dashboard') ? true : false} onClick={() => history.push('/dashboard')}>
            <ListItemIcon>
              <DashboardIcon />
            </ListItemIcon>
            <ListItemText primary="Dashboard" />
          </ListItem>
          {/* prima voce del menu */}
          <ListItem button onClick={() => this.handleClick(1)}>
            <ListItemIcon>
              <SettingsApplicationsIcon />
            </ListItemIcon>
            <ListItemText primary="Gestione" />
            {this.state.open1 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open1} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
            <ListItem button className={classes.nested} selected={(url === '/gestione/news_avvisi') ? true : false} onClick={() => history.push('/gestione/news_avvisi')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="News / Avvisi" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/gestione/modelli_email') ? true : false} onClick={() => history.push('/gestione/modelli_email')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Modelli email" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/gestione/profilo') ? true : false} onClick={() => history.push('/gestione/profilo')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Gestione profilo" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/gestione/ruoli') ? true : false} onClick={() => history.push('/gestione/ruoli')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Gestione ruoli" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/gestione/cassetti') ? true : false} onClick={() => history.push('/gestione/cassetti')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Gestione cassetti" />
              </ListItem>
            </List>
          </Collapse>
          {/* seconda voce del menu */}
          <ListItem button onClick={() => this.handleClick(2)}>
            <ListItemIcon>
              <LocalLibraryIcon />
            </ListItemIcon>
            <ListItemText primary="Anagrafiche" />
            {this.state.open2 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open2} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested} selected={(url === '/anagrafiche/utenti_censiti') ? true : false} onClick={() => history.push('/anagrafiche/utenti_censiti')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Utenti censiti" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/anagrafiche/archivio_documenti') ? true : false} onClick={() => history.push('/anagrafiche/archivio_documenti')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Archivio documenti" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/anagrafiche/archivio_rate') ? true : false} onClick={() => history.push('/anagrafiche/archivio_rate')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Archivio rate" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/anagrafiche/accertamenti') ? true : false} onClick={() => history.push('/anagrafiche/accertamenti')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Accertamenti" />
              </ListItem>
            </List>
          </Collapse>
          {/* terza voce del menu */}
          <ListItem button onClick={() => this.handleClick(3)}>
            <ListItemIcon>
              <ContactMailIcon />
            </ListItemIcon>
            <ListItemText primary="Richieste Utenti" />
            {this.state.open3 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open3} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested} selected={(url === '/richieste/assistenza_tecnica') ? true : false} onClick={() => history.push('/richieste/assistenza_tecnica')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Assistenza tecnica" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/richieste/assistenza_tributaria') ? true : false} onClick={() => history.push('/richieste/assistenza_tributaria')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Assistenza tributaria" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/richieste/variazioni_recapito') ? true : false} onClick={() => history.push('/richieste/variazioni_recapito')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Variazioni recapito" />
              </ListItem>
            </List>
          </Collapse>
          {/* quarta voce del menu */}
          <ListItem button onClick={() => this.handleClick(4)}>
            <ListItemIcon>
              <CreditCardIcon />
            </ListItemIcon>
            <ListItemText primary="Versamenti" />
            {this.state.open4 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open4} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested} selected={(url === '/versamenti') ? true : false} onClick={() => history.push('/versamenti')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Versamenti" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/versamentiCC') ? true : false} onClick={() => history.push('/versamenti/versamentiCC')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Versamenti CC" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/versamentiF24') ? true : false} onClick={() => history.push('/versamenti/versamentiF24')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Versamenti F24" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/versamenti_pagoPA') ? true : false} onClick={() => history.push('/versamenti/versamenti_pagoPA')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Versamenti PagoPA" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/quietanzeF24') ? true : false} onClick={() => history.push('/versamenti/quietanzeF24')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Quietanze F24" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/parifica') ? true : false} onClick={() => history.push('/versamenti/parifica')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Parifica" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/versamenti/upload_AdE') ? true : false} onClick={() => history.push('/versamenti/upload_AdE')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Upload modello AdE" />
              </ListItem>
            </List>
          </Collapse>
          {/* quinta voce del menu */}
          <ListItem button onClick={() => this.handleClick(5)}>
            <ListItemIcon>
              <VisibilityIcon />
            </ListItemIcon>
            <ListItemText primary="Monitoraggio" />
            {this.state.open5 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open5} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested} selected={(url === '/monitoraggio/log') ? true : false} onClick={() => history.push('/monitoraggio/log')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Log" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/monitoraggio/log_F24') ? true : false} onClick={() => history.push('/monitoraggio/log_F24')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Log F24" />
              </ListItem>
            </List>
          </Collapse>
          {/* sesta voce del menu */}
          <ListItem button onClick={() => this.handleClick(6)}>
            <ListItemIcon>
              <ListAlt />
            </ListItemIcon>
            <ListItemText primary="Report IMU/TASI" />
            {this.state.open6 ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open6} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested} selected={(url === '/imu_tasi/lista_immobili_imu_tasi') ? true : false} onClick={() => history.push('/imu_tasi/lista_immobili_imu_tasi')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Lista immobili" />
              </ListItem>
              <ListItem button className={classes.nested} selected={(url === '/imu_tasi/dettagli_modello_F24') ? true : false} onClick={() => history.push('/imu_tasi/dettagli_modello_F24')}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText primary="Dettaglio F24" />
              </ListItem>
            </List>
          </Collapse>
        </List>);
    } else {
      return (
        <List>
          <ListItem button selected={(url === '') ? true : false} onClick={() => history.push('/dashboard')}>
            <ListItemIcon>
              <DashboardIcon />
            </ListItemIcon>
            <ListItemText primary="Dashboard" />
          </ListItem>
        </List>
      );
    }

  }
}

NestedList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NestedList);

Answer: State are by default not persistent. You can have a look into storing value in the local storage and retrieving the state saved.
Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


File Rename problem?

Question: I'm using VB6 and I have a folder where I have n number of files.
I want to change the file extension to .txt. I used the code below to change the extension of all .fin files to .txt.
Dim filename1 As String
filename1 = Dir$(txtsourcedatabasefile & "\*.fin", vbDirectory)
Do While filename1 <> ""
    Dim strInput As String
    Dim strOutput As String
    Dim strChar As String
    Dim intChar As Integer
    Dim intLoop As Integer
    strInput = filename1
    strOutput = ""
    For intLoop = 1 To Len(strInput)
        strChar = Mid$(strInput, intLoop, 1)
        intChar = Asc(strChar)
        If ((intChar >= 48) And (intChar <= 57)) Or _
            ((intChar >= 65) And (intChar <= 90)) Or _
            ((intChar >= 97) And (intChar <= 122)) Or _
            (intChar = 95) Then

            strOutput = strOutput & strChar
        End If
    Next
    Name txtsourcedatabasefile & "\" & filename1 As txtsourcedatabasefile & "\" & strOutput & ".txt"
    filename1 = Dir$
Loop

The code above is working for changing .fin to .txt, but with filenames without any extension, like Clockings2.mis04062009 022511 PM, Silver_421_export, etc., aren't transformed to a .txt extention. For example, Clockings2mis04062009022511PM.txt, Silver_421_export.txt.
How should I change this code?
Answer: If I am interpreting your question correctly, you want to iterate through the files in a directory and change all files with the extension ".fin", or no extension at all, to ".txt".  You can add a reference to the Microsoft Scripting Runtime and use the FileSystemObject to do that rather easily.  In this example, we'll assume txtsourcedatabase contains the directory you wish to process:
Dim fso As New FileSystemObject
Dim fil As Variant

For Each fil In fso.GetFolder(txtsourcedatabase).Files
  If (LCase$(fso.GetExtensionName(fil.Name)) = "fin") Or _
      (fso.GetExtensionName(fil.Name) = vbNullString) Then
    fso.MoveFile fil.Path, fso.BuildPath(fso.GetParentFolderName(fil.Path), _
      fso.GetBaseName(fil.Path) & ".txt")
  End If
Next

Answer: Ok, a few things. This won't really fix your problem, but just so you know, some of what you are trying to do can be accomplished from the command prompt (ren *.fin *.txt). Obviously this  does not address the issue of files with no extensions.
Secondly, you shouldn't even be getting files with no extensions based on invoking the Dir command with *.fin.
Thirdly, assuming your criteria is to rename all files ending in .fin or having no extension .txt... This should work:
Private Const txtsourcedatabasefile As String = "C:\test\"
Public Sub Example()
    Dim filename1 As String
    Dim strOutput As String
    filename1 = Dir$(txtsourcedatabasefile & "*")
    Do While LenB(filename1)
        strOutput = filename1
        If InStrB(1, strOutput, ".", vbBinaryCompare) = 0& Then
            strOutput = strOutput & ".txt"
            Name txtsourcedatabasefile & filename1 As txtsourcedatabasefile & strOutput
        ElseIf LCase$(Right$(filename1, 4)) = ".fin" Then
            Mid$(strOutput, Len(filename1) - 2) = "txt"
            Name txtsourcedatabasefile & filename1 As txtsourcedatabasefile & strOutput
        Else
            Debug.Print "Skipped:", strOutput
        End If
        filename1 = Dir$
    Loop
End Sub

Answer: First, I think you want to change your Dir$ attribute from vbDirectory to vbNormal. Second I think you should simplify your renaming code. You can use the built-in VB function Replace to do what you want.
Dim filename1 As String

filename1 = Dir$(txtsourcedatabasefile & "\*.fin", vbNormal)

Do While Len(filename1) > 0
   Name txtsourcedatabasefile & "\" & filename1 As txtsourcedatabasefile & "\" & _
       Replace(filename1, ".fin", ".txt", Len(txtsourcedatabasefile & "\" & filename1) - 4, 1, vbTextCompare)
   filename1 = Dir$
Loop

File Rename problem?


Como criar uma variável inteira em hexadecimal?

Question: Estou tentando criar uma variável inteira em hexadecimal, mas ocorre um erro dizendo que não está no formato correto.
[DllImport("user32.dll")]
public static extern short GetKeyState(int vKey);
static void Main(string[] args)
{
    string[] lines = File.ReadAllLines("config.txt");
    int TriggerButton = int.Parse(lines[0].Replace("Trigger Button: ", ""));
    int PanicButton  = int.Parse(lines[1].Replace("Panic Button: ", ""));
    Console.WriteLine(TriggerButton + "\n" + PanicButton);
    while (true)
    {
        Console.WriteLine(GetKeyState(TriggerButton));
    }
    Console.ReadKey();
}

Config.txt
Trigger Button: 0x12
Panic Button: 0x78

Tem alguma maneira de converter uma string para um inteiro hexadecimal sem perder o 0x?
Comment: Pelo que entendi você quer pegar uma string no formato hexadecimal e transformar em inteiro. Segue [Fiddle](https://dotnetfiddle.net/eqepEg) com a resposta abaixo!
Answer: Sem utilizar StringFormat, uma opção válida é utilizar
Convert.ToInt32 Method (String, Int32)

Int32 será a base, neste caso 16 Hexadecimal
int PanicButton = Convert.ToInt32(lines[1].Replace("Panic Button: ", ""), 16);

int TriggerButton = Convert.ToInt32(lines[0].Replace("Trigger Button: ", ""), 16);


Functions & Cellular automata

Question: Let x = number of live neighbors of a cell
$$f(x)=\left\{\begin{matrix}
live & \textrm{if}\ x = 3\\
live & \textrm{if}\ x = 4\\
dead & \textrm{otherwise}\\
\end{matrix}\right.$$
$$f(1) = dead$$
$$f(3) = live$$
$$f(4) = live$$
$$f(5) = dead$$
Given that the outputs aren't numbers, is this still mathematically sound?
Answer: Yes. Functions represent a relationship between 2 (not necessarily identical) sets.
You can talk about the function whose input in the name of a town, and whose output is the distance that you are from it.

Functions & Cellular automata