text:
Q: getting error on passing argument for ProcessStartInfo In below C# code, I'm getting error,
ProcessStartInfo psi = new ProcessStartInfo("logman.exe")
            {
                RedirectStandardOutput = true,
                Arguments = "FabricTraces | findstr Root",
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false
            };
            Process proc = Process.Start(psi); ;
            StreamReader myOutput = proc.StandardOutput;
            proc.WaitForExit(20000);
            if (proc.HasExited)
            {
                Console.WriteLine( myOutput.ReadToEnd());
            }

Error,
Argument '|' is unknown.
Argument 'findstr' is unknown.
Argument 'Root' is unknown.

I need to pass below argument, how to do it? Thanks for your answer.
FabricTraces | findstr Root

Output in Console,
C:>logman.exe FabricTraces | findstr Root
Root Path:            C:\ProgramData\Windows Fabric\Fabric\log\Traces\
C:>

A: ProcessStartInfo accepts  Arguments with spaces inside quotes and interpreted them as multiple arguments.So you should wrap it with the double quote. (As I understand you should pass one argument to the process)
        startInfo.Arguments = "\"FabricTraces | findstr Root\"";

Now it should be treated as a one argument not 3 space separated ones.


text:
Q: How do I remove ONLY JavaScript comments that start with "// "? To clarify first, I already have a compression tool that successfully compresses EVERYTHING else so I don't need a long complicated preg_replace regex, just a simple preg_replace or str_replace rule will do.
I ONLY want to remove JavaScript comments that start with "// " (including the space so I don't erase URLs) up until the new line. THAT'S IT! Once again, I don't need to replace /* */ or any other variations as I have a script that does that already; the only thing it's missing is this one feature so I want to clean up the input with this first, then hand it over to the script.
Here are screenshots with examples of comments I would like to remove:

I would really appreciate help with this! :-) THANKS!

A: Try this code:
$re = "~\\n? */{2,} .*~";
$str = "text\n\n/*\ntext\n*\n    //example1\n    //example2\n\ntext\n\n//   example 3";
$subst = "";

$result = preg_replace($re, $subst, $str);

The regex matches two or more / following by a space like you asked in the question. When you replace it will erase the whole line or until the spaces and line breaks that were
Demo

A: I'd use a regex with the multi-lined modifier, m,
/^\h*\/\/.*$/m

This will find any lines that start with a // regardless of the whitespace preceding it. Anything after the first // will be removed until the end of that line.
Regex101 Demo: https://regex101.com/r/tN7nW9/2
You should include your data in the future as a string (not image) so users can run tests on it.
PHP Usage:
echo preg_replace('/^\h*\/\/.*$/m', '', $string);

PHP Demo: https://eval.in/430182

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implement infinite list using React Query in react native with Flatlist Here is my code:
import React, {useState} from 'react';
import {useQuery, useInfiniteQuery} from 'react-query';
import {getMeetup} from '../../api/methods/getMeetups';

export default function MyFunction(props) {
  const [next, setNext] = useState('');

  const fetchData = async ({pageParam = ''}) => {
    const response = await getMeetup( pageParam);
    console.log('API RESP', response);
    return response;
  };

  const {data, isLoading, fetchNextPage} = useInfiniteQuery(
    'myData',
    fetchData,
    {
      getNextPageParam: (lastPage, pages) => lastPage?.next?._id,
    },
  );

  console.log('RQUERY CHECK', data);

  const getMore = () => {
    console.log('data end', data?.pages[0]?.next?._id);
    fetchNextPage({pageParam: data?.pages[0]?.next?._id});
  };
  const flattenData = data?.pages
    ? data?.pages?.flatMap((page) => [...page.Docs])
    : [];

  return (
    <View>
      <FlatList
        style={{
          marginBottom: verticalScale(40),
          paddingHorizontal: scale(15),
        }}
        data={flattenData}
        keyExtractor={(item) => item._id}
        renderItem={({item, index}) => {
          return <ListItem data={item} index={index} />;
        }}
        onEndReachedThreshold={0.1}
        onEndReached={getMore}
      />
    </View>
  );
}

The problem i am facing is when the page loads the api calls one by one with unique next ids or page param. What i was trying to implement is , when user reaches the end of the page (onEndReached) the data needs to be fetched with a new page param.

A: getNextPageParam return the value for the next page. So you don't need pass pageParam in fetchNextPage unless you want overwrite, for any reason, the next page value.
You can add a hasNextPage validation for unnecessary requests.
 const {data, isLoading, hasNextPage, fetchNextPage} = useInfiniteQuery( /* your code */ )
 const getMore = () => {
    if(hasNextPage)
      fetchNextPage();
  };


text:
Q: Why doesn't MySQL InnoDB redo log block writing need double write? MySQL InnoDB redo log block size is 512 bytes (maybe a sector in the disk). I read Are disk sector writes atomic?. It looks like it depends on the underlying hardware to decide if a sector writing is atomic. So if it's not atomic, how can InnoDB redo log guarantees that it won't be corrupted?
Say the last log block was not full in the disk, then the InnoDB engine wrote more log records to this block and flushed it to the disk. Sudden power loss caused only part of the block had been written into disk. By that the checksum of this block is mismatched. Other previous committed transactions would be lost after the server restarts.

A: when a transcation commit,  mysql will force flush the redo log block(512b) to disk, if the log block is not full, mysql will fill the blcok with zero(zero-filling) before flush to disk.
if the flush action is success, the transcation commit will be success;
if the flush action has error, the transcation commit will be fail;
so if a transcation commit is success, the transcation's redo log must has flushed to disk.
if the checksum of redo block is mismatched, it mean the redo log block flush action has error(such as power loss), the transcation of the redo log in this block must is fail.
So the commited transcation will not be lost when mysql recover from power loss, because a success transcation must flush his redo log to disk successfully.
And Last, why the redo log block size is 512 byte?
because it try to use the disk atomic write(a disk sector size 512 byte) for speed up and less mismatched checksum.
if the disk not support 512byte atomic write, it doesn't matter.


text:
Q: Are There Inflection Points In A Function With No Critical Points? I have a function, defined as:
$f(x)=\frac{2x}{x^2-25}$
It has been determined to have no critical points since the x-values would be the same as the vertical asymptotes.
I have also determined that the function is always decreasing for the entire domain of the function. Domain is $\{x| x \ne \pm 5, x\in R\}$
With this information, can I conclude there are no inflection points and no concavity?

A: A monotonic function can have intervals of concavity bound by points of inflection.
\begin{align}
f(x)&=\frac{2x}{x^2-25}\\
f'(x)&=\frac{-2x^2-50}{(x^2-25)^2}=-2\left(\frac{x^2+25}{(x^2-25)^2}\right)\\
f''(x)&=-2\left(\frac{2x(x^2-25)-2(2x)(x^2+25)}{(x^2-25)^3}\right)\\
&=-2\left(\frac{2x^3-50x-4x^3-100x}{(x^2-25)^3}\right)\\
&=4x\left(\frac{x^2+75}{(x^2-25)^3}\right)
\end{align}
By inspection, there is a point of inflection at $(0,0)$.

Another way to see that there must be a point of inflection is to recognize that $f(x)$ is odd.  By the nature of rotational symmetry, concave up intervals have their counterpart concave down intervals.

A: if your domain is restricted, and you have determined the function is decreasing and any critical points would have been a vertical asymptote, then it will surely have no inflection points. Specifying your domain here would be helpful for the reader to help you.


text:
Q: why ruby loop does not exit I'm trying to write a loop that exits at a certain value of an integer variable.
i=2
while i != 5 do
    puts "insert an integer. 5 to end"
    i = gets.chomp
    puts "you entered #{i}"
end

puts "program end"

the program keeps asking puts "insert an integer. 5 to end" even if I insert 5
the same story with loop do
i=2
loop do
  puts "insert an integer. 5 to end"
    i = gets.chomp
    puts "you entered #{i}"
  break if i == 5
end
puts "program end"

A: i=2
while i != "5" do
    puts "insert an integer. 5 to end"
    i = gets.chomp
    puts "you entered #{i}"
end

puts "program end"

You're getting a string from the user, therefore i != 5 always evaluates to false. You can turn it to i != "5" or convert your string to an integer.

A: gets.chomp returns a String, so i is never equal to 5, a Fixnum. You need to convert it to an integer:
i = gets.chomp.to_i


text:
Q: When and Why is XML preferable to CSV? sometimes it feels like XML has been used just because it was fashionable.

A: I found an interesting performance test on the net. God example of drawbacks of XML when the features of XML is not needed.
"I tried Steven's experiment from a different angle. I filled an Excel XP
spreadsheet with a single-digit number, saved it in both XML and in a
comma-delimited text file (CSV). I then compressed both with WinZip and then
opened both with Excel. Here's what I found:
The XML file was 840MB, the CSV 34MB -- a 2,500% difference
Compressed, the XML file was 2.5MB, the CSV 0.00015MB (150KB) -- a 1,670%
difference.
Equally dramatic is the time it took to uncompress and render the files as
an Excel spreadsheet: It took about 20 minutes with the XML file; the CSV
took 1 minute -- a 2,000% difference."
http://www.xml.com/pub/a/2004/12/15/deviant.html

A: You can have a much more complex hierarchy, etc. and structure with XML vs. CSV. It offers a lot more flexibility.

A: Some strengths:

*

*You can validate XML data against XSD

*You can easily provide contracts (as XSD) to other parties that should either create/consume XML data, without literally describing them

*You can have one to many relations in multi-levels in XML data representation

*XML is arguably more readable than CSV

*XML is natively supported by the .net framework

To name a few from the top of my head.

A: XML is preferrable over CSV when the data is unstructured (unknown schema) and will be read by a human.
Arguably, unless the data contains predominantly text, CSV is also meant for human consumption.
Also relevant, is if your data is 2 or 3 dimensional.
CSV is most suitable for 2 dimensional text, and due to its' verbosity, XML works well with 3 dimensional data.
The whole "standardness" of XML is hyperbole, and should not be taken literally. XML does have huge technical issues and many of the solutions aren't particularly elegant, or in many cases useful:

*

*It uses text to specify its own text-encoding (chicken and egg?)

*None of the more common schema languages for XML work particularly well.

*The ancient and commonplace way of creating mark-up languages using <tags> is not particularly helpful as a standard.

*XML tries to retroactively shoehorn more powerful mark-up languages such as the SGML based ones, into itself, creating a mess of incompatible legacy.

*It still remains to be determined whether or not XML text escape sequences can work for anything but the most simple cases (ie. friendly data).

To be clear, XML is probably the incorrect choice for 90% of the data interchange it is currently being used for, since those uses break some or all of the above assumptions.

A: Of course it is fashionable and buzz-worthy sometimes. It all depends on your application. I prefer config files in XML because they are easy to parse. Whereas, I use CSV files for DataGridView or database dumps.
This Daily WTF : XML vs CSV The Choice is Obvious will help you make your decision ;)

A: I have found of the greatest advantages of XML to be the parsing functionality and the strict validation that comes out-of-the-box with most XML libraries. The insistence on well-formedness and easy-to-understand error message (xyz not closed in line x, column y) are a real help compared to hunting broken values, or unknown behaviour, because of an error in the CSV file.

A: In addition to the other answers, XML allows you to specify which character set the document is in.

A: .csv files are good when your data is strictly tabular and you know its structure.  As soon as you start having relationships between different levels of your data, xml tends to work better because relationships can be made obvious (even without schemas) just by nesting.

A: XML has become the default for its many benefits that lots of other people have already mentioned. So the question really becomes "When and Why is CSV preferable to XML?".
I feel CSV is preferable to XML when:
- you are loading simple tabular data
- you are in control of both the generation and consumption of the data file
- the dataset is large
CSV is perfectly usable if the first 2 points are true, and has a performance benefit that becomes more significant the larger the dataset is.
I did a quick test loading ~8000 records each with 6 text fields. Loading and parsing the XML took ~8 seconds. Loading the CSV took less than 1 second.
The overhead of XML is worth it in a lot of cases, but when the stars align, CSV makes more sense.

A: CSV is more lightweight if you want to move things about since its normally 2  more times smaller than XML
XML is standard and won't be hit by different OS'es version of CSV

A: I don't have enough reputation to comment on the relevant answer, but someone suggested compressing the XML as a way to gain size parity with csv formats. While this is true, XML compression can somtimes come back to bite you. If you are transferring XML data from point to point and it fails, it's nice to be able to read the XML and figure out what went wrong. If the XML is compressed and the transfer fails, it's sometimes not possible to decompress it and examine the contents. In other words compressing XML cancels out the human-readability advantage it has.

A: I would say use XML (and or JSON) because someday you or someone (with a short temper and a large gun collection) may have to go find an error in the CSV data.
So yes, I'm saying readability, don't forget to think of the other guy! He may be thinking about you.

A: CSV is useful when you just have a series of a values that relate to some piece of information and you know you will always store values for each field.
XML has the benefit of having self-describing data (tags) and having hierarchy - which gives you a lot more flexibility in the way that you store the data.

A: XML provides a way of tagging your data with metadata (provided by the tag names and attribute names), whereas CSV does not. Couple this with the ability to define structured hierarchies and it makes XML easier to understand when provided with just the data, whereas CSV would require an accompanying tool or document to describe how each value is interpreted.

A: You can easily traverse through XML data even when you have complex data.
Check these links:

*

*The Advantages of XML Over CSV

*XML vs CSV

*XML vs CSV : The Choice is Obviou

A: Structured, human readable, easier to edit, validation, parsability, transformability, typing, namespaces, powerful libraries behind it, are all amongst many of the reasons.
Above all else though it is standard.

A: And again one more for XML: The X in XML stands for Extensible (I know, not really mnemonic :-P). That means, with the help of the XML namespace mechanism, you can join any two XML languages you like and combine them in the same document. Given that there is only one CSV 'language' (not counting the myriads of delimiter styles), XML can handle quite a lot of complexity, and that in a modular way.
This however, is the advantage of CSV: If you really have tabular data, XML syntax is most often overkill.

A: I've also found that some cvs generators/parsers have a lot of difficulty with general text data.  Long text strings with a lot of carriage returns and commas and quotations, etc etc, just make life really difficult when it comes to manipulating a cvs.
SSMS likes to truncate csv for fun.

A: *

*There are existing parsers and emitters for it in every language and database

*They deal with encoding for me

*They deal with escaping for me

That's all that matters to me.
Sure, there's a semi-standard way to do escaping in CSV (i.e., "the way Excel does it"), and it's not exactly hard to write yourself, but it does take some time.  And then you've got to implicitly agree on a character encoding out-of-band.  But then, because it's so simple, people try to write it themselves, and invariably screw up either #2 or #3.
JSON also meets #2 and #3 and is getting close to satisfying #1.  It's also arguably simpler, at least for non-document files.  Not surprisingly, I find myself using it more and more, internally and externally.

A: And I also prefer it because it's much more readable.


text:
Q: How to implement a type into an interface definition? I have a nested object of optional properties. I found a way to declare this type via this answer. Now I'm trying to figure out how to apply this type to my object interfaces without having to modify every object that uses the interface. Some examples to make this clearer.
Here is a minimal reproducible example.
Here is the recursive object type:
export type PartialRecursive<T> = T extends object
? {
      [K in keyof T]?: PartialRecursive<T[K]>;
  }
: T;

Sample interface:
export interface Foo {
    bar: boolean;
    bax: boolean;
}

Simple object (NOTE: the array is required here):
import { Foo } from './types';
const foo: Foo[] = [
    {
        bar: true
    }
]

To use the new interface I could do this:
import { Foo, PartialRecursive } from './types';
const foo: PartialRecursive<Foo>[] = [{...}];`

But I would prefer to apply this PartialRecursive type to the interface where it is declared, but I'm not sure how to do it. I have a lot of objects and would prefer to implement this type against the interface instead of each implementation that uses it.
I hope this is clear, checked the TS docs, but it was hard to find what I was looking for.


text:
Q: Compiling Problem with c++ on Ubuntu 16.04 LTS? So I have a debugger problem. So I created a c++ program and I ran it on Ubuntu 16.04. However, when trying to compile by typing in the command line g++ decrypt.cpp caesor\ cipher.cpp -o decrypt, it gave me a few errors. this is the first time I've been working on c++ in a long time and was hoping that you guys could spot something I can't. Here is the code and the error below. thank you
=====================================
decrypt.cpp
#include"decrypt.h"
#include<fstream>
#include<string>
using namespace std;
#include<iostream>
Decrypt::Decrypt(string text)
{
    str = text;
    zero_analysis_array();
    //E A R I O are top 5 most commonly used letters in english words
     //initializing keys arrays with thier position in alphabets
    keys[0] = 'E' - 'A';
    keys[1] = 'A' - 'A';
    keys[2] = 'R' - 'A';
    keys[3] = 'I' - 'A';
    keys[4] = 'O' - 'A';
}
void Decrypt::zero_analysis_array()
{
    for (int i = 0; i < 26; i++)
    {
        freq[i] = 0;
    }

}

void Decrypt::character_count()
{
    char ch;
    for (int i = 0; i < str.size(); i++)
    {
        if (is_alpha(str[i]))
        {
            ch = str[i];
            if (!is_upper(ch))
                ch = to_upper(str[i]);
            int a = ch - 'A';
            if (a > 26 || a < 0)
                cout << "a";
            freq[ch - 'A']++;
        }
    }
}

void Decrypt::print_analysis_array()
{
    char alpha = 'A';
    cout << "\n\n";
    for (int i = 0; i < 26; i++)
    {
        cout << char(alpha + i) << " occurs " << freq[i] << " times\n";
    }
    int ind = max_index(), key;
    cout << "Possible keys:\n";
    for (int i = 0; i < 5; i++)
    {
        key = ind - keys[i];
        if (key < 0)
            key = key + 26;
        cout << key << "\n";
    }

}
string Decrypt::decrypt(int key)
{
    string decrypt = str;
    int code, a, b;
    char ch;
    for (int i = 0; i < decrypt.size(); i++)
    {
        if (is_alpha(decrypt[i]))
        {
            ch = 'A';
            if (is_upper(decrypt[i]) == false)
                ch = 'a';
            a = (decrypt[i] - ch);
            b = a + 26 - key;
            code = b % 26;
            decrypt[i] = ch + code;
        }
    }
    return decrypt;

}
void Decrypt::write_to_file(string fname, string text)
{
    fstream file;
    file.open(fname, ios::out);
    file << text;
    file.close();
}
void Decrypt::decryption(string fname)
{
    character_count();
    print_analysis_array();
    string decrypted;
    int key;
    char choice;
    do
    {
        cout << "Select/Enter key(0-26):";
        cin >> key;
        while (key < 0 || key>26)
        {
            cout << "Invalid Key!! Must be between 0-26\nEnter Again:";
            cin >> key;
        }
        decrypted = decrypt(key);
        cout << "\nHere is decrypted text:\n\n" << decrypted;
        cout << "\n\nDo you want to try again with different key? (y/n):";
        cin >> choice;
        while (choice != 'Y' && choice != 'y' && choice != 'n' && choice != 'N')
        {
            cout << "Invalid choice!!.\nEnter (y/n):";
            cin >> choice;
        }

    } while (choice == 'y' || choice == 'Y');
    write_to_file(fname, decrypted);
    cout << "Decrypted text written to file " << fname << "\n";
}
int Decrypt::max_index()
{
    int maxIndex = 0;
    int maxFreq = freq[0];
    for (int i = 0; i < 26; i++)
    {
        if (maxFreq < freq[i])
        {
            maxIndex = i;
            maxFreq = freq[i];
        }
    }
    return maxIndex;
}
char Decrypt::to_upper(char ch)
{
    if (!is_upper(ch))
        return ch - 32;
    return ch;
}
bool Decrypt::is_alpha(char ch)
{
    return((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'));
}
bool Decrypt::is_upper(char ch)
{
    return (ch >= 'A' && ch <= 'Z');
}

=================================
caesor cipher.cpp
#include<fstream>
#include <iostream>
#include"decrypt.h"
int main(int argc,char*argv[])
{
    if (argc < 2)
    {
        cout << "Invalid no of Arguments!!!\n";
        exit(0);
    }
    string text=read_from_file(argv[1]);
    cout << text;
    Decrypt d(text);
    d.decryption(argv[2]);
}

string read_from_file(char* fname)
{
    fstream file;
    string line,text="";
    file.open(fname, ios::in);
    while (getline(file, line))
    {
        text = text + line;
    }
    return text;

}

=========================
decrypt.cpp: In member function 'void Decrypt::write_to_file(std::__cxx11::string, std::__cxx11::string)':
decrypt.cpp:88:30: error: no matching function for call to 'std::basic_fstream<char>::open(std::__cxx11::string&, const openmode&)'
     file.open(fname, ios::out);
                              ^
In file included from decrypt.cpp:2:0:
/usr/include/c++/5/fstream:1001:7: note: candidate: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
       open(const char* __s,
       ^
/usr/include/c++/5/fstream:1001:7: note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*'
caesor cipher.cpp: In function 'int main(int, char**)':
caesor cipher.cpp:9:15: error: 'exit' was not declared in this scope
         exit(0);

A: Well, the compiler actually tells you what is wrong with your program (and also gives a hint where the error is located).
decrypt.cpp:88:30: error: no matching function for call to 'std::basic_fstream<char>::open(std::__cxx11::string&, const openmode&)'
     file.open(fname, ios::out);
                              ^

This means your call to std::fstream::open is not correct. It expects a C-string and not a C++ std::string that you are giving it.
The easiest fix here would be to change the call to open as follows:
file.open(fname.c_str(), ios::out);

The second error says that it can't find a function named exit. This is because the compiler doesn't know this function yet. You need to include the appropriate header (in this case stdlib.h) where the function is declared in order for the compiler to know that there is a function called exit.

A: Your error is pretty self-explanatory. It says:
error: no matching function for call to 'std::basic_fstream<char>::open(std::__cxx11::string&, const openmode&)'

But it lets you know the closest match would be:
note: candidate: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode)

If you notice, the big difference there is string vs. char *. So give it the C-string it's looking for:
file.open(fname.c_str(), ios::in);

However, open() should accept std::string since C++11. So assuming you're using g++, you could also just add
-std=c++11

when you compile.


text:
Q: Is there a good objc library wrapper for File System Events/kqueue that handles recursive watching for me? I want to write an OSX (Snow Leopard) app that receives notifications when files within a specific directory are changed, and I want access to the path of the specific file that was changed.
I know I can do this using either File System Events or kqueue. The former doesn't provide the details of which specific file changed (requiring me to build a snapshot of the directory I'm watching and then scan it to find out which file changed). The latter doesn't support recursive watching (requiring me to recursively add watches to every file and directory within the parent directory).
I've had a look for libraries that handle the snapshot/recursion fun for me, but can't find any. UKKQueue looks like a good wrapper for the low level kqueue stuff, but doesn't seem to do recursion. Same for GTMFileSystemKQueue. SCEvents looks like a good wrapper for File System Events but doesn't seem to handle finding out the specific file that changed.
Is there a library that does what I want and is suitable for an objc project for either of these technologies?

A: I ended up using GTMFileSystemKQueue after I found out how easy it is to recursively iterate over a directory in objc:
// Create a directory enumerator for the given top level directory
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];

// Add a kqueue on every file and folder below the top level
NSString *file;
while ((file = [de nextObject])) {
    [[GTMFileSystemKQueue alloc] initWithPath:[dir stringByAppendingString:file]
                                    forEvents:kGTMFileSystemKQueueAllEvents
                                acrossReplace:YES
                                       target:self
                                       action:@selector(fileSystemKQueue:events:)];
}


text:
Q: How is the subset of the domain of a function, $\mathcal{X}_c\equiv \{x\in \mathcal{X}: f(x)=c\}$, called? Take a function $f: \mathcal{X}\rightarrow \mathcal{A}$.
Let $\mathcal{C}\subseteq \mathcal{A}$ denote the image set of $f$.
Take $c\in \mathcal{C}$.
Consider the subset $\mathcal{X}_c$ of the domain $\mathcal{X}$ defined as
$$
\mathcal{X}_c\equiv \{x\in \mathcal{X}: f(x)=c\}
$$
What is the technically correct name of $\mathcal{X}_c$?

A: Such a set has the label fiber of $c$ under function $f$.
It seems however that the terminology is also used if $c$ is an element of the codomain of $f$ and not necessarily an element of the image of $f$. So more specifically you could call it a non-empty fiber.
Every function induces partition on its domain. The elements are the non-empty fibers.

A: The inverse image of $c$,denoted by $f^{-1}(c)$ is defined as $$f^{-1}(c)=\{x|f(x)=c\}$$
The set is also called the pre-image of $c$


text:
Q: Axios hitting No 'Access-Control-Allow-Origin' header is present on the requested resource error
https://samples.openweathermap.org/data/2.5/forecast?appid=be2e163d03a0b97a96a89b0230be8e4a&q=klang,my

When I directly paste the URL into the browser, I can make the API request successfully. However, when I try it with Axios I'm hitting below exception

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Based on some research,
I can't understand the logic behind as I'm following the exact same steps provided by online course, by simply firing this API call using Axios should be able to return the result.
import axios from 'axios';

const API_KEY = 'be2e163d03a0b97a96a89b0230be8e4a';
const ROOT_URL = `https://samples.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`
export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city) {
  const url = `${ROOT_URL}&q=${city},my`;
  const request = axios.get(url);

  return {
    type: FETCH_WEATHER,
    payload: request
  }
}

A: This exception means the server your hitting does not support CORS (Cross-Origin Resource Sharing).
In the case of openweathermap.org I think you should be using api.openweathermap.org instead of samples.openweathermap.org

A: Here are the few things i observed:

*

*You are using the sample api("samples.openweathermap.org") not the production one("api.openweathermap.org") so i think for integration with application you should use production API.On this they give the CORS support.

*If you still want to check with sample api endpoint then
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin'header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Reference: https://openweathermap.desk.com/customer/portal/questions/16823835-cors

A: You need to add cors in your server app
 var cors = require('cors');
 app.use(cors());

Hope this help

A: When you directly access the url in browser there is no cross domain request is issued.
But when you access the resource using axios there might be a chance that you are accessing resource on different domain then the domain present on your browser tab.That is the reason you are getting Access-Control-Allow-Origin not present. For handling this add a logic on server side to add this header in OPTION Response.


text:
Q: Changing behavior of cd linux command Please, how can i modify the behavior of cd command without change of $HOME ?
$ pwd
 /home/alice
$ echo $HOME
 /home/alice
$ HOME=/home/alice/Music/
$ cd
$ pwd
 /home/alice/Music

A: $ echo $HOME
/home/alice
$ cd /home/alice/Music/
$ pwd
/home/alice/Music
$ HOME=/tmp
$ cd
$ pwd
/tmp


text:
Q: Using the "Checkbox" hack on live websites So recently there has been a lot examples of what the "Checkbox Hack" is possible of with CSS.
Css-Tricks has a good explanation on what the hack does:

The "Checkbox Hack" is where you use a connected label and checkbox
  input and usually some other element you are trying to control

Source & more information of the hack.
What recently got me liking the hack was CoDrops experiment with radio buttons to create filter functionality with just CSS. Just amazing.
The hack can do some pretty amazing stuff that would require JavaScript without. The problem is that the checkbox and radio buttons is only suppose to be used for forms, so it's bad semantics. But I don't see the problem of using a "hack" that is compatible in most browsers and work-around for mobile devices if it means less JavaScript and better performance.
Do you think that this kind of hack would be "okay" to use on live websites, even though it's bad semantics or you think, it's okay to use?

A: Read the big yellow disclaimer on the site you linked to:

Disclaimer: Some of this stuff crosses the line of what you "should"
  do with CSS and introduces some bad semantics. It's still wicked fun
  to play with and cool that it's possible, but in general functional
  behavior should be controlled by JavaScript.

I wouldn't say this is a "hack" on it's own. It's all perfectly valid, there's a lot of other crazy stuff you can do with the + adjacent selector or :focus too, for example. However, it can definitely be used for some "hacky" stuff.
If for instance, it aids a user to complete a form: that's great. Just remember that support for :checked is not universal, so if the usability of your site relies on it, seek alternate solutions/shims via javascript.
If you're just adding the checkbox elements into your markup for the sake of behavior/presentation, then yes - you should avoid it. If you already had the element to begin with and you're merely improving the user experience with it, that's great.


text:
Q: Are commas meant to be syntactically valid in Javascript if statements? The last few days, I've been helping a friend learn Javascript. It's his first language in years and he remembers virtually nothing, so he's been starting pretty much entirely from scratch. He's been going through a simple tutorial and I've been providing him with some exercises to help him practice. The most recent exercise I gave him was the (apparently) classic FizzBuzz problem. He solved it with a bit of help, but he did something very interesting while working out his solution. He came up with the following code:
for (var x = 1; x <= 100; x++) {
    if (x%3 == 0, x%5 != 0) {
        console.log("Fizz");
    }
    else if (x%3 != 0, x%5 == 0) {
        console.log("Buzz");
    }
    else if (x%3 == 0, x%5 == 0) {
        console.log("FizzBuzz");
    }
    else {
        console.log(x);
    }
}

He wasn't familiar with boolean comparison operators, so he didn't use && and instead used commas. My expectation was that it would crash and say something about a syntax error, but to my surprise it ended up running fine and just printing out a bunch of "Fizz" and "Buzz" lines, with no "FizzBuzz" or numbers. Needless to say, I was confused, so I did a bit of experimentation. My first test was to run this:
if (true, true) console.log('true, true');
if (true, false) console.log('true, false');
if (false, true) console.log('false, true');
if (false, false) console.log('false, false');

Which gave me two lines of output:
'true, true'
'false, true'

From that, I made the guess that all comma did was cause it to evaluate nothing but the last expression in the list. I then tried running this code:
for (var i = 0; i < 16; i++) {
    if ((Math.floor(i / 8) == 1), (Math.floor(i / 4) == 1), (Math.floor(i / 2) == 1), (i % 2 == 1)) {
        console.log(i);
    }
}

The output I got was all the odd numbers from 1-15, which confirmed my guess from my first test (since the last boolean in the comma-separated list was flipping every other iteration).
After all that long-winded context, my question is this: Is this comma syntax a known and intentional piece of the Javascript engine, or is it a strange, overlooked quirk of the interpreter? I know commas can be used for a few other things (initializing multiple variables in one line, declaring arrays, and separating parameters jump to mind), but I've never heard of them being used in conditional statements like this in any language, and I'm curious if anyone else knows whether or not this code should even run.
For reference, the FizzBuzz code and the second test I ran were both done using node, and the first test I ran was done in the Javascript console in Chrome, so it doesn't seem to be just a browser- or node-exclusive quirk if indeed it is one. Also, if you actually read this far, thank you.

A: The comma is an actual operator.  It evaluates both of its operands (from left to right) and returns the value of the second operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
Its most common usage is to supply multiple parameters in a for loop, but it can also be used for other purposes.


text:
Q: postgresql create all tables in schema with schema owner not the postgres default How to get all the tables I create to have the schema owner as the table owner?
In a database called layers, I have a schema called hi_ow and the owner is hi_ow. when I run a create table command it creates the table in the hi_ow schema but the owner is defaulted to Postgres
example:
drop table if exists hi_ow.how_dump;
create table hi_ow.how_dump as
select (st_dump(geom)).geom geom from hi_ow.how;

I know I can just run
alter table hi_ow.how owner to hi_ow

but I want the default owner for just THIS schema to be hi_ow
Is there some sort of set owner = hi_ow before I run multiple queries?
Or something in the schemas settings I need to enable?
The reassign command does not work for me because the tables I am trying to switch ownership from are owned by Postgres.


text:
Q: How to Check or Uncheck all Items in VB.NET CheckedListBox Control I need to select and unselect all items in a VB.NET CheckedListBox control, what is the best way to do this?
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        With clbCheckedListBox

        .Items.Add("Select/UnSelect All")
        .Items.Add("Enero")
        .Items.Add("Febrero")
        .Items.Add("Marzo")
        .Items.Add("Abril")
        .Items.Add("Mayo")
        .Items.Add("Junio")
        .Items.Add("Julio")
        .Items.Add("Agosto")
        .Items.Add("Septiembre")
        .Items.Add("Octubre")
        .Items.Add("Noviembre")
        .Items.Add("Diciembre")

        .SelectedIndex = 0

    End With

End Sub

    Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck

    If e.Index = 0 Then

        If e.NewValue = CheckState.Checked Then

            For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
                Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
            Next

        ElseIf e.NewValue = CheckState.Unchecked Then

            For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
                Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
            Next

        End If

    End If

End Sub

After Hours the above code work fine for me !

A: Ricardo, perhaps this might be what you are looking for:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim items$() = New String() {"Select/UnSelect All", "Enero",
     "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
     "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
    For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)

Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
    If e.Index = 0 Then
        Dim newCheckedState As CheckState = e.NewValue
        For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
            Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
        Next
    End If
End Sub

A: To check all CheckedListBox Item:

For i As Integer = 0 To CheckedListBox1.Items.Count - 1
     CheckedListBox1.SetItemChecked(i, True)
Next

To uncheck all CheckedListBox Item:

For i As Integer = 0 To CheckedListBox1.Items.Count - 1
     CheckedListBox1.SetItemChecked(i, false)
Next

A: If button.Text = "Select All" Then
    For i As Integer = 0 To checklist.Items.Count - 1
        checklist.SetItemChecked(i, True)
    Next
    Button.Text = "Deselect All"
Else
    For i As Integer = 0 To checklist.Items.Count - 1
        checklist.SetItemChecked(i, False)
        Button.Text = "Select All"
    Next
End If

A: I found that clbCheckedListBox.clearSelection() works well for unselecting all.

A: Do you mean something like this:
Dim checked As Boolean = True   ' Set to True or False, as required.
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
    CheckedListBox1.SetItemChecked(i, checked)
Next

Here I'm just looping through all the CheckedListBox Items and setting their checked state.

A: Added a separate checkbox called "Select All". On checking and unchecking of this checkbox items of a checklistbox can be selected or unselected. So you can call this Kb() function anywhere in your code:
Private Sub ChkSelectAll_Click(sender As Object, e As EventArgs) Handles ChkSelectAll.Click
    Kb(ChkSelectAll.CheckState)
End Sub

Private Sub Kb(ByVal Key As Boolean)
    For i As Integer = 0 To ChkLstServices.Items.Count - 1
        ChkLstServices.SetItemChecked(i, Key)
    Next
End Sub

A: Put this code in the SelectedValueChanged event.
Private Sub clbCheckedListBox_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles ContrListCheckBox.SelectedValueChanged
    If clbCheckedListBox.SelectedIndex = 0 Then
        If clbCheckedListBox.GetItemChecked(0) = False Then
            For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1

                Me.clbCheckedListBox.SetItemChecked(idx, False)
            Next
        Else
            For idx As Integer = 1 To ContrListCheckBox.Items.Count - 1

                Me.clbCheckedListBox.SetItemChecked(idx, True)
            Next
        End If
    ElseIf clbCheckedListBox.SelectedIndex > 0 Then
        If clbCheckedListBox.CheckedItems.Count = clbCheckedListBox.Items.Count - 1 And clbCheckedListBox.GetItemChecked(0) = False Then
            clbCheckedListBox.SetItemCheckState(0, CheckState.Checked)
        End If
        For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1

            If clbCheckedListBox.GetItemChecked(idx) = False Then
                clbCheckedListBox.SetItemCheckState(0, CheckState.Unchecked)

            End If
        Next
    End If
End Sub

Other solutions are correct but if you want to deselect another checkbox inside the CheckBoxList or empty the CheckBoxList without the Select All checkbox
the top checkbox will remain checked and it is not logical so the above code should solve this problem.

A: Another option would be to bundle the check/uncheck events - of two buttons, for example - into one handler and use the value of sender to set the check state:
Private Sub clbCheckedListBox(
    ByVal sender As Object,
    ByVal e As EventArgs) Handles btnAll.Click, btnNone.Click

    For i As Integer = 0 To clbApis.Items.Count - 1
        clbApis.SetItemChecked(i, sender Is btnAll)
    Next i
End Sub


text:
Q: Config file for a Java Application I am building a Java Application with the intention of packaging it to be a windows executable in the future. My NetBeans project structure can be seen
here.
I am currently reading from config.properties using getResourceAsStream(). I was not aware that this file cannot be written to in a similar manner. Would anyone be able to advise a way to achieve this or is a different approach to my problem required? Thanks.

A: I think you can use java.util.properties to solve your problem; to write to your properties first create a new Properties object, load them via your InputStream, use methods such as setProperty to add to your configuration and finally use store to write to them.
Example:
File appConfig = new File("a_file");
FileInputStream propsInput = new FileInputStream("a_file");

Properties prop = new Properties();

prop.load(propsInput);

try (Writer inputStream = new FileWriter(appConfig)) {

   // Setting the properties.
   prop.setProperty("A_PROP", "A_VALUE");

   // Storing the properties in the file with a heading comment.
   prop.store(inputStream, "INFORMATION!!!");

} catch (IOException ex) {
   ex.printStackTrace();
}

A: There's no straightforward answer to the question how to externalize configuration -- it depends on the application and the environment in which it will be deployed.
The Java preferences API is an attempt to get around this problem by providing a platform-neutral API for preferences. On Linux, the data is actually stored in an XML file in a subdirectory of $HOME/.java but, of course, the programmer isn't supposed to be concerned about this. Using this API is convenient, but doesn't allow complex data to be stored, and doesn't easily allow the programmer to provide the application with a way to read configuration from some specific place.
Rather than use the preferences API you can read/write files explicitly. For simple 'name=value' configuration, you can use a Properties object, which has methods for handling files. This method does allow a specific file location but, of course, controlling the file location does require some adaptation for the various platforms you might support.
If your configuration is more complex than 'name=value', you could read/write it in a format of your choice -- JSON, YAML, XML, etc. All these file formats are well-supported by Java. Using a text-based format allows users to edit the configuration using other tools, if they so wish.
In practice, I nearly always externalize configuration in serialized Java objects, into a file whose location I control. This allows configuration of arbitrary complexity without additional coding, since you're storing Java data directly. It takes a bit of work to structure a program to be serialized, but it's worth it in the long run. Unfortunately, this approach does not allow for easy editing of the configuration outside the program.
If you ever intend to run the application in a container (Docker, etc), then completely different considerations apply. You'll need to use a method of externalizing configuration that is compatible with the container platform -- simply reading and writing files is often inappropriate in such an environment.
If you're unsure how you want to handle configuration, do it in a class that implements an interface you define. Then, if you later change your mind, you can supply a different class that implements the same interface.


text:
Q: By using Ekcalendar how can we delete Particular events by clicking delete action By using EventKit i can add events to iphone calendar and i can make a new calendar by using EkCalendar. But now reqirement is need to delete single events in iphone calendar. how can i do this. Thanks in advance
func retrieveYourCalendar() {
    let calendars = eventStore.calendarsForEntityType(EKEntityType.Event)

    if(yourReminderCalendar == nil) {
        for calendar in calendars {
            if calendar.title == "new" {
                yourReminderCalendar = (calendar as EKCalendar)
                //  Exist = true
                break
            }
        }

        if(yourReminderCalendar == nil) {
            yourReminderCalendar = EKCalendar(forEntityType: EKEntityType.Event, eventStore: eventStore)
            yourReminderCalendar!.title = "new"
            yourReminderCalendar!.source = eventStore.defaultCalendarForNewEvents.source
          //  var error: NSError?
            do {
                try eventStore.saveCalendar(yourReminderCalendar!, commit: true)
                // self.calendarIdentifier = yourReminderCalendar!.calendarIdentifier
                print("Event calender saved")

            }
            catch(_){}
        }
    }

}

A: While adding Events to the calendar, store eventIdentifier in your db or any storage. It will be useful to identify the particular event to delete.
By using following code you can delete the event based on identifier,
Objective C:
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
  if (!granted) return;
  EKEvent* eventToRemove = [store eventWithIdentifier:savedEventId];
  if (eventToRemove) {
    NSError* err = nil;
    [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&err];
  }
}];

Swift: Fetching events based on start date and end date.
// Create an Event Store instance
let eventStore = EKEventStore();
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: {
            (accessGranted: Bool, error: NSError?) in

            if accessGranted == true {
                var startDate=NSDate().dateByAddingTimeInterval(-60*60*24)

        var endDate=NSDate().dateByAddingTimeInterval(60*60*24*3)

        var predicate2 = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil)

        println("startDate:\(startDate) endDate:\(endDate)")

        var eV = eventStore.eventsMatchingPredicate(predicate2) as [EKEvent]!

        if eV != nil {

eventStore.removeEvent(eV, span:EKSpanFutureEvents, commit:true, error:&error)
}

            } else {
                return
            }
        })

Check the updated answer for swift.
FYI: I didn't tested the code for swift.


text:
Q: Submitting an iOS game, viewport is completely wrong for App Store reviewer but fine on all of our devices I have a game we're trying to release in the app store for iphone and ipad, and while it works fine on all of our devices (a handful of iphones and ipads), when the app store reviewers try it the actual viewport they see is highly cropped and distorted.
This is an example options screen that the reviewer saw:

This is what that options screen looks like for us on an equivalent aspect ratio/resolution:

As you can see, it's just a small, off-centered square for them, surrounded by black. But we've tested this on devices like an old iphone 5 up to big ipads and have never seen anything like this, the game takes up the full screen and the aspect ratio is correct and not distorted or stretched.
One important detail is this is entirely an OpenGL and SDL program, not using any Apple UI frameworks at all. The render size is determined by SDL_GetRendererOutputSize(), which then is used in glViewport(), and the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag. This so far has seemed to work with both retina and non-retina physical devices.
Also all of the screenshots they've given us look the same, same little square viewport surrounded by black, so I originally thought they were cropping them on purpose to highlight specific components of the screen, but this appears to be just exactly how it looks for them as this square is in the same position in each screenshot.  I've asked them for more information on their devices but they wouldn't tell me.
We also have the program set to only ever use landscape, not portrait, but the weird thing is that with the way our UI reflows, the only way to get that button to look squished the way it does there is if the game was somehow still rendering in portrait, as seen this example shot I took by forcing it to run in a very tall portrait window:

I don't even know where to begin to try to figure out what's going wrong for them though, because as I've said, everything looks fine when running in an emulator and everything looks fine when we've run it on several physical devices. Is there some build or release configuration I could be missing? Some OpenGL setting I should check? I'm just hoping this problem looks similar to something someone else has encountered before.

A: If you are on an equivalent device, then another thing that may differ is the accessibility settings.  Search for display zoom in settings.   Also, try locking the iPad into portrait mode before launching your app to try and reproduce.
Note the little double arrow icon in the lower right corner of the reviewer's screenshot.   I don't know what that is, but it looks like it could be some kind of screen zoom or accessibility mode.  Perhaps they can answer what it does, and how to enable it for yourself.

A: To follow up with the solution that worked for me, I noticed that in my project's General settings in Xcode, under Deployment Info, I had only checked iPhone and not iPad.  What I've since learned is that without that checkbox, some iPads will have to run in an emulation mode, which may have been the source of our problem.  Deploying a new build with that checked (as well as "requires full screen"), it rendered exactly the same on our own iPads, but the app was subsequently approved with no further problems.  I had made no other changes to the program, so my assumption is that that setting likely fixed it.


text:
Q: How can I get my Square Connect location without using command line I want to start by saying I have searched extensively, including google, connect.squareup.com, and Stack Overflow and cannot find an answer to my question. I have posed this question to Square support, and (even though I mentioned I could not access command line and have already done the tutorial mentioned below, I was directed to said tutorial and told to use the command line that I can't use. Here's my problem...
I am trying to set up the square connect API on a webserver for a client. On the webserver, I do not have access to command line (or SSH without an additional cost to the client). The only ways I have found to get the location_id requires command line (as far as I can tell). Is there a way to not have to use command line? Or is there another way to put in the required command without command line access?
Here is what I have done so far:
I read somewhere (can't remember where now) that you can install composer locally, use command line on your machine to install the dependencies needed for square-connect, then move all the files to your server. I have done that to get the files on the server.
My file structure looks like this:
payment-portal/
    vendor/
        composer/
        square/
        autoload.php
        composer.json
    composer.json
    composer.lock
    composer.phar
    locations-test.php
    process-card.php
The locations-test.php contains:
<?php
require 'vendor/autoload.php';
$access_token = "ACCESS_TOKEN";
$location_api = new \SquareConnect\Api\LocationApi();
echo $location_api->listLocations($access_token);

Note: ACCESS_TOKEN has been replaced with my personal access token.
Of coarse, if I access this file at mywebpage.com/payment-portal/locations-test.php, I get a blank page.
Also, I am not getting any errors in the error log.
The way to get locations is lined out here.
Under "Retrieving your location IDs." I am OK up until this point, but I cannot use command line in my server to use the code:
php locations-test.php

What are my other options to get the location_id? What am I missing?
Thanks in advance for any help or direction!

A: According the php-sdk you're using for connecting to the square API, the required format for $access_token should be "Bearer YOUR_ACCESS_TOKEN" no just your access token.
/**
 * @param string $authorization The value to provide in the Authorization header of
 * your request. This value should follow the format `Bearer YOUR_ACCESS_TOKEN_HERE`.

Try using this instead and see if it works.
require 'vendor/autoload.php';
$access_token = "Bearer ACCESS_TOKEN";
$location_api = new \SquareConnect\Api\LocationApi();
echo $location_api->listLocations($access_token);

Of course, don't forget to replace the ACCESS_TOKEN part with your own access token.


text:
Q: Trouble computing covariance and variance I want to compute the covariance and the variance of two times series but for some reason, I always get a "NA" answer. My data seems to be fine, they are real numbers without special features. The code looks like this:
> a = cov(dtarussell, dtasp)
> b = var(dtarussell)
> a
>[1] NA
> b
>[1] NA

The vectors I use are excess returns of russell 2000 and s&p 500and they don't have any "NA" value.


text:
Q: Rank of a linear operator.
Let $V$ be a vector space of dimension 3 and  $T $ be a linear operator on  $V $ such that  $T^3=0 $ and $T^2 \neq 0$. The question is to show the rank of $T=2$.

My attempt : As I had no other idea, I tried using proof by contradiction. I succeeded in showing that a rank of 0 or 3 will lead to a contradiction.
Now suppose rank($T$) = 1. Let $\{v_1,v_2,v_3\} $ be a basis of  $V $ and WLOG assume  $\{v_1,v_2\}$ spans the kernel of $T$ and $Tv_3$ spans the range of  $T$. Then I  can show that Range($T^2$) is spanned by $T^2(v_3)$ and rank($T^2$)= 1. I'm completely stuck after this. I'm not even sure this result has any importance. Any hint is appreciated. Thanks.

A: Since we know that $T^3=0$, we know that the null space of $T^3$ contains the image of $T^2$.  Since $T^2\not=0$, we know that $\operatorname{rank}(T^2)\geq 1$.  Since $T^2(v)=T(T(v))$, i.e., $T$ applied to some vector $T(v)$, we know that $\operatorname{rank}(T^2)\leq\operatorname{rank}(T)$.  Therefore, the rank of $T$ is at least one (but you already knew that).
On the other hand, since $T^2\not=0$, there is some vector $v$ so that $T^2(v)\not=0$, but since $T^3(v)=T(T^2(v))=0$, it follows that there is some nonzero vector, i.e., $T^2(v)$ which is mapped to zero by $T$.  This implies that the kernel of $T$ is at least $1$-dimensional.  This implies, by the rank-nullity theorem that the rank of $T$ is at most $2$ (but you already knew that).  If you don't know the rank-nullity theorem, keep a count of free and pivot variables and you'll get the same conclusions.
Now, suppose that the rank of $T$ is $1$.  Then, since $T^2$ has rank $1$ as well, this implies that $T^2$ and $T$ have the same image.  But, since $T$ applied to the image of $T^2$ is zero, then $T$ applied to the image of $T$ is also zero.  But then, $T^2$ is zero, but this contradicts the assumptions.
This shows that the rank of $T$ must be $2$.  To prove that this is even possible, an example would be
$$
\begin{bmatrix}0&1&0\\0&0&1\\0&0&0\end{bmatrix}.
$$


text:
Q: How do you properly address another scripts function? I'm trying to call a function called dieAnim() in one script from another script, called Magnum.
This is in my Fire function in the Magnum script:
if (hit.collider.tag == "Alien1")
{
    Alien.dieAnim();
}

In the Alien script:
public void dieAnim()
{
    Destroy(gameObject);
}

Everytime i try to run this, it says Object reference not set to an instance of an object.

A: To run this more efficiently do
if(hit.collider.CompareTag("Alien1")){
    //either
    Destroy(hit.gameObject);
    //or if there is logic in dieAnim()
    hit.collider.GetComponent<Alien>().dieAnim();
}

The reason your code was not working was because you were calling the dieAnim() function as if it were on a static component. That means you were trying to call it on all scripts basically. You have to have a reference to that instance of the alien that you hit. The CompareTag is just a special function that allows you to compare tags of gameobjects more quickly and efficiently than a string == string comparison.

A: In the above it looks like you're trying to call dieAnim() from the Class name of Alien
You'll want to use
hit.collider.gameobject.GetComponent<desiredcomponent>().dieAnim();

In this you're accessing the instance of the Alien class as a component.
Edit for clarity.
In the editor when you add a script you're adding a new monobehavior. These are attached to a game object as components. So when you want to access one, you have the access the components of the game object.
So in your case to get the other script you need to call get component on your the game object your colliider hit. The tag is also attached to the game object itself

A: Just re-write your code to the following
if (hit.collider.tag == "Alien1")
{
    hit.collider.GetComponent<Alien>().dieAnim();
}

But if the the only thing that dieAnim is doing is destroying the alien that was hit, you don't need to call a function inside of another script for that - that's overkill.
Just do this
if (hit.collider.tag == "Alien1")
{
     Destroy(hit.gameObject);
}


text:
Q: XSLT, sorting, and position() Starting to work with XSLT, that's fun, I like the principal although it will take a little time to get used to. Now... I already ran in a problem which I'm wondering about and maybe someone could enlighten me about it.
I have a set of boxes with a priority. The box with the smaller priority appears first. This works great. However, I'd like to place my boxes in rows and have row 1 & 3 marked as odd, and row 2 marked as even (I'm expected to have many more rows with the real project.)
Thus, I thought I should be able to use the fn:position() function. Unfortunately, the position returned is the one of the original nodes, not the resulting sorted nodes. Is there a way to fix that problem?
There is a sample XSLT that exposes the problem:
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="body">
    <xsl:apply-templates>
      <xsl:sort select="@priority" data-type="number"/>
    </xsl:apply-templates>
  </xsl:template>
  <xsl:template match="body/box">

Box[<xsl:value-of select="count(preceding-sibling::box) + 1" />,<xsl:value-of select="position()"/>] = (<xsl:value-of select="@priority"/>)
  <xsl:copy-of select="title"/>

  </xsl:template>
</xsl:stylesheet>

And there is an example of input. TWO should appear first, then THREE and finally ONE.
<?xml version="1.0"?>

  <box priority="103">
    <title>This is box ONE</title>
  </box>
  <box priority="1">
    <title>This is box TWO</title>
  </box>
  <box priority="12">
    <title>This is box THREE</title>
  </box>

Yet I'd expect position() to be 1, 2, and 3... but this is the output:

Box[2,4] = (1)
  <title>This is box TWO</title>

Box[3,6] = (12)
  <title>This is box THREE</title>

Box[1,2] = (103)
  <title>This is box ONE</title>

The second number inside the Box square brackets is the position(). I was expected 1, 2, 3. But as we can see, we get 4, 6, 2 which is the position of the node in the original document (I'm not too sure why it's x2 though, when I tested with an xsl:for-each tag, it was 2, 3, and 1 instead.)
I tested with xmlpatterns (Qt 4.7) and xsltproc (libxml2, this should use version 1.0, the code is compatible to 1.0) and both return the same numbers.
So... is that a limit of XSLT, or is that a bug in those two XSLT implementations?!
Update May 27, 2012
It was determined that QXmlQuery (xmlpatterns) is a broken parser in that specific case. The position() must be computed using something similar to count(preceding-sibling::box) + 1 instead of the correct index in the running for-each or template sequence.

A: Well you do
<xsl:apply-templates>
  <xsl:sort select="@priority" data-type="number"/>
</xsl:apply-templates>

which is an abbreviation of doing
<xsl:apply-templates select="node()">
  <xsl:sort select="@priority" data-type="number"/>
</xsl:apply-templates>

which processes all kind of child nodes, both the element nodes you seem to be interested in as well as the white space text nodes between elements. So use
<xsl:apply-templates select="box">
  <xsl:sort select="@priority" data-type="number"/>
</xsl:apply-templates>

and you should at least have the position() as 1,2,3, as you want.
For what it's worth, I tested xsltproc on Windows with the stylesheet
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="body">
    <xsl:apply-templates select="box">
      <xsl:sort select="@priority" data-type="number"/>
    </xsl:apply-templates>
  </xsl:template>
  <xsl:template match="body/box">

Box[<xsl:value-of select="count(preceding-sibling::box) + 1" />,<xsl:value-of select="position()"/>] = (<xsl:value-of select="@priority"/>)
  <xsl:copy-of select="title"/>

  </xsl:template>
</xsl:stylesheet>

against the input you posted and the result is
compilation error: file test2012052702.xsl line 2 element stylesheet
xsl:version: only 1.0 features are supported
<?xml version="1.0"?>

Box[2,1] = (1)
  <title>This is box TWO</title>

Box[3,2] = (12)
  <title>This is box THREE</title>

Box[1,3] = (103)
  <title>This is box ONE</title>

so the position is right I think.

A: Can't repro this.
I run your transformation with Saxon 9.1.07 and the result is;

      Box[2,5] = (1)
      <title>This is box TWO</title>

      Box[3,6] = (12)
      <title>This is box THREE</title>

      Box[1,7] = (103)
      <title>This is box ONE</title>

As we see, the positions are correct (still not 1,2,3 -- because white-space-only nodes are also present).
The same result is produced by XQSharp (XmlPrime).
AltovaXML2009 (XML-SPY) produces even this:
<?xml version="1.0" encoding="UTF-8"?>

    Box[2,1] = (1)
      <title>This is box TWO</title>

    Box[3,2] = (12)
      <title>This is box THREE</title>

    Box[1,3] = (103)
      <title>This is box ONE</title>

which means that it uses an XML parser that strips-off white-space-only text nodes.
An improved version of this transformation would exclude white-space-only nodes:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="body">
        <xsl:apply-templates>
          <xsl:sort select="@priority" data-type="number"/>
        </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="box">

      Box[<xsl:value-of select="count(preceding-sibling::box) + 1" />
      <xsl:text>,</xsl:text>
      <xsl:value-of select="position()"/>
      <xsl:text>] = (</xsl:text>
      <xsl:value-of select="@priority"/>)
      <xsl:copy-of select="title"/>

 </xsl:template>
</xsl:stylesheet>

When this transformation is applied against the provided XML document:

    <box priority="103">
        <title>This is box ONE</title>
    </box>
    <box priority="1">
        <title>This is box TWO</title>
    </box>
    <box priority="12">
        <title>This is box THREE</title>
    </box>

the wanted, correct result is produced:

      Box[2,1] = (1)
      <title>This is box TWO</title>

      Box[3,2] = (12)
      <title>This is box THREE</title>

      Box[1,3] = (103)
      <title>This is box ONE</title>

Notes: xsl:strip-space is used to exclude the white-space-only nodes even from being parsed.
Conclusion: The reported result is due either to using a buggy XSLT processor, or to performing a transformation that is different than the provided one.


text:
Q: Is it possible to get scroll-margin-top to work in Safari? I'm using scroll-margin-top on an anchor point to add space for my sticky header, but it is not supported in Safari.
These docs here - https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin point out this bug -

Scroll margin is not applied for scrolls to fragment target or scrollIntoView(), see bug 189265.

Aternate Name Uses the non-standard name: scroll-snap-margin

Is there any way around this bug?

A: This is the only solution I've found so far that works in both Safari and Firefox... Safari-specific selectors. It's not ideal, because using padding in the Safari element limits the styling you can use, but it beats everything I've tried otherwise.

.anchor { scroll-margin-top: 130px; }
.anchor::-webkit-full-page-media, .anchor:future, .anchor:root .safari_only { padding-top: 130px;}

A: I had the same problem with safari, here is my solution:
[id] {
    scroll-margin-top: 3ex;
    outline: 0 none;

    @media screen and (-webkit-min-device-pixel-ratio:0) {
        margin-top: -3ex;
        padding-top: 3ex;
    }
}

A: According to caniuse.com, scroll-margin-top is now supported in safari as well.
But I get a warning in VS Code from the webhint plugin to use scroll-snap-margin-top in order to support Safari 11+. There's also a related article & a stackoverflow question, which mentions the same thing.

You would have to use scroll-snap-margin-top instead of scroll-margin-top and this is because Safari has implemented it as part of the CSS scroll snap module, which means it is only to be used with scroll snap containers.

A: scroll-margin-top indeed seems to work fine in Safari nowadays (tested on IOS). I landed on this topic as I had an issue with it in Safari but found that the references from Mozilla and "CanIuse" mentioned by others in this topic confirm that the later versions of Safari fully support scroll-margin-top.
In my case the issue in Safari was that I had set scroll-margin-top on an element which had "display: inline". Changing that to "display: inline-block" solved the issue. Strangely enough the issue didn't occur on desktop browsers, there it worked already with "display: inline", but for IOS (Safari and Chrome) it needed "display: inline-block".
A very nasty issue to figure out, I hope this helps someone.


text:
Q: Floats subtraction in Python Why is this happening and how do I avoid this issue?
Python 2.7.5 (default, Jun 27 2013, 09:29:43)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>  0.3 - 0.1 - 0.1 - 0.1
2.7755575615628914e-17
>>> 0.3 - 0.3
0.0
>>> 0.3 - 0.2
0.09999999999999998

A:
Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
When the code is compiled or interpreted, your "0.1" is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

What every programmer should know about floating point: Basic Answers
Also, if you're interested in getting around this, check out fixed-point representation. Python seems to have a variety of solutions.


text:
Q: Deleting Objects from Coredata In my app I have a Place entity that contains reviews and featured objects at the minute my app is constantly refreshing these everytime i parse my xml data which is fine however I need to delete the review and featued objects before they are re parsed. My code is as follows and I believe I need to delete the objects in the parseXML method at the top:
-(void)parseXML:(NSString*)xml{

    TBXML * tbxml = [TBXML tbxmlWithXMLString:xml];

    if(tbxml.rootXMLElement){
        [self traverseElement:tbxml.rootXMLElement];

        if(self.tempItem){
            NSLog(@"Ending Application");
           [self configurePlaceChildrenAndSave];
            [self startGeoCodingQueue];
        }
    }

}

-(void)fireGeocoder:(BSForwardGeocoder*)g{
    NSLog(@"Begining FGC for %@ (%@)",g.searchQuery,g.metaData);
    [g findLocation];
}

-(void)startGeoCodingQueue{

  [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:YES] forKey:kGeoCoderInProgress];

    int i = 0;
    BSForwardGeocoder * fgc;

    NSArray * a = [CoreDataBasicService fetchResultsForEnity:@"Place" andSortDiscriptor:@"name" Ascending:YES];

    for (Place * p in a) {

        if(p.latitude && p.longitude)continue;//skip geocoding if location data exists

        fgc = [[BSForwardGeocoder alloc] initWithDelegate:self];
        fgc.metaData = p.name;
        fgc.searchQuery = p.postcode;

        NSLog(@"gc:%i-%i",i,[a count]);
        if([a count] == i+1){
          fgc.last = YES;
        }

        float delay = (float)i*kGeoCoderDelay;
        [self performSelector:@selector(fireGeocoder:) withObject:[fgc autorelease] afterDelay:delay];

        fgc = nil;

        i++;
    }

  [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:i] forKey:kGeoCoderCompletedKey];
}

-(void)finishedGeocoding{

  [[NSUserDefaults standardUserDefaults] setValue:[NSDate date] forKey:kGeoCoderlastRanKey];

  [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO] forKey:kGeoCoderInProgress];

  [[NSNotificationCenter defaultCenter] postNotificationName:kGeoCoderNotificationName object:nil];
}

-(void)forwardGeocoderError:(BSForwardGeocoder *)geocoder errorMessage:(NSString *)errorMessage{
    NSLog(@"EX ERROR: GEOCODER FAILED - %@",errorMessage);

    if(geocoder.last)[self finishedGeocoding];

}

- (void)forwardGeocoderFoundLocation:(BSForwardGeocoder*)geocoder
{
    if(geocoder.status == G_GEO_SUCCESS)
    {
        BSKmlResult *result = [geocoder.results lastObject];

        if(!result)return;

        //[self.fowardGeocodingQueue setObject:[NSString stringWithString:value] forKey:self.tempItem.name];
        Place * p = [CoreDataBasicService fetchPlaceNamed:geocoder.metaData];

        p.latitude = [NSNumber numberWithFloat:result.latitude];
        p.longitude = [NSNumber numberWithFloat:result.longitude];

        [CoreDataBasicService saveChanges];

    //NSLog(@"%@ - %f,%f",p2.name,p2.latitude,p2.longitude);

        NSLog(@"completed Foward geocoding for '%@' (%@) [%f,%f]",geocoder.metaData,geocoder.searchQuery,[p.latitude floatValue],[p.longitude floatValue]);

        if(geocoder.last)[self finishedGeocoding];

    }
    else {

        NSString *message = @"";

        switch (geocoder.status) {
            case G_GEO_BAD_KEY:
                message = @"The API key is invalid.";
                break;

            case G_GEO_UNKNOWN_ADDRESS:
                message = [NSString stringWithFormat:@"Could not find %@", geocoder.searchQuery];
                break;

            case G_GEO_TOO_MANY_QUERIES:
                message = @"Too many queries has been made for this API key.";
                break;

            case G_GEO_SERVER_ERROR:
                message = @"Server error, please try again.";
                break;
            default:
                break;
        }

        NSLog(@"ERROR: GEOCODER FAILED - %@",message);

//      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information"
//                                                      message:message
//                                                     delegate:nil
//                                            cancelButtonTitle:@"OK"
//                                            otherButtonTitles: nil];
//      [alert show];
//      [alert release];
    }
}

-(void)configurePlaceChildrenAndSave{
    if(self.tempReviewArray.count==0 && self.tempReview)[self.tempReviewArray addObject:self.tempReview];

    if(self.tempFeatureArray.count==0 && self.tempFeature)[self.tempFeatureArray addObject:self.tempFeature];

    [self.tempItem setReviews:self.tempReviewArray];
    [self.tempItem setFeatured:self.tempFeatureArray];

    self.tempReviewArray = nil;
    self.tempReview = nil;
    self.tempFeatureArray = nil;
    self.tempFeature = nil;

    [CoreDataBasicService saveChanges];
    self.tempItem = nil;
}

-(NSString*)formatKeyForCoreData:(NSString*)elementKey{
    return [elementKey stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

-(NSDate*)convertStringDateToDate:(NSString*)stringDate{

    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    NSLog(@"DATE:%@",stringDate);
    [df setDateFormat:@"y-M-d'T'H:m:s'Z'"];
    NSDate * d = [df dateFromString:stringDate];
    [df release];
    return d;
}

-(Place*)getPlaceForName:(NSString*)name{
  NSPredicate * pred = [NSPredicate predicateWithFormat:@"name = %@",name];
  NSArray * results = [CoreDataBasicService fetchResultsForEnity:@"Place" WithPredicate:pred andSortDiscriptor:@"identifier" Ascending:YES];
  return [results lastObject];
}

-(void)traverseElement:(TBXMLElement *)element {

    do {
        // Display the name of the element
        NSString * value = [TBXML textForElement:element];
        NSLog(@"%@-'%@'",[TBXML elementName:element],value);
        // Obtain first attribute from element

        NSString * ele = [TBXML elementName:element];

        if([ele isEqualToString:@"place"]){
            if(self.tempItem){
                //GEOCODER HERE
                [self configurePlaceChildrenAndSave];
            }

            //CREATE NEW CD ITEM HER

          if(dataBaseExits){

            TBXMLElement * idElement = [TBXML childElementNamed:@"name" parentElement:element];
            Place * p = [self getPlaceForName:[NSString stringWithFormat:@"%@",[TBXML textForElement:idElement]]];

            if(p){
              [self setTempItem:p];

              TBXMLElement * reviewsElement = [TBXML childElementNamed:@"reviews" parentElement:element];
              if(reviewsElement){
              self.tempItem.reviews = nil;
              [CoreDataBasicService saveChanges];
              [self traverseElement:reviewsElement];
              }

              TBXMLElement * promosElement = [TBXML childElementNamed:@"featured-places" parentElement:element];
              if(promosElement){
                self.tempItem.featured = nil;
                [CoreDataBasicService saveChanges];
                [self traverseElement:promosElement];
              }

              [CoreDataBasicService saveChanges];
              continue;

            }


text:
Q: Redirecting with React-router if user is not authenticated I'm building a React application with React-router and redux, and i have a profile page I want to show at /profile only if the user is authenticated. In my App component's componentWillMount method I am fetching the current user with fetchUser() which uses axios to send a GET request to my Express API. My fetchUser() returns null by default, and returns false or the user object when the request finishes. In my Profile component, I am trying to switch over the user (null, false or user which should be truthy). The problem I am facing is that my switch case gets called before the fetchUser() request comes through, and so the user is null. The following code gets the job done, but chrome throws an error in the console:
render() {
    if (this.props.auth === false) this.props.history.push('/');
    return (

            //Profile page goes here

    )
}

Error thrown by chrome:
Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

Just to clarify: The code works perfectly, but chrome still complains.
I realise this means I need to move my logic from from the render method into componentWillMount or componentDidMount. The problem is that when those lifecycle methods are called, the user object is null, and so that won't work (I've tried). Does anyone have any ideas? Thanks in advance!

A: Adding the logic into the componentDidUpdate() lifecycle method solved the issue:
componentDidUpdate() {
        if (this.props.auth === false) return this.props.history.push('/');
    }
    render() {

        return (

Profile page

                <ProfileForm />

        )
    }
}

A: As you have observed correctly that render method should not contain any logic that is switching the state/rerouting.
If your fetchUser function is asyc then you should only render the component based on the response of fetchUser.
componentWillMount(){
      this.setState({loading:true})
      fetchUser().then( () =>{this.setState({auht:true,loading:false)})
            .catch( ()=>{this.setState({auth:false,loading:false})})
}

now based on this.state.loading you may take some decisions in the render.
Hope this works.


text:
Q: WPF - how to know when all Images in a FlowDocument have been downloaded My scenario: using the MVVM pattern I'm marrying a XAML FlowDocument with a ViewModel, not displaying it on the UI, but converting it to an XPS file.
This mostly works: everything gets rendered properly, including Image's that have an HTTP URL but are relatively small or have already been displayed on the UI (and are therefore cached). The only gotcha is images that are large-ish and take 1-2 seconds to fully download. These are not included in the final file output; no big surprise here. But I need a way to guarantee that the XPS output will include all images, regardless of size or whether they've been cached or not.
Idea #1:
Have some sort of inspection mechanism on the FlowDocument that can find all images and determine if they are in fact downloaded/ready, then when all are good, run the XPS conversion
The problem here is there is even if I were to create some elaborate document inspector, it's not like the Image control has any property indicating it is fully loaded.
Idea #2
Eagerly load all images that I know will be included in the FlowDocument. Once they are in the mysterious WPF image cache, in theory there should be no issue rendering even very large images in the XPS file.
I got pretty far into this approach, and almost got it to work. My issue is that I can't find a reliable way to forego the eager downloading if the image is already cached; there doesn't seem to be a way to test for it being in the cache. Checking the IsDownloading property of BitmapImage doesn't appear to be reliable, as it often will return true even if a given image is already cached.
The ideal solution
would be #1, and setup as an async Task that a client can await until all the images in the FlowDocument are fully realized.


text:
Q: How to install VMware tools for Ubuntu 11.04 hosted on VMware ESXi? I'm running Vmware ESX 4.1 and I have a development VM that I recently upgraded from Ubuntu 10.04 to 11.04. Then I tried to re-install VMware Tools and some of the modules gave me an error and would not compile. As a result I'm having problems with backing up this virtual machine now and I suspect VMware tools is the reason. I installed latest patches for VMware host, that included an update to VMware Tools (v8.3.7 build-381511) but I'm still getting the same error.
The error I'm getting is like this:
...
/tmp/vmware-root/modules/vmhgfs-only/super.c:73:4: error: unknown field \u2018clear_inode\u2019 specified in initializer
make[2]: *** [/tmp/vmware-root/modules/vmhgfs-only/super.o] Error 1
make[1]: *** [_module_/tmp/vmware-root/modules/vmhgfs-only] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-2.6.38-8-generic'
make: *** [vmhgfs.ko] Error 2
make: Leaving directory `/tmp/vmware-root/modules/vmhgfs-only'

and also this:
/tmp/vmware-root/modules/vmci-only/vmci_drv.c:91:4: error: unknown field \u2018ioctl\u2019 specified in initializer
/tmp/vmware-root/modules/vmci-only/vmci_drv.c:91:4: warning: initialization from incompatible pointer type
/tmp/vmware-root/modules/vmci-only/vmci_drv.c: In function \u2018vmci_init\u2019:
/tmp/vmware-root/modules/vmci-only/vmci_drv.c:151:4: error: implicit declaration of function \u2018init_MUTEX\u2019
make[2]: *** [/tmp/vmware-root/modules/vmci-only/vmci_drv.o] Error 1
make[1]: *** [_module_/tmp/vmware-root/modules/vmci-only] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-2.6.38-8-generic'
make: *** [vmci.ko] Error 2
make: Leaving directory `/tmp/vmware-root/modules/vmci-only'

Any ideas?

A: My guess would be that you have the wrong version of the kernel headers. Unless you need some specific feature that is only available in the version of vmware tools you are trying to build (hint: You probably don't) you can save yourself a lot of pain by removing the hand-installed version and use the open-vm-tools package in ubuntu:
sudo aptitude install linux-headers-virtual open-vm-dkms open-vm-tools

It is also possible to pull the latest version of the tools directly from vmware, but then you need to mess a little with apt:
apt-add-repository 'deb http://packages.vmware.com/tools/esx/4.1latest/ubuntu natty main restricted'
wget http://packages.vmware.com/tools/VMWARE-PACKAGING-GPG-KEY.pub -q -O- | apt-key add -
apt-get update
apt-get install vmware-open-vm-tools-kmod-source
module-assistant prepare
module-assistant build vmware-open-vm-tools-kmod-source
apt-get install vmware-open-vm-tools

A: It seems that after migration of our VMware ESXi servers to version 5.0 this problem goes away. Apparently, it was a problem with VMware tools that was eventually fixed by VMware.
Prior to this we were running VMware tools from Ubuntu repository as per @pehrs suggestion and they were working okay with exception that they were shown as "Unmanaged" in VMware vCenter and they cannot be upgraded from VMware vCenter console if new version is available. Instead,  someone would need to login to the Ubuntu machine as root and check for updates. It was a working short term solution though.


text:
Q: Debugging module internals in Chisel I have a complex module written in Chisel. I'm using chiseltest to verify its operation. The test is failing. I want to be able to inspect the module's internal wire values to debug what is going wrong. Since the PeekPokeTester only allows me to inspect the value of the io signals, how can I inspect the internal wires?
Here is an example:
import chisel3._

class MyModule extends Module {
  val io = IO(new Bundle {
    val a = Input(Bool())
    val b = Input(Bool())
    val c = Input(Bool())
    val d = Output(Bool())
  })

  val i = Wire(Bool())
  i := io.a ^ io.b

  io.d := i | io.c
}

import chisel3._
import chisel3.tester._
import org.scalatest.FreeSpec

class MyModuleTest extends FreeSpec with ChiselScalatestTester {
  "MyModule should work properly" in {
    test(new MyModule) { dut =>
      dut.io.a.poke(true.B)
      dut.io.b.poke(false.B)
      dut.io.c.poke(false.B)
      dut.i.expect(true.B)  // This line throws a java.util.NoSuchElementException
                            // : key not found: Bool(Wire in MyModule)
    }
  }
}

How can I inspect the intermediate value "i"?

A: There's a few ways to do this.
1 ) Turn on VCD output by adding an annotation to your test, as in
import chiseltest.experimental.TestOptionBuilder._
import treadle._
...
test(new MyModule).withAnnotations(Seq(WriteVcdAnnotation)) { dut =>

The .vcd file will be placed in the relevant test_run_dir/ you can view it with GtkWave or similar
2 ) add printf statements to your module.
3 ) There is a simulation shell in the Treadle Repo that allows you to peek poke and step based on a firrtl file (the firrtl file should be in the same test_run_dir/ directory as above). There is A bit of documentation here
Good luck!


text:
Q: post can't reach on target with Heroku - Fixie I'm making REST API service with another REST API service.
When I post a request to use external REST API service, the post can't reach on target.
The target host requires static IP address and HTTP protcol, so I use Fixie on Heroku.
I get following messages on heroku.
o.apache.http.impl.execchain.RetryExec   : I/O exception (org.apache.http.NoHttpResponseException) caught when processing request to {tls}->http://xxxxx.usefixie.com:80->https://my-target-host.com:443: The target server failed to respond
o.apache.http.impl.execchain.RetryExec   : Retrying request to {tls}->http://xxxxx.usefixie.com:80->https://my-target-host.com:443 org.apache.http.NoHttpResponseException: my-target-host.com:443 failed to respond

Currentry, the host don't expose access log.
These are my Java code.
Code-A.
HttpPost post = new HttpPost("/action");
HttpHost targetHost = new HttpHost("my-target-host.com",443,"https");
post.setHeader("Content-Type", "application/json; charset=UTF-8");

try{
    URL proxyUrl = new URL(System.getenv("FIXIE_URL"));

    HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort());
    HttpRoutePlanner routePlanner = new HttpRoutePlanner() {

        @Override
        public HttpRoute determineRoute(HttpHost target, org.apache.http.HttpRequest request,
                org.apache.http.protocol.HttpContext context) throws HttpException {
            return new HttpRoute(target, null,  new HttpHost(proxyUrl.getHost(), proxyUrl.getPort()), true);
        }
    };
    try (CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build();) {

        try {
            post.setEntity(new StringEntity(CONTENT_JSON, StandardCharsets.UTF_8));
            CloseableHttpResponse res = httpclient.execute(targetHost,post);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}catch(Exception e){
    e.printStackTrace();
}

Code-B.
HttpPost post = new HttpPost("/action");
HttpHost targetHost = new HttpHost("my-target-host.com",443,"https");
post.setHeader("Content-Type", "application/json; charset=UTF-8");

try{
    URL proxyUrl = new URL(System.getenv("FIXIE_URL"));
    String userInfo = proxyUrl.getUserInfo();
    String user = userInfo.substring(0, userInfo.indexOf(':'));
    String password = userInfo.substring(userInfo.indexOf(':') + 1);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(proxyUrl.getHost(),proxyUrl.getPort()),
            new UsernamePasswordCredentials(user,password));

    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();) {

        HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort());
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        post.setConfig(config);

        String encodedAuth = Base64.getEncoder().encodeToString(userInfo.getBytes());
        post.setHeader("Proxy-Authorization", "Basic " + encodedAuth);

        try {
            post.setEntity(new StringEntity(CONTENT_JSON, StandardCharsets.UTF_8));
            CloseableHttpResponse res = httpclient.execute(targetHost,post);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}catch(Exception e){
    e.printStackTrace();
}

Code-C.
HttpPost post = new HttpPost("/action");
HttpHost targetHost = new HttpHost("my-tareget-host.com",443,"https");

try{
    URL proxyUrl = new URL(System.getenv("FIXIE_URL"));
    String userInfo = proxyUrl.getUserInfo();
    String user = userInfo.substring(0, userInfo.indexOf(':'));
    String password = userInfo.substring(userInfo.indexOf(':') + 1);

    DefaultHttpClient httpclient_ = new DefaultHttpClient();
    try {
      httpclient_.getCredentialsProvider().setCredentials(
            new AuthScope(proxyUrl.getHost(), proxyUrl.getPort()),
            new UsernamePasswordCredentials(user, password));
      HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort());
      httpclient_.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      String encodedAuth = Base64.getEncoder().encodeToString(userInfo.getBytes());

      post.setEntity(new StringEntity(CONTENT_JSON, StandardCharsets.UTF_8));
      post.setHeader("Proxy-Authorization", "Basic " + encodedAuth);

      HttpResponse rsp = httpclient_.execute(targetHost, post);

    } finally {
        httpclient_.getConnectionManager().shutdown();
    }
}catch(Exception e){
    e.printStackTrace();
}

These code cause same result.
On same environment, this ruby code is reached.
RestClient.proxy = ENV['FIXIE_URL'] if ENV['FIXIE_URL']
RestClient.post("https://my-target-host.com/action", CONTENT_JSON, {
  'Content-Type' => 'application/json; charset=UTF-8'
})

What's happend on access? What should I modify on Java?


text:
Q: Is there a power series solution for this ODE with non-recursive coefficients? I am trying to see if the following ODE of $g(x)$ admits a series solution the coefficient of which does not have to be expressed recursively but has a direct and closed expression.
$$g'-\Big(\frac1{x^2}+\frac1x+\frac1{1-x}\Big)g=\Big(\frac x{1-x}\Big)^2-\frac{a_0}{1-x}+(2a_0-a_1)\frac x{1-x}$$
where $x\in(0,1)$, and $a_0$ and $a_1$ are constants.
I multiplied both sides by $e^h=\frac{1-x}xe^{\frac1x}$ where $h(x):=\frac1x+\ln\frac{1-x}x$ and get
$$\frac{d}{dx}\Big(\frac{1-x}xe^{\frac1x}g\Big)=e^{\frac1x}\Big(\frac x{1-x}-\frac{a_0}x+(2a_0-a_1)\Big).$$
The difficulty comes from the factor $e^\frac1x$ which seems to call for special functions for the integration with respect to $x$. Is there a power series expression for $g(x)$ where the coefficients of it is some "closed" expression, special functions such as hypergeometric functions included?


text:
Q: Can Silverlight downloads be zipped to speed up the download? When Silverlight downloads the assemblies in your app can it be made to download them as zipped files and then uncompress them before running? This would speed up the download time for a large application.

A: afaik silverlight 2 xap files are already zip compressed. So unless I misunderstood you there should not be much optimization through compression. (Edit: See other posts and comments on how to optimize through re-compression. Thanks!)
More Info: Structure of the xap file
What you could do is dynamically load additional assemblies after a small "bootstrap" version of your program distracts the user long enough to load the rest. ;)
Dynamically Loading an Assembly

A: The Silverlight 2 .xap file format is already compressed, if you rename it to .zip you'll be able to open it in Windows Explorer for example.
The default compression is not as optimal as it can be however and so there are a few free utilities you can use to reduce the filesize of the .xap often dramatically.
Here are the best links:
http://web-snippets.blogspot.com/2008/11/another-one-on-repacking-xaps-to-reduce.html
http://blogs.msdn.com/delay/archive/2008/11/04/smaller-is-still-better-a-simple-step-continues-to-shrink-the-download-size-of-silverlight-2-applications.aspx
http://blogs.telerik.com/ValeriHristov/Posts/08-05-13/Increasing_the_compression_ratio_of_the_XAP_files.aspx

A: Why don't you enable GZIP compression on your server, this should work for silverlight aswell.


text:
Q: Is the input of `tf.image.resize_images` must have static shape? I run the code below, it raises an ValueError: 'images' contains no shape. Therefore I have to add the line behind # to set the static shape, but img_raw may have different shapes and this line makes the tf.image.resize_images out of effect.
I just want to turn images with different shapes to [227,227,3]. How should I do that?
def tf_read(file_queue):
    reader = tf.WholeFileReader()
    file_name, content = reader.read(file_queue)
    img_raw = tf.image.decode_image(content,3)
    # img_raw.set_shape([227,227,3])
    img_resized = tf.image.resize_images(img_raw,[227,227])
    img_shape = tf.shape(img_resized)
    return file_name, img_resized,img_shape

A: The issue here actually comes from the fact that tf.image.decode_image doesn't return the shape of the image. This was explained in these two GitHub issues: issue1, issue2.
The problem comes from the fact that tf.image.decode_image also handles .gif, which returns a 4D tensor, whereas .jpg and .png return 3D images. Therefore, the correct shape cannot be returned.

The solution is to simply use tf.image.decode_jpeg or tf.image.decode_png (both work the same and can be used on .png and .jpg images).
def _decode_image(filename):
    image_string = tf.read_file(filename)
    image_decoded = tf.image.decode_jpeg(image_string, channels=3)
    image = tf.cast(image_decoded, tf.float32)
    image_resized = tf.image.resize_images(image, [224, 224])

    return image_resized

A: No, tf.image.resize_images can handle dynamic shape
file_queue = tf.train.string_input_producer(['./dog1.jpg'])
# shape of dog1.jpg is (720, 720)

reader = tf.WholeFileReader()
file_name, content = reader.read(file_queue)
img_raw = tf.image.decode_jpeg(content, 3) # size (?, ?, 3)  <= dynamic h and w
# img_raw.set_shape([227,227,3])
img_resized = tf.image.resize_images(img_raw, [227, 227])
img_shape = tf.shape(img_resized)

with tf.Session() as sess:
    print img_shape.eval() #[227, 227, 3]

BTW, I am using tf v0.12, and there is no function called tf.image.decode_image, but I don't think it is important

A: Of course you can use tensor object as size input for tf.image.resize_images.
So, by saying "turn images with different shapes to [227,227,3]", I suppose you don't want to lose their aspect ratio, right? To achieve this, you have to rescale the input image first, then pad the rest with zero.
It should be noted, though, you should consider perform image distortion and standardization before padding it.
# Rescale so that one side of image can fit one side of the box size, then padding the rest with zeros.
# target height is 227
# target width is 227
image = a_image_tensor_you_read
shape = tf.shape(image)
img_h = shape[0]
img_w = shape[1]
box_h = tf.convert_to_tensor(target_height)
box_w = tf.convert_to_tensor(target_width)
img_ratio = tf.cast(tf.divide(img_h, img_w), tf.float32)
aim_ratio = tf.convert_to_tensor(box_h / box_w, tf.float32)
aim_h, aim_w = tf.cond(tf.greater(img_ratio, aim_ratio),
                       lambda: (box_h,
                                tf.cast(img_h / box_h * img_w, tf.int32)),
                       lambda: (tf.cast(img_w / box_w * img_h, tf.int32),
                                box_w))
image_resize = tf.image.resize_images(image, tf.cast([aim_h, aim_w], tf.int32), align_corners=True)

# Perform image standardization and distortion
image_standardized_distorted = blablabla

image_padded = tf.image.resize_image_with_crop_or_pad(image_standardized_distorted, box_h, box_w)
return image_padded


text:
Q: ciclo for para cálculo de uma função Pretendo efectuar um ciclo for mas não está a resultar. Os meus conhecimentos de 'R' ainda são parcos. Pretendo calcular uma função F(y, x) = 1 + y + y^2 + ... + y^x = sum(y^(0:x)).
Escrevi o seguinte código, mas está a dar um resultado que não é o que pretendo. Qual o erro?
> sum <- 1
> for(i in 0:3){
+     for(y in 0:3){
+             sum <- sum + y ^ (i)
+     }
+ }

print( sum )
  [1] 61

A: Seu código está fazendo exatamente o que especificou. Você forneceu um valor de x e um valor de y, e foi esse o resultado retornado:
> 0^0+0
[1] 1

Para usar for, você deve especificar uma sequência, por exemplo:
x <- 3

> for(i in x) print(i+1)
[1] 4

> for(i in 1:x) print(i+1)
[1] 2
[1] 3
[1] 4

Para armazenar os valores, deve ter um objeto de dimensão apropriada para receber o resultado de cada volta, ou terá apenas o último valor:
for(i in 0:x) y = x ^ i + x
> y
[1] 30
# o objeto y teve o valor atualizado a cada volta

y <- rep(NA, x+1)
for(i in 0:x) y[i+1] = x ^ i + x
> y
[1]  4  6 12 30

Mas R é otimizado para operações vetoriais, é melhor evitar loops sempre que possível. Você já chegou na solução quando editou sua questão, apenas não percebeu que era apenas isso:
suaFuncao <- function(y, x) sum(y^(0:x))

> suaFuncao(2, 3)
[1] 15

A: Aqui está um ciclo for bem simples. E a comparação com o resultado da função da resposta do Carlos Eduardo Lagosta.
suaFuncao <- function(y, x) sum(y^(0:x))

suaFuncao2 <- function(y, x){
  s <- 1
  for(k in seq_len(x)) s <- s + y^k
  s
}

suaFuncao(2, 3)
#[1] 15

suaFuncao2(2, 3)
#[1] 15


text:
Q: Orthogonal idempotents with sum equal to 1 in $k[G]$ span sub-Hopf algebra Let $G$ be a finite group. Let $B$ be a set of orthogonal non-zero idempotents with $|B| \leq |G|$, s.t. $\sum_{b \in B}b =1_{kG}$. Is it known if $B$ spans a sub-Hopf algebra $kH \subseteq kG$?

A: In general no. Take for example $G=C_3, e = \frac{1}{|G|}\sum_{g\in G}g$ and $B=\{1-e,e\}$. Then $B$ spans a sub algebra, but not a sub-Hopf algebra. This was a particular example, but for most finite groups $G$ and most sets of idempotents you will not get the group algebra of a subgroup.
In fact, any sub-Hopf algebra which contains $e$ must coincide with $kG$.


text:
Q: Как обновить список Bundle ID в itunesconnect? Когда в itunesconnect выбираю нужный Bundle ID (ID Пакета), в перечне предоставленных нет нужного. Хотя в провижн портале всё нормально.
Как обновить этот список, чтоб выбрать нужный?