Q: Avoiding clashing of events by comparing their time and venues This might be easy for some of you but for me its a big hitch:
What I want to do is make sure two events don't clash by comparing their dates and venues.
Here is what I have done so far:
<?php
    require_once (LIB_PATH.DS.'database.php');
    require_once ('../includes/initialize.php');

    class Event extends DatabaseObject {

        protected static $table_name="event_tbl";

        protected static $db_fields = array('id', 'visible', 'event_title', 'start_date', 'end_date', 'start_time', 'end_time', 'venue', 'event_type', 'event_description', 'event_program', 'reminder_date', 'reminder_time');

        public $id;
        public $event_title;
        public $start_date;
        public $end_date;
        public $start_time;
        public $end_time;
        public $venue;
        public $event_type;
        public $event_description;
        public $event_program;
        public $visible;
        public $reminder_date;
        public $reminder_time;

        public function avoid_clash($time1, $time2, $database_venue, $time3, $time4, $venues) {
        $timeStart = strtotime("{$time1}");
        $timeEnd   = strtotime("{$time2}");
        $time      = strtotime("{$time3}") - strtotime("{$time4}");

        if ($result =($time > $timeStart && $time < $timeEnd) && $database_venue==$venues) {
            $session->message('Warning: This event clashes with another!');
            redirect_to('event_management.php');
        }
    }

    }

    /*function process_avoid_clash($time1, $time2, $time3, $time4, $venues) {
        $event = self::find_from_event();
        $row = fetch_array($event);

        foreach ($row as $rows) {
            $time1 = $rows['start_date']." ".$rows['start_time'];
            $time2 = $rows['end_date']." ".$rows['end_time'];
            $database_venue = $rows['venue'];

            if ($time1 && $time2 && $database_venue) {
                avoid_clash($time1, $time2, $time3, $time4, $venues);
            } else {
                 die("find_from_event failed!");
            }
        }
    }*/

?>

Then this is how I test it by using a form which when submitted will alert the user if two events clashed:
<?php

    require_once ('../includes/initialize.php');

    if(!$session->is_logged_in()) {
        redirect_to("login.php");
    }
?>
<?php
    if (isset($_POST['submit'])) {

        $event = new Event();
        $even = Event::find_public();

                $time3  = $_POST['start_date']." ".$_POST['start_time'];
                $time4  = $_POST['end_date']." ".$_POST['end_time'];
                $venues = $_POST['venue'];

         foreach($even as $events):
                $time1  = $events->start_date." ".$events->start_time;
                $time2  = $events->end_date." ".$events->end_time;
                $database_venue = $events->venue;

                if ($time1 && $time2 && $database_venue) {
                 $event->avoid_clash($time1, $time2, $database_venue, $time3, $time4, $venues);
                }
                endforeach;

        $event-> event_title       = $_POST['event_title'];

        $event-> start_date        = $_POST['start_date'];

        $event-> end_date          = $_POST['end_date'];

        $event-> start_time        = $_POST['start_time'];

        $event-> end_time          = $_POST['end_time'];

        $event-> venue             = $_POST['venue'];

        $event-> event_type        = $_POST['event_type'];

        $event-> event_description = $_POST['event_description'];

        $event-> event_program     = $_POST['event_program'];

        $event-> visible           = $_POST['visible'];

        $event-> reminder_date     = $_POST['reminder_date'];

        $event-> reminder_time     = $_POST['reminder_time'];

        $event->create();
        $session->message('Event successfully created!');
        redirect_to('event_management.php');

    }

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />

<title>New Event</title>

<link rel="stylesheet" type="text/css" href="../anytime/anytime.css"/>

<link href="../assets/css/test_project.css" rel="stylesheet" type="text/css" />

<link href="../assets/css/links.css" rel="stylesheet" type="text/css" media="screen" />

<?php echo output_message($message); ?>

      <form id="form1" name="form1" method="post" action="new_event.php">

            Event Title:

            <input type="text" name="event_title" />

            <input name="start_date" type="text" size="14" id="start_date" value="START DATE"/>

            <input name="start_time" type="text" size="8" id="start_time" value="TIME"/>

            TO

            <input name="end_date" type="text" size="14" id="end_date" value="END DATE"/>

            <input name="end_time" type="text" size="8" id="end_time" value="TIME"/>

            Venue:

            <input type="text" name="venue" />

            Event Type:

            <input type="text" name="event_type" />

            Event Description:

            <textarea name="event_description"></textarea>

            Event Program:

            <textarea name="event_program"></textarea>

            Visible:
            <input name="visible" type="radio" value="0" />
            No
            <input name="visible" type="radio" value="1" />
            Yes

            Reminder:

              <input name="reminder_date" type="text" size="10" id="reminder_date" />

              <input name="reminder_time" type="text" size="10" id="reminder_time"/>

            <input type="submit" name="submit" value="Create Event" />
             <input name="New" type="button" id="New" value="Cancel" onclick="location.href='event_management.php'"/>

      </form>

  <?php include_layout_template('footer.php'); ?>

Any information or suggestion is welcomed.

A: My suggestion would be to push this problem down to your database. PostgreSQL, for example, has great support for this kind of problem as documented in this blog post:

On 7th of December, Tom Lane committed patch by Jeff Davis that adds general exclusion constraints:
  Log Message:
  Add exclusion constraints, which generalize the concept of uniqueness to
  support any indexable commutative operator, not just equality.  Two rows
  violate the exclusion constraint if "row1.col OP row2.col" is TRUE for
  each of the columns in the constraint....This could be used for example for making sure that given room is only reserved by 1 user at any give point in time.

as well as a handy "Temporal" extension (see here for a slide-deck from PgCon 2012 discussing some of its features).


Q: Using dplyr to summarise a running total of distinct factors I'm trying to generate a species saturation curve for a camera trapping survey. I have thousands of observations and do most of my manipulations in dplyr.
I have three field sites, with observation records of different animal species from a number of weeks of trapping. In some weeks there are no animals, in other weeks there may be more than one species. I want to generate a separate figure for each site to compare how quickly new species that are encountered over the sequential weeks of the study. These observations of new species should eventually saturate once the total species diversity has been captured in the area. Some field sites are likely to saturate faster than others.
The problem is that I have not come across a way of counting the number of distinct species to provide a running total by time. A simple dummy dataset is below.
field_site<-c(rep("A",4),rep("B",4),rep("C",4))
week<-c(1,2,2,3,2,3,4,4,1,2,3,4)
animal<-c("dog","dog","cat","rabbit","dog","dog","dog","rabbit","cat","cat","rabbit","dog")
df<-as.data.frame(cbind(field_site,week,animal),head=TRUE)

I can easily generate the number of unique species within each week grouping, e.g.
tbl_df(df)%>%
  group_by(field_site,week) %>%
  summarise(no_of_sp=n_distinct(animal))

But this is not sensitive to the fact that some species are encountered again in subsequent weeks. What I really need is a running count of the different species that counts the unique species per site from week 1 going down through the rows, assuming that the data is sorted by increasing time from the start of the survey.
The cumulative total of species encountered over the course of the study by week in the example for field Site A would be: week 1 = 1 species, week 2 = 2 species, week 3 = 3 species, week 4 = still 3 species.
For site B cumulative total of species would be: week 1 = 0 species, week 2 = 1 species, week 3 = 1 species,week 4 = 1 species, etc...
Any advice would be greatly appreciated.
cheers in advance!

A: I'm making two assumptions:

*

*Site B, week 4 = 2 species, both "dog" and "rabbit"; and

*All sites share the same weeks, so if at least on site has week 4, then all sites should include it. This only drives the mt (empty) variable, feel free to update this variable.

I first suggest an "empty" data.frame to ensure sites have the requisite week numbers populated:
mt <- expand.grid(field_site = unique(ret$field_site),
                  week = unique(ret$week))

The use of tidyr helps:
library(tidyr)

df %>%
  mutate(fake = TRUE) %>%
  # ensure all species are "represented" on each row
  spread(animal, fake) %>%
  # ensure all weeks are shown, even if no species
  full_join(mt, by = c("field_site", "week")) %>%
  # ensure the presence of a species persists at a site
  arrange(week) %>%
  group_by(field_site) %>%
  mutate_if(is.logical, funs(cummax(!is.na(.)))) %>%
  ungroup() %>%
  # helps to contain variable number of species columns in one place
  nest(-field_site, -week, .key = "species") %>%
  group_by(field_site, week) %>%
  # could also use purrr::map in place of sapply
  mutate(n = sapply(species, sum)) %>%
  ungroup() %>%
  select(-species) %>%
  arrange(field_site, week)
# # A tibble: 12 × 3
#    field_site   week     n
#        <fctr> <fctr> <int>
# 1           A      1     1
# 2           A      2     2
# 3           A      3     3
# 4           A      4     3
# 5           B      1     0
# 6           B      2     1
# 7           B      3     1
# 8           B      4     2
# 9           C      1     1
# 10          C      2     1
# 11          C      3     2
# 12          C      4     3


Q: Extract PNG from a PDF file using PyPDF2 and Pillow: not enough image data Using the code I found in this post, which corrects this example code, I'm trying to extract images on all pages of a PDF file. Now I'm getting an error for PNG images (works for JPG) at the second line of this piece (Image.frombytes):
if xObject[obj]['/Filter'] == '/FlateDecode':
    img = Image.frombytes(mode, size, data)
    img.save(imagename + ".png")
    number += 1

This yields ValueError: not enough image data, which seems to occur because data cannot be correctly decoded.

A: The code is incorrect as the PDF files do not embed full PNG images (as opposed to JPEG). The images with FlateDecode filter include only raw image data has been compressed with Flate method.
You have to decompress the data to get the raw image data, convert it to RGB (based on the colorspace defined on the PDF image image) and using the other properties defined on the PDF image object (Width, Height, etc) you can construct a PNG image.


Q: Determine which sets are local attractors and determine global attractors Consider the discrete-time dynamical system on $X=\mathbb R_0^+$ given by iteration of the map $f(x)=x^{1/2}$
I want to determine which of the sets $I_1=\{ 0 \}$, $I_2=\{ 1 \}$, $I_3=[0,1]$ are local attractors and if they are, determine their basin attractors.
$I_1$, $I_2$ and $I_3$ are compact invariant sets.
I then want to find the global attractor.
What I have worked out so far
So, first I have found the flow operator/map operator $S_{n}x$, $n \in \mathbb{N_0}$
to be
$S_{n}x=x^{\frac{1}{2}^n}$
and $\lim_{n \to \infty}S_nx = \lim_{n \to \infty} x^{\frac{1}{2}^n} = 1$
I also know the definition of a local attractor states that
A set $\Omega \subset X$ is called a local attractor if $\Omega$ is
i.) Compact
ii.) Invariant
iii.) There is a neighbourhood $V$ of $\Omega$ which is uniformly attracted by $\Omega$
Also, the Basin of Attraction of Omega is the set $A(\Omega)= \{ x \in X : dist(S_tx,\Omega) \rightarrow 0 \}$
We know $I_1$, $I_2$ and $I_3$ are all compact invariant sets so I just want to determine if there is a there is a neighbourhood $V$ of $\Omega$ which is uniformly attracted by $\Omega$ but I do not understand how to do this.
Similary I know that a global attractor is defined as follows:
A set $\Omega \subset \mathbb R^n$ is called a global attractor, if $\Omega$
is
• compact
• invariant
• attracts the bounded sets B ⊂ X
Again I am confused about how to prove $\Omega$ attracts the bounded sets B ⊂ X.
Any help much appreciated. Many thanks

A: You have shown that for all $x>0$, $\lim_{n\to\infty}S_nx=x^{2^{-n}}=1$. This tells you that $\{1\}$ is a local attractor. If $x=0$ we have $S_nx=0$ for all $n$. This implies that $\{1\}$ is not a global attractor since it does not attract any bounded set containing $0$.
Reasoning like this, you can see that $\{0\}$ is not a local attractor and that $[0,1]$ is a global attractor.


Q: Удалить все теги  из текста Здравствуйте всем.
Есть переменная в PHP-скрипте, содержащая текст, скажем, $comment. Переносы строк в тексте сделаны тегами

, причём тегов этих может быть как одна пара (открывающий - закрывающий), так и несколько (неограниченно пар).
Нужно заменить все эти

 на

 в переменной $comment перед её выводом.

A: Например, функцией str-replace:
$comment = "
" . str_replace("

", "

", $comment) . "
";

Можно добавить строчку, чтобы зачистить пустые абзацы:
$comment = str_replace("

", "", $comment);

A: Что-то вроде этого, наверное, Вам подойдёт:
<?php
    $comment = "TEXT
TEXT 1
 TEXT
 TEXT 2-1
 TEXT 2-2
 TEXT 2-3
 TEXT";
    $count = 0;
    do {
        $comment = preg_replace("/
(.+?)<\/br>/", "
$1
", $comment, -1, $count);
    }
    while ($count > 0);
    echo($comment);
?>

A: $comment = str_replace('
', '
', $commnet);
$comment = str_replace('
', '
', $commnet);
тогда произойдет замена всех тегов.


Q: cannot read property of undefined when trying to read from array object I am writing an jasmine test in angular 8 and getting error cannot read property of undefined. Its trying to read property of array object. I have tried initialising but it doesn't seem to work.
I am trying to initialise component.myData
Test
fit('should update  when acceptSection is called ', () => {
   let updateSpy: jasmine.Spy;
   setupComponent();

   component.myData = [] = ['reviewWindowExpiry'];

   updateSpy = spyOn(component, 'update').withArgs(3).and.returnValue(true);
   component.acceptSection(true);
   expect(updateSpy).toHaveBeenCalled();
});

Component
myData: any;

getNextSectionContent(contentIndex: number) {
    // Get scroll height of agreement
    this.agreementScrollHeight = this.scroll.nativeElement.scrollHeight;

    // Calculate remaining days left on next agreement
    this.hoursUntil = null; // reset this value
    this.daysUntil = differenceInDays(this.myData[contentIndex].reviewWindowExpiry, this.todaysDate);

    if (this.daysUntil < 1) {
      this.hoursUntil = differenceInHours(this.myData[contentIndex].reviewWindowExpiry, this.todaysDate);
      this.daysUntil = null;
    }

    if (this.myData[contentIndex] !== undefined) {
      this.agreementData = this.myData[contentIndex].data;
      this.scroll.nativeElement.scrollTop -= this.agreementScrollHeight;
    } else {
      this.agreementData = 'NO MORE AGREEMENTS!!';
    }
  }

A: You are passing .withArgs(3) to the update function.
Does that set or influence the value of contentIndex? (e.g maybe loops the array 3 times).
As it looks like the array entry is attempting to be retrieved for an index that is not in the array as you only add one item to it.
Does this give you a value?
//contentIndex value is 0
this.myData[0].reviewWindowExpiry

Also think Date.UTC would return a function, try
 component.myData = [{'reviewWindowExpiry': Date.now()}];

To get the numeric millisecond value.


Q: How to change literals of type xsd:date to xsd:dateTime using Python? I have a graph which uses Literals of datatype xsd:date to save dates. However I want to use an .owl version of that graph in a reasoner, and the reasoner only accepts the xsd:dateTime format. Is there any way to change the datatype of my date literals?
I was thinking of using rdflib to get all the date nodes of my graph as such:
for birthday in g.objects(None,URIRef(ns+'hasBirthday')):

and then converting the birthday to xsd:dateTime somehow. But I can't figured out how to do the conversion.
If there was a way to do this in the ontology file, it would also help.

A: You could create a new xsd:dateTime literal based on the original xsd:date literal.
Here is an example if you want to replace the original triples in the graph with new triples with the converted literal as the object:
from rdflib import Literal, URIRef
from datetime import datetime

for s, p, o in g.triples((None, URIRef('hasBirthday', base=ns), None)):
    d = o.toPython()
    g.add((s, p, Literal(datetime(d.year, d.month, d.day))))
    g.remove((s, p, o))


Q: How to change StatusBar font color in wxWidgets? I want to display an error message in red on status bar if a user action results in error. I have tried setting the forground color to red but the it still displays the message in default black font. How do make the font color red on statusbar? I'm using wxWidgets 2.8 on red hat 5.5
Thanks!

A: Found out the answers from wxWidget forum:
this->StatusBar->SetForegroundColour(wxColour(wxT("RED")));
wxStaticText* txt = new wxStaticText( this->StatusBar, wxID_ANY,wxT("Validation failed"), wxPoint(10, 5), wxDefaultSize, 0 );
txt->Show(true);


Q: Is it possible to develop Windows Phone 8 applications using the WP8 SDK on Windows 7 Is there any work around so developers who does not have Windows 8 can develop for windows phone using Windows Phone SDK 8.0?

A: Unfortunately, it is currently not possible to develop for Windows Phone 8 on Windows 7. In the system requirements of Windows Phone 8 SDK it states you need to have Windows 8 to develop Windows Phone 8 apps.
Directly from MSDN:

Windows Phone SDK 8.0 requires 64-bit Windows 8 Pro or higher. You can't develop Windows Phone 8 apps on Windows 7, on Windows Server 2008, or on Windows Server 2012. The Windows Phone 8 Emulator has special hardware, software, and configuration requirements. For more info, see System requirements for Windows Phone Emulator.

This is mainly because of the Hyper-V emulator that is in windows 8. Be sure if you buy Windows 8 you get the Pro (64bits) version because the normal version has no Hyper-V in it also your BIOS has to support virtualization to run the emulator in Hyper-V.


Q: Pandas: Re-indexing after picking those that meet a condition I'm trying to learn more about re-indexing.
For background context, I have a data frame called sleep_cycle.
In this data frame, the columns are: Name, Age, Average sleep time.
I want to pick out only those who's names begin with the letter 'B'.
I then want to re-index these 'B' people, so that I have a new data frame that has the same columns, but only has those who's name begins with B.
Here was my attempt to do it:
    info = list(sleep_cycle.columns) #this is just to set a list of the existing columns
    b_names = [name for name in sleep_cycle['name'] if name[0] == 'B']

    b_sleep_cycle = sleep_cycle.reindex(b_names, columns = info) #re-index with the 'B' people, and set columns to the list I saved earlier.

Results: Re-indexing was succesful, managed to pick those who only began with the letter 'B', and the columns remained the same. Great! Problem was: All the data has been replaced with NaN.
Can someone help me with this one? What am I doing wrong? It would be best appreciated if you could suggest a solution that is only in one line of code.

A: Based on your description (example data and expected output would be better), this would work:
sleep_cycle[sleep_cycle['name'].str.startswith['B']]


Q: setsockopt() equivalent for non-socket file descriptors? Is anyone aware of an equivalent to setsockopt() that works on non-socket based file descriptors?
Specifically, consider this block of  code:
int on = 1;
setsockopt(socketfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(int));

All fine and dandy, and now we can avoid SIGPIPE and refer to EPIPE when writing instead. But this only works on socket file descriptors opened with accept(), socket(), etc.
I'm trying to gain similar functionality for a file descriptor opened by a pipe() call, which setsockopt() promptly rejects as being a non-socket file descriptor.
Is there an equivalent to the above (setsockopt()) for descriptors opened by pipe() or open()?

A: There is no equivalent, but you could use socketpair to create a Unix socket instead.

A: If your ultimate goal is to avoid signals altogeather, you can use init and cleanup functions as described here
Also see good example here:
Automatically executed functions when loading shared libraries
Just write an init function that handles the signals you wish to avoid and every program that loads your library will automatically have your handlers
I must say this is a strange necessity though, can you be more specific about the actual problem you're trying to solve?


Q: deprecation errors when running rspec tests after updating to rails 5.0.0 I just upgraded an application from rails 4 to rails 5.0.0, however now when running my rspec tests I'm getting these deprecation warnings (they don't show up when running my server):
DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at /Users/Documents/app/config/environment.rb:5)
DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at /Users/Documents/app/config/environment.rb:5)
DEPRECATION WARNING: after_filter is deprecated and will be removed in Rails 5.1. Use after_action instead. (called from <top (required)> at /Users/Documents/app/config/environment.rb:5)

The alias_method_chain warning does show up twice. I'm not using neither alias_method_chain or after_filter in any of my code.
The gems are using for the test enviroment:
group :development do
  gem 'dotenv-rails', '2.1.1'
  gem 'byebug', '9.0.5'
  gem 'bullet', '5.2.0'
  gem 'bundler-audit', '0.5.0'
  gem 'spring', '1.7.2'
  gem 'web-console', '3.3.1'
  gem 'guard-rspec', '4.7.3'
end

group :test do
  gem 'capybara', '~> 2.1'
  gem 'poltergeist', '1.10.0'
  gem 'formulaic', '0.3.0'
  gem 'rspec-rails', '3.5.1'
  gem 'rspec-mocks', '3.5.0'
  gem 'shoulda-matchers', '3.1.1'
  gem 'timecop-console', '0.1.0'
  gem 'database_cleaner', '1.5.3'
  gem 'simplecov', '0.12.0'
  gem 'rails-controller-testing', '0.1.1'
end

group :development, :test do
  gem 'pry-rails', '0.3.4'
  gem 'factory_girl', '4.7.0'
  gem 'faker', '1.6.6'
  gem 'jasmine', '2.4.0'
  gem 'jasmine-ajax', '0.0.2'
end

I'm not using versions in my gemfile, I just included the current versions I'm using. Any clues of what's causing the deprecation warnings?
EDIT:
I found where the warnings are coming from, I'm using wicked_pdf, here's the issue
It seems it's been fixed, but I'm getting the deprecation warnings still even though I'm using the last version

A: The warnings were caused by the wicked_pdf gem, updating to version 1.1.0 solved the issue


Q: Why cannot marshal struct with auto layout I encountered an odd behaviour when marshalling a struct with auto layout kind.
For example: let's take a simple code:
[StructLayout(LayoutKind.Auto)]
public struct StructAutoLayout
{
    byte B1;
    long Long1;
    byte B2;
    long Long2;
    byte B3;
}
public static void Main()
{
    Console.WriteLine("Sizeof struct is {0}", Marshal.SizeOf<StructAutoLayout>());
}

it throws an exception:

Unhandled Exception: System.ArgumentException: Type
  'StructAutoLayout' cannot be marshaled as an unmanaged
  structure; no meaningful size or offset can be computed.

So it means that compiler doesn't know struct size at compile time? I was sure that this attribute reorders struct fields and then compiles it, but it doesn't.

A: It doesn't make any sense. Marshalling is used for interop - and when doing interop, the two sides have to agree exactly on the structure of the struct.
When you use auto layout, you defer the decision about the structure layout to the compiler. Even different versions of the same compiler can result in different layouts - that's a problem. For example, one compiler might use this:
public struct StructAutoLayout
{
    byte B1;
    long Long1;
    byte B2;
    long Long2;
    byte B3;
}

while another might do something like this:
public struct StructAutoLayout
{
    byte B1;
    byte B2;
    byte B3;
    byte _padding;
    long Long1;
    long Long2;
}

When dealing with native/unmanaged code, there's pretty much no meta-data involved - just pointers and values. The other side has no way of knowing how the structure is actually laid out, it expects a fixed layout you both agreed upon in advance.
.NET has a tendency to make you spoiled - almost everything just works. This is not the case when interoping with something like C++ - if you just guess your way around, you'll most likely end up with a solution that usually works, but once in a while crashes your whole application. When doing anything with unmanaged / native code, make sure you understand perfectly what you're doing - unmanaged interop is just fragile that way.
Now, the Marshal class is designed specifically for unmanaged interop. If you read the documentation for Marshal.SizeOf, it specifically says

Returns the size of an unmanaged type in bytes.

And of course,

You can use this method when you do not have a structure. The layout must be sequential or explicit.
The size returned is the size of the unmanaged type. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.

If the type can't possibly be marshalled, what should Marshal.SizeOf return? That doesn't even make sense :)
Asking for the size of a type or an instance doesn't make any sense in a managed environment. "Real size in memory" is an implementation detail as far as you are concerned - it's not a part of the contract, and it's not something to rely on. If the runtime / compiler wanted, it could make every byte 77 bytes long, and it wouldn't break any contract whatsoever as long as it only stores values from 0 to 255 exactly.
If you used a struct with an explicit (or sequential) layout instead, you would have a definite contract for how the unmanaged type is laid out, and Marshal.SizeOf would work. However, even then, it will only return the size of the unmanaged type, not of the managed one - that can still differ. And again, both can be different on different systems (for example, IntPtr will be four bytes on a 32-bit system and eight bytes on a 64-bit system when running as a 64-bit application).
Another important point is that there's multiple levels of "compilation" in a .NET application. The first level, using a C# compiler, is only the tip of the iceberg - and it's not the part that handles reordering fields in the auto-layout structs. It simply marks the struct as "auto-layouted", and it's done. The actual layouting is handled when you run the application by the CLI (the specification is not clear on whether the JIT compiler handles that, but I would assume so). But that has nothing to do with Marshal.SizeOf or even sizeof - both of those are still handled at runtime. Forget everything you know from C++ - C# (and even C++/CLI) is an entirely different beast.
If you need to profile managed memory, use a memory profiler (like CLRProfiler). But do understand that you're still profiling memory in a very specific environment - different systems or .NET versions can give you different results. And in fact, there's nothing saying two instances of the same structure must be the same size.


Q: Question on Reeb's theorem. I am reading through the first couple of chapters of Milnor's Morse theory, and I've gotten to Reeb's sphere theorem (theorem 4.1),

If $M$ is a compact manifold and $f$ is a differentiable function on $M$ with only two critical points, both of which are nondegenerate, then $M$ is homeomorphic to a sphere.

Milnor states that for some small enough $\varepsilon > 0$, the sublevel sets $f^{-1}[0,\varepsilon]$ and $f^{-1}[1-\varepsilon,1]$ are closed $n$-cells, which follows by the Morse Lemma. But I don't quite follow this. I've read other related posts, but none of them quite flesh out why we need a "small enough" $\varepsilon$, or why exactly the Morse lemma implies that the aforementioned preimages are closed $n$-cells.
Now, I understand that the two critical points will have index $0$ and $1$, which correspond to the minimum and maximum, but why does applying the coordinate maps given to us my the Morse lemma tell us that we get $n$-cells, and not only containments? If anyone could clarify, that would be great.

A: The neighborhood of a critical point where Morse Lemma applies is not necessarily a disk, but it contains a, (sufficiently small radius) closed disk.
Suppose that $p$ is a minimum of $f$ with $f(p)=0$. By Morse Lemma, there is a coordinate system $(U,y^i)$ of $p$ such that $y^i(p) = 0$ for all $ i=1,\dots,n$ and $f$ has representation
$$
f = (y^1)^2 + \dots + (y^n)^2, \quad \text{on }U.
$$
So, for sufficiently small $\varepsilon>0$ we have $D \equiv f^{-1}[0,\varepsilon] \subseteq U$. That is
$$
D = \{q \in U \, \mid \, f(y_q) = (y^1_q)^2+ \dots + (y^n_q)^2 \leq \varepsilon \},
$$
which is clearly diffeomorphic to a closed $n$-disk in $\mathbb{R}^n$, via coordinate map $y$.


Q: Unable to cast object of type 'System.DBNull' to type 'System.String'. I have a problem at hand here that I can't seem to figure out. I have this Button which fires a OnClick. On this event I'm calling a stored procedure in the SQL server. Before creating a new record I have a check in place to see if the already exist. If it does then I'm outputting an error. This part works fine but when record doesn't exist I get this error in ASP.NET:
"Unable to cast object of type 'System.DBNull' to type 'System.String'."
Any help would be really appreciated
protected void createloctype_Click(object sender, EventArgs e)
{
    con.Open();
    cmd = new SqlCommand("sp_CREATE_LOCATION_TYPE", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@lt_code", SqlDbType.VarChar, 2).Value = loctype.Text;
    cmd.Parameters.Add("@lt_description", SqlDbType.VarChar, 50).Value = loctypedescription.Text;
    cmd.Parameters.Add("@lt_putaway_zone", SqlDbType.VarChar, 5).Value = putaway_zone_txt.Text;
    cmd.Parameters.Add("@lt_rule1", SqlDbType.VarChar, 5).Value = rule1_txt.Text;
    cmd.Parameters.Add("@lt_rule2", SqlDbType.VarChar, 5).Value = rule2_txt.Text;
    cmd.Parameters.Add("@lt_rule3", SqlDbType.VarChar, 5).Value = rule3_txt.Text;
    cmd.Parameters.Add("@lt_rule4", SqlDbType.VarChar, 5).Value = rule4_txt.Text;
    cmd.Parameters.Add("@lt_rule5", SqlDbType.VarChar, 5).Value = rule5_txt.Text;
    cmd.Parameters.Add("@lt_misc1", SqlDbType.VarChar, 500).Value = misc1_txt.Text;
    cmd.Parameters.Add("@lt_misc2", SqlDbType.VarChar, 500).Value = misc2_txt.Text;
    cmd.Parameters.Add("@lt_misc3", SqlDbType.VarChar, 500).Value = misc3_txt.Text;
    cmd.Parameters.Add("@lt_misc4", SqlDbType.VarChar, 500).Value = misc4_txt.Text;
    cmd.Parameters.Add("@lt_misc5", SqlDbType.VarChar, 500).Value = misc5_txt.Text;
    cmd.Parameters.Add("@lt_user", SqlDbType.VarChar, 10).Value = user;
    cmd.Parameters.Add("@error", SqlDbType.VarChar, 250);
    cmd.Parameters["@error"].Direction = ParameterDirection.Output;
    cmd.ExecuteNonQuery();
    message = (string)cmd.Parameters["@error"].Value;

    error_message.Text = message;

    con.Close();

}

/STORED PROCEDURE/
USE [1_WMS]

GO

ALTER PROCEDURE [dbo].sp_CREATE_LOCATION_TYPE
@LT_CODE VARCHAR(5)
, @LT_DESCRIPTION VARCHAR(250)
, @LT_PUTAWAY_ZONE VARCHAR(5)
, @LT_RULE1 VARCHAR(5)
, @LT_RULE2 VARCHAR(5)
, @LT_RULE3 VARCHAR(5)
, @LT_RULE4 VARCHAR(5)
, @LT_RULE5 VARCHAR(5)
, @LT_MISC1 VARCHAR(20)
, @LT_MISC2 VARCHAR(20)
, @LT_MISC3 VARCHAR(20)
, @LT_MISC4 VARCHAR(20)
, @LT_MISC5 VARCHAR(20)
, @LT_USER VARCHAR(20)
, @ERROR VARCHAR(250) OUT

AS
DECLARE
    @LT_DATE VARCHAR(10)
    , @LT_TIME VARCHAR(8)
    , @LT_ROW_COUNT INT

SET @LT_DATE = CONVERT(VARCHAR(10), GETDATE(),101)
SET @LT_TIME = CONVERT(VARCHAR(8), GETDATE(),114)

/* CHECK FOR EXISTING */
SELECT @LT_ROW_COUNT = COUNT(*)
    FROM LOC_TYPE(NOLOCK)
WHERE lt_code = @LT_CODE

/*  */
IF @LT_ROW_COUNT = 0
    BEGIN
        INSERT INTO LOC_TYPE
            (
                lt_code             , lt_description            , lt_putaway_zone               , lt_rule_1
                , lt_rule_2         , lt_rule_3                 , lt_rule_4                     , lt_rule_5
                , lt_misc1          , lt_misc2                  , lt_misc3                      , lt_misc4
                , lt_misc5          , lt_created_date           , lt_created_time               , lt_created_by
                , lt_modify_date    , lt_modify_time            , lt_modify_by
            )
            VALUES
            (
                @LT_CODE            , @LT_DESCRIPTION           , @LT_PUTAWAY_ZONE              , @LT_RULE1
                , @LT_RULE2         , @LT_RULE3                 , @LT_RULE4                     , @LT_RULE5
                , @LT_MISC1         , @LT_MISC2                 , @LT_MISC3                     , @LT_MISC4
                , @LT_MISC5         , @LT_DATE                  , @LT_TIME                      , @LT_USER
                , @LT_DATE          , @LT_TIME                  , @LT_USER
            )
    END

ELSE IF @LT_ROW_COUNT = 1
    BEGIN

        SET @ERROR = 'LOCATIOIN TYPE ALREADY EXIST'

        EXEC sp_CREATE_ERROR_MESSAGE
            'CRT_LTY'       , @ERROR            , @LT_CODE          , @LT_PUTAWAY_ZONE
            , @LT_RULE1     , @LT_RULE2         , @LT_RULE2         , @LT_RULE3
            , @LT_RULE4     , @LT_RULE5         , ''                , ''
            , @LT_USER
    END

GO

A: Try the short version of IF
var result = cmd.Parameters["@error"].Value;
message = (result == DBNull.Value) ? string.Empty : result.ToString();

or simply
var result = cmd.Parameters["@error"].Value;
message = (result == DBNull.Value) ? string.Empty : result.ToString();

or
var result = cmd.Parameters["@error"].Value;
message = ((result == DBNull.Value) || (result == DBNull.Value)) ? string.Empty : result.ToString();

A: A shorter alternative:
message = cmd.Parameters["@error"].Value as string ?? "";


Q: Node Express: axios shows Request failed with status code 404, even if the request was completed(failed to redirect) I am using axios to send a post / put request to a Express route.
put
const handleSubmit = async (e) =>
    {
        e.preventDefault();
        const data = new FormData(e.currentTarget);

        const body = {
            title: data.get('title'),
            description: data.get('description'),
        };

        await axios.put(`${process.env.NEXT_PUBLIC_DR_HOST}/view/${_id}`, body)
    };
    //example link: http://localhost:3000/view/61e038051b755034d31d49a2

put route
router.put("/:id", async (req, res) =>
{
    const { id } = req.params;
    await Declaration.findByIdAndUpdate(id, req.body)
    res.redirect("/")
})

post
const handleSubmit = async (e) =>
    {
        e.preventDefault();
        const data = new FormData(e.currentTarget);

        const body = {
            title: data.get('title'),
            description: data.get('description'),
        };

        await axios.post(process.env.NEXT_PUBLIC_DR_HOST, body)
    };

post route
router.post('/', async (req, res) =>
{
    const declaration = new Declaration({ ...req.body })
    await declaration.save();
    res.redirect("/")
})

Now, when submitting to the put form, It displays this error: Unhandled Runtime Error
Error: Request failed with status code 404, but the request was actually cmopleted and the model saved, even if the redirect never happened and the error page remained. When submitting to the post form, No Error, and similar to the first, the request was completed but no redirect, and the form page remains the same. So how can I fix this?

A: using axios
  await axios.post(process.env.NEXT_PUBLIC_DR_HOST, body)
        .then((res) =>
        {
            window.location = res.request.responseURL;
        })


Q: How many Functions/ Bijections X → X do exist, if the set X has 4 elements? So I belive the amount of functinos is $4^4$. But I can't seem to find the right explaination to prove it.
My idea was, that
$a\mapsto a,b,c,d$
$b \mapsto a,b,c,d$
...
...
are the possible ways the elements are related.
... and if you change/exclude the diffrent elements you get to $4^4$. But I know that this is not a real prove and I can't seem to find one.
And the amount of bijections is $4!$. Because the defintions of bijection is that one element can't be related to a diffrent amount of elements, than exactly one element.
Would you have suggestions how you could do that

A: $X=\{a,b,c,d\}$.
We search the number of functions $f: X\to X$.
Note that every element of $X$ has exactly one value $f(x)$ under $f$.
For every $x\in X$ there are four possibilities to choose $f(x)$. Therefore there are $4\cdot 4\cdot 4\cdot 4=4^4$ different functions $f: X\to X$.
Now we want to obtain the number of bijective functions $f:X\to X$.
Note that every element in $X$ has to be mapped on exactly once.
For the first value $x_1$ we have 4 possibilities to choose the image $f(x_1)$.
For the second value $x_2$ we have 3 possibilities to choose the image $f(x_2)$, since $f$ has to bijectiv and we can not map onto the same value more then once.
We get $4!=4\cdot 3\cdot 2\cdot 1$ possible bijective functions.

A: Suppose $X = \{a,b,c,d\}$. Consider a bijection $f\colon X \rightarrow X$. You are looking for all the possible combinations of $f(a),f(b),f(c),f(d)$. Start with $f(a)$. You have $4$ possibilities for it, i.e. $a,b,c$ or $d$. Now $f(a)$ is fixed, so $f(b)$ will have to be different from $f(a)$ in order for $f$ to be injective. Then $f(b)$ can be chosen in $3$ ways. Similarly, $f(c)$ can be chosen in $2$ ways and $f(d)$ is then forced to be the only remaining element in $X$.
To sum up, you got $4$ possibilities for $f(a)$, and for each of them $3$ possibilities for $f(b)$, then again $2$ for $f(c)$ and $1$ for $f(d)$. Hence $4 \cdot 3 \cdot 2 \cdot 1 = 4!$ possibilities.


Q: How to check the length of each child in a list and conditionally apply a class to the children of another I've been searching and searching for the solution to this, but I'm quite new to javascript and I must be missing something obvious.
What I'm trying to do is check each nth-child li by number to see whether they're empty or not, and, if they do contain something, add a class to the corresponding nth-child of another element.
This is what I've ended up at:
if ($('#availList ul li:nth-child(1)').text().length > 0){
$('map area:nth-child(1)').addClass("areaSold");
}

While firebug doesn't have any syntax errors, it doesn't seem to matter if the li is empty or not, because the class will always be applied.
I must be doing something thoroughly dense.
UPDATE:
jsfiddle.net/filmcryptic/ed8LF/1
This actually works as intended... Which means that something is messing up on the site:
Gah.
UPDATE 2:
It works! Thanks blender_noob!

A: I have created a jsFiddle below. Based on my understanding on your question, you want to add a class to the li if it contains a certain text on it. Please update me if this answers your question. Thanks
$(function(){
  $('#availList li').each(function(i,val){
     if($(this).text() == "Area Sold"){
       $('#mapArea li:nth-child('+(i+1)+')').addClass('areaSold');
     }else{
       $('#mapArea li:nth-child('+(i+1)+')').addClass('notSold');
     }
  });
});

Check sample here:
http://jsfiddle.net/tBLhN/


Q: React-sound doesn't work on mobile I use the npm package 'react-sound' - it's fine and easy to configurate. But! It doesn't work on mobile devices. I tested that on android phones and iPad.
Maybe someone had the same problem, or idea how to resolve this?

A: By default, a restriction on mobile prevent you from playing multiple sounds. To avoid this, you need to set the ignoreMobileRestrictions property to true when setting up soundManager2.


Q: Safe Calls in Kotlin with Array is confuse There is an array: notes: Array<KeyValueNote>? and I use the Kotlin 1.0.5-2 in the following code.
I want
if (notes != null) {
    for (note in notes) {
        // Put the note to the payload Json object only if the note is non-null.
        payloadJson.put(note.key, note.value)
    }
}

But there are several alternations
    // Alternative 1.
    notes?.let {
        it.takeWhile { it != null /** Inspection will note The condition 'it != null' is always true' in here**/ }.forEach { payloadJson.put(it.key, it.value) }
    }

    // Alternative 2.
    notes?.takeWhile { it != null /** Inspection will note The condition 'it != null' is always true' in here**/ }?.forEach { payloadJson.put(it.key, it.value) }

    // Alternative 3.
    notes?.filterNotNull()?.forEach { payloadJson.put(it.key, it.value) }

My Question

*

*You can see there is Inspection Note The condition 'it != null' is always true in the Alternative 1&2, whether the inspection is right? because I want to ensure only the non-null item in the notes can be put to the payloadJson.

*In Alternative 3, you can see there is a Safe Call in filterNotNull()?., whether the ? is needed in here?, because I review the source code, the result of the filterNotNull() can't be null, but when I remove ? in there, the compile is failed.

A: Inspection is right. You declare your notes variable to be nullable array of not nullable items.
notes: Array<KeyValueNote>? // Can be null, cannot contain nulls.
notes: Array<KeyValueNote?> // Cannot be null, can contain nulls.

With this in mind, filterNotNull()?. is necessary for this array because it is nullable. You can find more information on Kotlin null safety in Kotlin documentation.

A: The type of notes is Array<KeyValueNote>?, which means that the elements of the array can not be null, but the array itself can. Thus, your code in the "I want" section is correct. A shorter alternative for it would be:
notes?.forEach { payloadJson.put(it.key, it.value) }

About your alternatives:

*

*Alternative 1: Never use let like this. It should be a safe call ?. (like in Alternative 2), nothing else. My heart bleeds when I see let in those situations :(

*Alternative 2: takeWhile and filter are obviously not the same thing. I guess you wanted filterNotNull, like in the Alternative 3

*Alternative 3: Since the elements of the array can NOT be null (because of their type), filterNotNull is equivalent to toList since it just copies the content

A: I guess you're confused by it parameter used in different scopes. The first alternative can be rewritten as:
notes?.let { notesSafe:Array<KeyValueNote> -> // notesSafe is not null here
    notesSafe
      .takeWhile { item:KeyValueNote -> item != null } // item is already not null by it's type definition
      .forEach { payloadJson.put(it.key, it.value) }
}

The second alternative is pretty much the same and the compiler note about item:KeyValueNote is true for the same reason: val items:Array<KeyValueNote>? cannot hold null values - but the items itself could be null.
The 3rd alternative has a safe call to filterNotNull which returns source collection with null values removed. However as mentioned Array<KeyValueNote> cannot have null values in it hence the filterNotNull is not required.
In conclusion the expression can be written as:
notes?.forEach { payloadJson.put(it.key, it.value) }


Q: How do I unravel apparent recursion in an edef statement? The text book that I'm writing requires the ability to dynamically build an alphabetically sorted list. As to not invoke the overhead of high powered, general purpose packages, I have opted instead to write my own, which is both fun and instructive.
Any alphabetic sorting routine must use a sort key to determine the sorted position in the list of the current phrase by comparing its sort key with key of each of other phrases in the list. That routine implements the desired sorting rules such as ignore case, numbers, spaces and punctuation marks for example, as well as strip out any embedded formatting commands which include font and font family changes and accent (diacritical) marks (zap the accent, keep the character). This routine will not only drop characters (spaces and punctuation, etc.), but could directly alter the character itself, such as changing its case for example. One way to accomplish all these tasks is to march through the phrase being sorted character by character, applying these rules to each character individually, and finally build the key by appending the resulting character to the string of already processed characters. It is this last step, appending a character to a string, that is the basis of this question.
I have implemented this appending process using a (global) \edef statement as shown in the \appendChar macro in the following MWE:
\documentclass{article}

\usepackage[svgnames]{xcolor}% to get named colors

\def\RLp{{\color{Red}\tt(}} \def\RRp{{\color{Red}\tt)}}% (input)
\def\RLb{{\color{Red}\tt[}} \def\RRb{{\color{Red}\tt]}}% [output]

\gdef\ttt{\tt\char92}% A better \tt \textbackslash

\def\appendChar#1{% Append argument character to string
  \global\edef\resultStr{\resultStr#1}%
  \par{\tt~\RLp#1\RRp~~~\RLb\resultStr\RRb}\par%
}

\def\testAppendOne#1{% Use counter and \chardef; FAILS
  \newcount\chNum \chNum=\numexpr(`#1)%
% Do arithmetic on the counter to implement the sorting rules
  \chardef\myCh=\chNum%
  \appendChar{\char\myCh}%
}

\def\testAppendTwo#1{% Use counter, \chardef and \the ; WORKS
  \newcount\chNum \chNum=\numexpr(`#1)%
% Do arithmetic on the counter to implement the sorting rules
  \chardef\myCh=\chNum%
  \appendChar{\char\the\myCh}%
}

\def\testAppendThree#1{% Bypass \chardef, WORKS
  \newcount\chNum \chNum=\numexpr(`#1)%
% Do arithmetic on the counter to implement the sorting rules
  \appendChar{\char\the\chNum}%
}

\def\useMacro#1{% Calls macro #1{<character>}
  \global\edef\resultStr{}% (Re)initialize to empty string:
  \medskip
  \par{\tt\RLp chr\RRp~~\RLb\ttt resultStr\RRb}\par
  #1{a}% Simulate character data from string parsing macro
  #1{b}%
  #1{c}%
  #1{d}%
  #1{e}%
  \medskip
}

\begin{document} %               B E G I N   D O C U M E N T

% Proof of principle of using \edef to rebuild a string
\noindent{\Large\bf\color{Blue}Using {\ttt resultStrAppend}:}
\useMacro{\appendChar}

% First attempt fails with apparent recursion
\bigskip\noindent{\Large\bf\color{Blue}Using {\ttt testAppendOne}:}
\useMacro{\testAppendOne}

% Second attempt: adding \the command eliminates recursion
\bigskip\noindent{\Large\bf\color{Blue}Using {\ttt testAppendTwo}:}
\useMacro{\testAppendTwo}

% Third (final) macro: don't need the \chardef, have working macro
\bigskip\noindent{\Large\bf\color{Blue}Using {\ttt testAppendThree}:}
\useMacro{\testAppendThree}

\end{document} %                 E N D   D O C U M E N T

We call the \appendChar macro four different ways:

*

*Using \appendChar: First we call \appendChar directly to provide a "proof of principle" of using an \edef statement to (re)construct a string with what at first appears to be recursion, but clearly is not as seen in the screenshot.

*Using \testAppendOne: This processes the input character using the \chNum counter and a \chardef statement prior to passing it to \appendChar. The resulting string, \resultStr, is completely wrong. After the nth character, all n characters in \resultStr have been changed into the character just input! This certainly looks like recursion, but is it, really?

*Using \testAppendTwo: This macro is identical to \testAppendOne except for the addition of the \the command to the call to \appendChar. We find that this stops the "recursion" and generates the correct result.

*Using \testAppendThree: After some experimentation, it was found that the \chardef was not needed. This is the final, working macro.

Item 2 above is the heart of this question. Even though I have a working solution to the append process, the odd behavior of the \testAppendTwo macro caught my attention and I sought to understand what was happening. I have been unsuccessful. Hence, my question is:
What, exactly, is happening in the \testAppendOne macro? I'm not only interested in a description of what's happening, but also please describe what steps I should take to unravel this behavior for myself.
I suspect that would include using some of the \tracing... macros, but I have not found a usable description of how to use these macros, vs. what they do, and even that is very sketchy.

A: First some general comments about your code:
In LaTeX use \bfseries instead of \bf and \ttfamily instead of \tt. The 2-letter font changing commands are obsolete since LaTeX2ε was released more than 20 years ago.
\global\edef can be shortened to \xdef. However, a macro does not create a group level, so since you are using this all without any grouping layer, the \global assignments are unnecessary here (unless, of course, in your actual code you need it, then ignore this).
One trick for printing command names is that what you achieve with \ttt command you can do with \ttfamily\string\command or, if you define \def\ttt{\ttfamily\string}, then \ttt\command.
One quite important thing is: do not allocate a register more than once. You are just depleting the number of available registers. Allocate the registers once an use them as many times as you need. I moved \newcount\chNum outside the macro definition.
In number assignments TeX already understands \chNum=`#1 to get the numerical value of an alphabetic constant; you don't need (but it doesn't hurt either) \numexpr here. Also the extra pair of parentheses around `#1 in the \numexpr aren't needed here.
Now on to \testAppendOne. The code
\chNum=\numexpr(`#1)%
\chardef\myCh=\chNum%
\appendChar{\char\myCh}%

appends the two tokens \char\myCh to \resultStr. However, since the \char primitive is not expandable the contents of \resultStr are \char\myCh after the first iteration, \char\myCh\char\myCh after the second one, and so on. When you ask TeX to write the contents of \resultStr it will use \char\myCh\char\myCh... and \myCh will have the last value assigned to it, which will be the last letter you processed, thus the behaviour you see.
When you process a \myCh is \char"61, so \char\char"61 will be a. Pretty obvious. When you process b \myCh is \char"62 then \char\char"62\char\char"62, which is bb and so on. To fix this you have to give \appendChar something that will not change if the \myCh change. The code
\chNum=\numexpr(`#1)%
\chardef\myCh=\chNum%
\appendChar{\char\myCh}%

is redundant. You don't need to \chardef a character before passing it to \char. As you have yourself done for the backslash with \char92, you can just use the number here:
\chNum=`#1
\appendChar{\char\chNum}%

or even:
\appendChar{\char`#1}%

This will pass \char`<some number which will not change> to \appendChar and you'll get what you want.
But why did \char\the\myCh in \testAppendTwo work? Because the primitive \the will access the value in \myCh. Suppose \myCh is \char"61 (a), then \the\myCh will be "61 (hexadecimal) or 97. Thus the code
\chNum=\numexpr(`#1)%
\chardef\myCh=\chNum
\showthe\myCh
\appendChar{\char\the\myCh}%

is also redundant because \the\myCH will access the number in \myCh, which is \chNum, so you can simplify to:
\chNum=\numexpr(`#1)%
\appendChar{\char\chNum}%

\testAppendThree is the same, except that \the\chNum will get the value in the \count register instead of the \char. But they are the same, thus the result is the same (and is the same as the modified version of \testAppendTwo :).

Now to the second part how to debug TeX code... Well... You don't really want to enter here. You'll be happier if you don't (just kidding... or am I?).
You code is rather straightforward, so I managed to debug it using only \show and \showthe. They both are used as \show<macro> and \showthe<register>.
\show prints the contents of a macro to the console. For example, if I change your \appendChar macro to:
\def\appendChar#1{% Append argument character to string
  \xdef\resultStr{\resultStr#1}%
  \show\resultStr
  \par{\ttfamily~\RLp#1\RRp~~~\RLb\resultStr\RRb}\par%
}

and run the \testAppendOne TeX will show this in the terminal:
> \resultStr=macro:
->\char \myCh .
\appendChar #1->\xdef \resultStr {\resultStr #1}\show \resultStr
                                                                 \par {\ttfamily ~\RLp #1\RRp ~~~\RLb \resultStr \RRb }\par
l.63 \useMacro{\testAppendOne}

?

then, if I press <return>, it shows:
> \resultStr=macro:
->\char \myCh \char \myCh .
\appendChar #1->\xdef \resultStr {\resultStr #1}\show \resultStr
                                                                 \par {\ttfamily ~\RLp #1\RRp ~~~\RLb \resultStr \RRb }\par
l.63 \useMacro{\testAppendOne}

?

(notice the second line). This showed me why your \testAppendOne was printing the same letter multiple times as I described earlier.
\showthe is similar, but it shows the value of a register. For instance, if you want to see the value of the \chNum register you'd use \showthe\chNum.
These two macros have equivalents which, instead of printing to the console (and the log) print to the PDF. \meaning<macro> will print the definition of the <macro> and \the<register> will print its value.

Not enough debugging?
You can use the \tracingall macro, which tells TeX “give me all you have to show” (and then \tracingnone when you want it to stop), and then your console will be flooded with text. With some practice you'll learn how to read that.
You can also load the trace package and use \traceon/\traceoff, which will hide some steps of the code which will print rather long trace text, like LaTeX's font selection system.

Still not enough?
Load \usepackage{unravel} (after all you asked for unravel :) and use \unravel{<code which is keeping you awake at night>}, and the package will show you step-by-step what TeX is doing. It's pretty useful when you are stuck at some nasty piece of code. Beware that this step-by-step is really thorough, so it might take a handful steps to \unravel{\useMacro{\appendChar}} :)

A: You are using
  \chardef\myCh=\chNum%
  \appendChar{\char\myCh}%

neither \char  nor a \chardef defined token such as \myCh is expandable so your repeated \edef just produces
\char\myCh\char\myCh\char\myCh\char\myCh

and when you finally use the macro you just get multiple copies of the last defined \myCh

A: You can debug by adding something like
\texttt{\meaning\resultStr}

to the output. If you do it on your original code you'd get, for \testAppendOne,

For \testAppendTwo and \testAppendThree you'd get

which is not what you want either, is it?
Here's a fixed version of \testAppendOne that appends the real character with a \lowercase trick, namely
\def\testAppendOne#1{% Use a better approach; WORKS
  \chNum=\numexpr(`#1)\relax
% Do arithmetic on the counter to implement the sorting rules
  \begingroup\lccode`!=\chNum\lowercase{\endgroup\appendChar{!}}%
}

Note other fixes: \ttfamily is used instead of \tt and similarly \bfseries for \bf; more important, you should not use \newcount\chNum at each call: you're wasting a count register at each macro call. I also streamlined the initial macros.
Why do I use \lccode`!=\chNum? The character ! has category code 12, so we essentially normalize all category codes to 12, which seems appropriate when dealing with strings.
\documentclass{article}

\usepackage[svgnames]{xcolor}% to get named colors

\newcommand{\Rtt}[1]{\textcolor{Red}{\ttfamily#1}}
\newcommand\RLp{\Rtt{(}}\newcommand\RRp{\Rtt{)}} % input
\newcommand\RLb{\Rtt{[}}\newcommand\RRb{\Rtt{]}} % [output]

\newcommand\ttt{{\ttfamily\char92}} % A better \tt \textbackslash

\newcount\chNum % NOT inside macros

\def\appendChar#1{% Append argument character to string
  \global\edef\resultStr{\resultStr#1}%
  \par{\ttfamily~\RLp#1\RRp~~~\RLb\resultStr\RRb}\par
}

\def\testAppendOne#1{% Use a better approach; WORKS
  \chNum=\numexpr(`#1)\relax
% Do arithmetic on the counter to implement the sorting rules
  \begingroup\lccode`!=\chNum\lowercase{\endgroup\appendChar{!}}%
}

\def\testAppendTwo#1{% Use counter, \chardef and \the; DOESN'T REALLY WORK
  \chNum=\numexpr(`#1)\relax
% Do arithmetic on the counter to implement the sorting rules
  \chardef\myCh=\chNum
  \appendChar{\char\the\myCh}%
}

\def\testAppendThree#1{% Bypass \chardef, DOESN'T REALLY WORK
  \chNum=\numexpr(`#1)\relax
% Do arithmetic on the counter to implement the sorting rules
  \appendChar{\char\the\chNum}%
}

\def\useMacro#1{% Calls macro #1{<character>}
  \global\edef\resultStr{}% (Re)initialize to empty string:
  \medskip
  \par{\tt\RLp chr\RRp~~\RLb\ttt resultStr\RRb}\par
  #1{a}% Simulate character data from string parsing macro
  #1{b}%
  #1{c}%
  #1{d}%
  #1{e}%
  \medskip
  \texttt{\meaning\resultStr}% for debugging
  \medskip
}

\begin{document} %               B E G I N   D O C U M E N T

% Proof of principle of using \edef to rebuild a string
\noindent{\Large\bfseries\color{Blue}Using {\ttt resultStrAppend}:}
\useMacro{\appendChar}

% First attempt fails with apparent recursion
\bigskip\noindent{\Large\bfseries\color{Blue}Using {\ttt testAppendOne}:}
\useMacro{\testAppendOne}

% Second attempt: adding \the command eliminates recursion
\bigskip\noindent{\Large\bfseries\color{Blue}Using {\ttt testAppendTwo}:}
\useMacro{\testAppendTwo}

% Third (final) macro: don't need the \chardef, have working macro
\bigskip\noindent{\Large\bfseries\color{Blue}Using {\ttt testAppendThree}:}
\useMacro{\testAppendThree}

\end{document}


Q: Excel (Custom Format): Format numbers to be displayed with a + as a thousand mark I don't know how to explain this in simple words, so I will give you some examples.
I have some numbers and I want a custom format to display them like this:
0     to be  000+000
12     to be  000+012
123    to be  000+123
1234   to be  001+234
12345  to be  012+345
123456 to be  123+456

A: Format cells > Custom > Set Type to 000+000.


Q: Hypernym of "pair/dyad", "tetrad", "pentad" Does the English language have a hypernym for words like "pair", "triad", "tetrad", and "pentad"? I'm not sure where to look.

A: I believe these are all examples of cardinal quantifiers

cardinal numbers, or cardinals for short, are a generalization of the natural numbers used to measure the cardinality (size) of sets. [Wikipedia]
Quantifier: (n) an expression that indicates the scope of a term to which it is attached. [OED]

So, given a pair, triad, tetrad, etc., each is defined by its cardinal attributes (2, 3, 4, n) along with an identifiable and consistent expression regarding the property of each number.

A: Mathematicians and computer scientists
sometimes use the word tuple
or the construct n-tuple (e.g., 2-tuple, 3-tuple, etc.).
(This is derived/generalized from words
like “double”, “triple”, “quadruple”, “quintuple” and “sextuple”.)
This differs from pair, triad, etc., and the other suggestions
(set, group, collection, etc.)
in that tuple implies that order is significant.
For example, [red, green, blue] is not the same 3-tuple as [blue, green, red].
I don’t know whether this would be understood
by somebody not in one of the above fields.
(I’m not even sure how well it is known within those fields.)

A: If I needed a name I would call such nouns "group names for numbers".

A: I was looking for an answer to the same question.  The only thing I discovered was that beyond pentad, we have hexad, heptad, ogdoad, ennead and decad.  They are Greek cardinal prefixes but I could not find any collective term for them beyond this.  I suggest we invent the word 'cardinads'!


Q: jsTree Clear Tree, Rebuild Tree jsTree appears to be a beautiful lightweight jquery Tree building package, but after working with it for a few days it really left a sour taste in my mouth for the lack of clear and useful documentation online.
I'm including the following methods below in case any future devs are trying to figure out how to accomplish this and don't feel like spending hours or days stumbling through it. I'm sure there's a more elegant or Best Practice way to code this, but I couldn't find any examples that didn't involve building the ajax method into the jstree function itself (very much not an option in my case). in my example below, I'm free to call an Ajax method in makeTree() to get my data, build the JSON as I see fit and insert it into the tree manually.
Anyway, below is some sample code I created to Build a tree on page load, Empty the tree of all its nodes on emptyTree(), and rebuild the tree from JSON on makeTree(). This is obviously an incomplete reference, but if you just need a quick and dirty way to do what I'm doing with this package, you might appreciate this.
    $(document).ready(function(){
        $("#myJSTree").jstree({
            'core' : {
                'check_callback' : true
            }
        });
    });

    function emptyTree()
    {
        var myTree = $("#myJSTree").jstree(true);

        $("#myJSTree .jstree-leaf, .jstree-anchor").each(function(){

            myTree.delete_node($(this).attr('id'));

        });
    }

    function makeTree()
    {
        var myTree = $("#myJSTree").jstree(true);

        // This JSON is just an example, you can create it how you need it, I'll include the sample Valid JSON at the bottom for reference.
        var nodesJSON = { "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }, "children": [{ "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }},{ "text": "Passed Testing", "icon": "images/success.png", "state": { "opened": true }}]};

        myTree.create_node("#", nodesJSON, "last", function() {}, true);

    }

// Adding the HTML that gets built into the tree at page load in my example

Node 1

SubNode 1

SubNode 2

Node 2

// Valid JSON format that took me a while to find on the jstree website
// I didn't write these. it's copied and pasted.
// sample JSON 1
{
  id          : "string" // will be autogenerated if omitted
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  children    : []  // array of strings or objects
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

// Sample JSON 2
{
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

Please feel free to share any insights you have if you have a better way to accomplish this, but this package's documentation is not super intuitive to me. I've combed through their webpage, it was painful.

A: To clear all nodes in the tree, you can call
        myTree.delete_node(myTree.get_node("#").children);


Q: Set color to a QTableView row void MyWindow::initializeModelBySQL(QSqlQueryModel *model,QTableView *table,QString sql){
        model = new QSqlQueryModel(this);
        model->setQuery(sql);
}

With this method i can set a QSQlQueryModels to my QTableviews.
But How i can set color to a row based on a cell value?

A: Your best bet is to define a custom model (QAbstractTableModel subclass). You probably want to have a QSqlQueryModel as a member in this custom class.
If it's a read-only model, you need to implement at least these methods:
 int rowCount(const QModelIndex &parent) const;
 int columnCount(const QModelIndex &parent) const;
 QVariant data(const QModelIndex &index, int role) const;

and for well behaved models also
 QVariant headerData(int section, Qt::Orientation orientation, int role) const;

If you need the model to be able to edit/submit data, things get a bit more involved and you will also need to implement these methods:
 Qt::ItemFlags flags(const QModelIndex &index) const;
 bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole);
 bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex());
 bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex());

What will actually change a row appearance lies in the return value of this method:
 QVariant data(const QModelIndex &index, int role) const;

A dumb example:
 QVariant MyCustomModel::data(const QModelIndex &index, int role) const
 {
     if ( !index.isValid() )
         return QVariant();

     int row = index.row();
     int col = index.column();

     switch ( role )
     {

        case Qt::BackgroundRole:
        {
            if(somecondition){
               // background for this row,col is blue
               return QVariant(QBrush (QColor(Qt::blue)));
            }
            // otherwise background is white
            return QVariant(QBrush (QColor(Qt::white)));
        }

        case Qt::DisplayRole:
        {
           // return actual content for row,col here, ie. text, numbers

        }

        case Qt::TextAlignmentRole:
        {

           if (1==col)
              return QVariant ( Qt::AlignVCenter | Qt::AlignLeft );

           if (2==col)
              return QVariant ( Qt::AlignVCenter | Qt::AlignTrailing );

           return QVariant ( Qt::AlignVCenter | Qt::AlignHCenter );

        }
     }

  }

A: The view draws the background based on the Qt::BackgroundRole role of the cell which is the QBrush value returned by QAbstractItemModel::data(index, role) for that role.
You can subclass the QSqlQueryModel to redefine data() to return your calculated color, or if you have Qt > 4.8, you can use a QIdentityProxyModel:
class MyModel : public QIdentityProxyModel
{
    QColor calculateColorForRow(int row) const {
        ...
    }

    QVariant data(const QModelIndex &index, int role)
    {
        if (role == Qt::BackgroundRole) {
           int row = index.row();
           QColor color = calculateColorForRow(row);
           return QBrush(color);
        }
        return QIdentityProxyModel::data(index, role);
    }
};

And use that model in the view, with the sql model set as source with QIdentityProxyModel::setSourceModel.
OR
You can keep the model unchanged and modify the background with a delegate set on the view with QAbstractItemView::setItemDelegate:
class BackgroundColorDelegate : public QStyledItemDelegate {

public:
    BackgroundColorDelegate(QObject *parent = 0)
        : QStyledItemDelegate(parent)
    {
    }
    QColor calculateColorForRow(int row) const;

    void initStyleOption(QStyleOptionViewItem *option,
                         const QModelIndex &index) const
    {
        QStyledItemDelegate::initStyleOption(option, index);

        QStyleOptionViewItemV4 *optionV4 =
                qstyleoption_cast<QStyleOptionViewItemV4*>(option);

        optionV4->backgroundBrush = QBrush(calculateColorForRow(index.row()));
    }
};

As the last method is not always obvious to translate from C++ code, here is the equivalent in python:
def initStyleOption(self, option, index):
    super(BackgroundColorDelegate,self).initStyleOption(option, index)
    option.backgroundBrush = calculateColorForRow(index.row())


Q: How to configure external USB touchpad for a laptop I have a laptop that, obviously, comes with a touchpad and a keyboard. However, I have an USB keyboard with integrated touchpad that better suits my needs. I use Ubuntu 13.10 and I cannot find how to configure the external touchpad sensitivity, or any other options.
The default touchpad settings tool from Ubuntu works fine, but it only changes the settings for the laptop's default touchpad. I also tried gpointing-device-settings, no luck.
Google's search results only mention touchpads from laptops, nothing about a second touchpad input device... How would I achieve this?
Here is the output of xinput: http://pastebin.ca/2643065


Q: Thymeleaf Form Request method 'POST' not supported, HTTP Error = Method Not Allowed, status=405 I am new into Thymeleaf and here I made a Form using Thymeleaf but running into this issue.
I read many many articles but didn't find any solution.
Here's my Controller Class ->
@Controller

public class SavingUser{

@Autowired
private UserRepository userRepository;

@PostMapping("/registerUser")
public ModelAndView user(@ModelAttribute Customer customer, ModelMap model){
    System.out.println("User in registration page..");
    userRepository.save(customer);
    model.addAttribute("saveUser", customer);
    return new ModelAndView("index");
 }
}

And here's my HTML Form -

    <form action="registerUser" th:action="@{/registerUser}"  th:object="${saveUser}" method="POST">

        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        Your Name:

        <input type="text" th:field="*{name}"  placeholder="" />

        Your Suburb

        <input type="text"  th:field="*{suburb}"  placeholder="" />

            <input class="submit" type="submit" value="Submit"  />

    </form>

I tried not put action="", still it didn't work.
Any solution, thanks in advance.


Q: How to modify or remove older commit in Git? From past few days i had kept on adding and committing files in my local. My branch is now 16 commits ahead of 'origin/master'.
I wanted to push them to my git repo but one of the file being very large my push command fails. Is there any way to remove that commit from the stash or will i have to do a hard reset on the head.

A: If you just want to skip a commit, do git rebase -i master and select drop for the commit to be skipped. If you just want to remove a single file from it, select edit and amend the commit to remove the file.

A: *

*You can use the squash

*BFG

*Move HEAD back to previous commit (link)

squash
# edit all the commits up to the given sha-1
git rebase -i <sha-1>

but one of the file being very large my push command fails...

How to remove big files from the repository
You can use git filter-branch or BFG.
https://rtyley.github.io/bfg-repo-cleaner/

BFG Repo-Cleaner
an alternative to git-filter-branch.
The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:
* Removing Crazy Big Files*
  * Removing Passwords, Credentials & other Private data

Examples (from the official site)

In all these examples bfg is an alias for java -jar bfg.jar.

# Delete all files named 'id_rsa' or 'id_dsa' :
bfg --delete-files id_{dsa,rsa}  my-repo.git

A: If you just want to remove the file then why not just do that by deleting the file and then committing the change?
Now, in your latest commit the file doesn't exist.
You should now be able to push your branch to the remote without any problem.

A: what you can do is you can use git rebase option and squash all the commits.


Q: Is there a tool for previewing both LaTeX and MetaPost files? I'm trying to find a tool for Windows that I can use to preview .tex and .mp files as they are saved. Does such a tool exist? I have TeXworks installed which has a handy build button (this displays the result in another window), but I'd rather use Emacs. Also, TeXworks does not compile .mp files.
Perhaps there's a more elegant way to preview files, other than the approach I'm thinking of.

A: Solution is to use pdflatex and Sumatra PDF, since this viewer auto-reloads the file.


Q: VBA (Excel) 2010: specific script how-to, dealing with range comparisons I have 3 columns that follow these rules:

*

*Any cell in Col A may be empty, otherwise it contains a string.

*If a row in Col A is empty, that row in Col's B and C will be empty.

*If a row in Col A is populated, That row in Col B will be populated with an integer, and that row in Col C may be empty or have a "1".

I need a script that, for each cell in Col A,

*

*Checks the string in that cell and looks for all identical strings in Col A.

*For each row containing said matching string, checks Col C for a "1"

*For each row where both of the above are true, sum the values in Col B and replace each of them with that sum.

So for example, this:
A B C
x 1
x 2
z 2 1
y 1 1
y 2 1

y 1
z 2 1
z 1 1

Should become this:
A B C
x 1
x 2
z 5 1
y 3 1
y 3 1

y 1
z 5 1
z 5 1

So 3 different strings are found in Col A, (x y and z). Duplicates of x are found but the values in col B are not summed because there was no "1" in Col C. Dupes of y are found, but only those with a "1" to the right are summed. All dupes of z found have a "1", so all are summed.
What's the best way to do this? Please let me know if I need to clarify something about this question (I know it's convoluted, but I spent a lot of time trying to make it as clear as possible haha).

A: A simple formula should do the job : assuming the data are found in A:C
=IF(ISBLANK(A2),"",IF(ISBLANK(C2),B2, SUMIFS(B:B,A:A,A2,C:C,1)))

The outer IF display nothing when column A is empty.
The inner IF displaycolumn B when column C is empty.
The SUMIFS will add upcolumn B where column A is the same(as current row) and when column C is 1.


Q: Set Theory: Union over sets satisfying criterion, rigorous definition? I'm trying come to a rigorous understanding of certain types of set unions. For purposes of this question I'm comfortable with set unions written as
$$
\mathcal{A} = \bigcup A = \{x:\exists_a(x\in a \wedge a\in A)\}
$$
but I am not comfortable with unions expressed using other types of notations..
I am trying to understand Munkres Lemma 13.1 concerning a characterization for the basis ($\mathcal{B}$) of a topology*. In fact, I am stuck at the same point as the asker in this question: Proof of Lemma 13.1 in Munkres.
We are considering an open set $U$ and the proof has a step which says for each $x$ in $U$ we know there is a set $B_x$ satisfying $x\in B_x\subset U$ and $B_x \in \mathcal{B}$. I understand and agree with this statement. The next statement is the problem. That statement says that thus
$$
U = \bigcup_{x\in U}B_x
$$
Let
Intuitively I very much understand this statement. We've found a $B_x$ for each $x$ and we combine together all of the $B_x$ that we found. Let
$$
C = \bigcup_{x\in U}B_x
$$
Clearly each $x$ in $U$ will be in this collection so $U\subset C$and clearly each element of this collection is a subset of $U$ so $C\subset U$ so clearly $C=U$.
My problem is understanding what is the rigorous definition of the set $C$ in terms of the definition for infinitary unions I have given above. That is, is there some set $b$ such that I can write
$$
C = \bigcup b
$$
Where $b$ somehow captures the notion of having one set $B_x\subset U$ inside of it for each $x$ in $U$? How would I construct the set $b$ formally? It seems like it is something like constructing a choice function? (something I'm not really familiar with..)
edit:
Just a few notes to explain along what lines I am thinking about the problem. It seems like I want something like
$$
f:U \rightarrow \mathcal{B}
$$
with $x \in f(x) \subset U$. Then I would want $b$ to be the range of $f$ which is guaranteed to be a set by the axiom schema of replacement. The problems are 1) I don't know exactly how to construct the function $f$ and 2) I'm not sure if this is an overkill solution to the issue I am describing when there is in fact a much more straightforward definition..
*However my question doesn't really have to do with this particular proof but rather a general notion about set unions so I don't want to get bogged down in the details of this particular proof.

A: You can take
$$
b = \{B\in \mathcal{B}\colon B\subseteq U\}.
$$
Obviously, $$C = \bigcup b\subseteq U.$$
For each $x\in U$ there exists some $B_x\in b$ such that $x\in B_x$, hence $x\in C$.
You don't have to make any choices. You should just take more sets in $b$ than you really need.


Q: Converting Unix timestamp to hours All,
I have a database field which actually computes the time spent from the time the quiz started to the current time. This was done at some point of time (recorded as current time) and now I have an Unixtimestamp value for it
i.e. Suppose the start time was 5/5/2011 1pm and the current time was populated at 5/5/2011 2pm. So the difference is calculated and stored as an Unix timestamp.
Now I don't know when this was actually done and now I have to revert back to hours spent taking the quiz. So here a Unix timestamp needs to be converted back to hours, in this case return 1 hour. Can anyone please help me understand how to do this?

A: You have the seconds, so just do something like
SELECT secondsField / 3600 as 'hours' FROM tableName

A: Here is an example of finding the difference between two timestamps in days.
//Get current timestamp.
$current_time = time();

//Convert user's create time to timestamp.
$create_time  = strtotime('2011-09-01 22:12:55');

echo "Current Date \t".date('Y-m-d H:i:s', $current_time)."\n";
echo "Create Date \t".date('Y-m-d H:i:s', $create_time)."\n";

echo "Current Time \t ".$current_time." \n";
echo "Create Time \t ".$create_time." \n";

$time_diff = $current_time - $create_time;
$day_diff = $time_diff / (3600 * 24);

echo "Difference \t ".($day_diff)."\n";
echo "Quote Index \t ".intval(floor($day_diff))."\n";
echo "Func Calc \t ".get_passed_days($create_time)."\n";

function get_passed_days($create_time)
{
    return intval(floor((time() - $create_time) / 86400));
}

To convert to hours, instead of 86400 put 3600 instead.
Hope this helps.


Q: Get access token facebook-sdk I'm trying to figure out, how to log in to facebook account and get access token so I can post into my groups.
To create a GraphAPI instance, I need to check access_token I need and put it into the code.
I'm curious whether is it possible to use username and password to get the access_token automatically so the program can be used by more users.
oauth_access_token = 'ACCESS TOKEN WHICH I HAVE TO GET FROM https://developers.facebook.com/tools/explorer/..../'

def post_to_1_group(user,password,post):

    graph = facebook.GraphAPI(oauth_access_token)
    groups = graph.get_object("me/groups")
    group_id = groups['data'][1]['id'] # select the first group I'm in

    graph.put_object(group_id, "feed", message=post)

This code works but it doesn't use user and password arguments. I have to check my access_token everytime I want to run the program.
Is it possible?


Q: Creating a loop in JS for a web application I'm trying to loop this function at least ten times but can't seem to get it to work on my web application.
I am learning JS at school and this is as far as i've come
$(function fade_in_pictures() {
  for (int i = 0; i < 10; ++i) {
    $('.wi2').delay(2000).fadeIn(0);
    $('.wi1').delay(2000).fadeOut(0);
    $('.wi1').delay(4000).fadeIn(0);
    $('.wi2').delay(4000).fadeOut(0);
    $('.wi2').delay(2000).fadeIn(0);
    $('.wi1').delay(2000).fadeOut(0);
  }
});

ERROR:Parsing error: Unexcepted Token i


Q: Resource leak not closed I'm using Eclipse, and doing the function below, it happens that I'm opening a Scanner, and then, in the end I close it, but Eclipse keeps saying that it is not closed "resource leak: 'scanner' is not closed".
I can do it with try with resources, and the warning disappears, but I want to understand why the way I'm trying in here doesn't work
   private void follow(String userID) {

        if(!(new File("../users/"+userID+"/")).exists()){
            System.out.println("User especificado nao existe");
            return;
        }

        File list = new File("../users/"+userID+"/followers.txt");
        try {
            list.createNewFile();

            Scanner scanner = new Scanner(list);
            while(scanner.hasNextLine()){
                String line = scanner.nextLine();
                if(line.equals(clientID)){
                    System.out.println("Cliente ja segue este user");
                    return;
                }
            }

            PrintWriter out = new PrintWriter(new FileWriter(list, true));
            out.append(clientID+"\n");

            out.close();
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

A: #createNewFile() can throw an IOException before you get to the close() statement, keeping it from being executed.

A: put out.close() in a finally statement:
finally {
    out.close();
}

What finally does is that any code within it gets executed even if an error is thrown.

A: Scanner implements AutoCloseable; you may use try-with-resources
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


Q: Loading a shared library in a same directory with the executable file In Windows, an executable(.exe) which needs a shared library (.dll) can be run when the exe and dll files are in a same directory.
In Linux, even though the executable and the shared library(.so) are in the same directory, Linux always looks for it in the absolute directory where .so was first built, then fails to run the executable.
Setting LD_LIBRARY_PATH or RPATH environment variable before running the executable is a ad-hoc solution, but I want to do it without setting the environment variable, and make it behaves like Windows.
How can I do it? I added "-rpath=$ORIGIN" to CMakelists but it still fails.
For just experimenting, I made a simple program and another shared library and tried dlopen and it works as I wanted. However, I don't use dlopen for this case.

A: I found the solution: add rpath option to CMakelists.txt for the executable, not for the shared library.


Q: How to DRY a Bootstrap view I'm looking for a better way to effectively DRY my Rails views that use Bootstrap 3.0
Here's the HAML code of the view:
%h1 Profiles

.visible-xs
  %table.table.table-striped
    %tbody
      - @profiles.each do |profile|
        %tr
          %td
            = profile.name
          %td{style: "text-align: right"}
            =link_to "".html_safe, setup_profile_path(profile), class: "btn"
            =link_to "".html_safe, edit_setup_profile_path(profile), class: "btn"

.hidden-xs
  %table.table
    %tr
      %th Name
      %th Last Updated
      %th Actions
    - @profiles.each do |profile|
      %tr
        %td= profile.name
        %td= time_ago_in_words profile.updated_at
        %td
          =link_to " Details".html_safe, setup_profile_path(profile), class: "btn btn-sm"
          =link_to " Change".html_safe, edit_setup_profile_path(profile), class: "btn btn-sm"
          =link_to " Remove".html_safe, setup_profile_path(profile, method: :destroy), class: "btn btn-sm"

As you can see, I have an additional column (presently) and may add two or three more for the larger viewports (hence a table layout) as the app develops, but for the mobile devices, I just show the Profile name and buttons to get to more details (which is all that's really practical on small screens).
I tried using rows and cols of the grid system, but its a lot of work to get a usable interface at each viewport size and the template code looks like a big ball of mud when all in one.  Separating into XS and "everything else" so far is the cleanest implementation, but two blocks and two loops though same data to present.  Before I go and create 20 more of these, is there a DRY'er way to implement mobile (xs) vs. tablet/desktop (sm, md, lg, ...) viewports that is still very clear to glance at and understand?


Q: How to join 2 json files by one key jsonfile1
[
    [
        "i-pfasdqaertcbidlkl",
        "Some_Task",
        "t2.small",
        "running",
        "4.3.2.1",
        "Malaysia_db",
        "2018-04-10T13:56:50.000Z",
        "db",
        null,
        "1.2.3.4",
        null,
        null
    ]
]

jsonfile2
[
    "i-pfasdqaertcbidlkl",
    false
]

I want to join both files by i-pfasdqaertcbidlkl
Output Needed
[
    [
        "i-pfasdqaertcbidlkl",
        "Some_Task",
        "t2.small",
        "running",
        "4.3.2.1",
        "Malaysia_db",
        "2018-04-10T13:56:50.000Z",
        "db",
        null,
        "1.2.3.4",
        null,
        null,
        false
    ]
]


Q: Deriving the partition function in MaxEnt I'm trying to understand this paper on Maximum Entropy by Jaynes, and am stuck on something which should be rather simple.
We're attempting to maximize the entropy $-\sum_i p_i \ln(p_i)$ subject to the constraints $\langle f \rangle = \sum_i p_i f_i$ and $\sum_i p_i = 1$. Using Lagrange multipliers, we have:
$$L = -\sum_i p_i \ln(p_i) + \lambda \left( \sum_i p_i f_i - \langle f \rangle \right) + \mu \left( \sum_i p_i - 1 \right)$$
$$\frac{\delta L}{\delta p_i} = - \ln(p_i) - 1 + \lambda f_i + \mu = 0$$
So $p_i = e^{-1 + \mu + \lambda f_i}$. Plugging this back into the definition for $\langle f \rangle$:
$$\langle f \rangle = \sum_i p_i f_i = \sum_i f_i e^{-1 + \mu + \lambda f_i} = \sum_i f_i e^{-1 + \mu + \lambda f_i}$$
Equation (2-5) in Jaynes' paper states (ignoring sign conventions) that $\langle f \rangle = \frac{\partial}{\partial \lambda} \ln{Z}$, where $Z$ is the partition function, probably defined as $Z = \sum_i e^{-1 + \mu + \lambda f_i}$, or just simply $Z = \sum_i e^{\lambda f_i}$ if we ignore the normalisation. I tried to check this:
$$\langle f \rangle = \frac{1}{Z} \frac{\partial}{\partial \lambda} Z = \frac{1}{Z} \frac{\partial}{\partial \lambda} \sum_i e^{\lambda f_i} = \frac{1}{Z} \sum_i f_i e^{\lambda f_i} = \frac{1}{Z} \langle f \rangle$$
Which I doubt is correct. I'm probably making some obvious mistake, but for the life of me I can't find it.

A: Your mistake is in the last line. You assert:
\begin{equation*}
\langle f \rangle=\sum_i f_i e^{\lambda f_i}
\end{equation*}
but that isn't true, rather:
\begin{equation*}
\langle f \rangle=\sum_i f_i e^{\lambda f_i-1+\mu}
\end{equation*}
To convert correctly between your two expressions for $\langle f \rangle$, you must figure out a way to express $\mu$ (which is not the chemical potential, to avoid any potential confusion) in terms of other variables.

A: You're almost there.
The thing to realise about the partition function is that it is the normalisation. If statistical mechanics were being developed today I'm sure its name would be "normalisation factor", but "partition function" has stuck historically.
Now, the partition function is in fact defined as $Z = \sum_i e^{\lambda f_i}$, so that
$$
p_i = \frac{1}{Z}e^{\lambda f_i}.
$$
This is the formula you should have tattooed on the inside of your brain if you want to think much about statistical mechanics. You can note that this implies $Z = e^{1-\mu}$, and if you like you can think of this as its definition.
With all this in mind, it should now be clear that your derivation is correct up to the last equality, which should instead say
$$
\dots = \frac{1}{Z} \sum_i f_i e^{\lambda f_i} = \langle f \rangle.
$$


Q: change image in a div with Onclick in React I have several divs with an image inside each of them and I have an onCLick on the wrapping div, which executes two functions -clickHandler() and toggleCollapse2(). The idea is that the image in the div represents a styled ticked box which replaces the image of the empty box with the onClick. The onclick in the beginning was on the image but when i put the Onclick on the wrapping div, I cannot change the source of the pictures when the div is clicked. I have put the div in a dropdown item,because i have about 20 buttons with ticked icons with text and I'm trying to rewrite the code in React, but unfortunately I am new to React yet. So I'll be thankful for any help. The idea is to use this code, instead of writing all the buttons with the onClick and the functions one by one. Moreover the ticked icons with text must be in 3 columns.
The problem is to make the checkbox-yellow replace the checkbox_empty image when clicking on the div.

//in the constructor
//constructor(props) {
//       super(props);
//this.state = {
buttons :
    [
    {id:1, name:"check1", isVisited: false, value:"name1"},
    {id:2, name:"check2", isVisited: false, value:"name2"},
    {id:3, name:"check3", isVisited: false, value:"name3"},
    {id:4, name:"check4", isVisited: true, value:"name4"},
    {id:5, name:"check5", isVisited: false, value:"name5"},
    {id:6, name:"check6", isVisited: false, value:"name6"},
    {id:7, name:"check7", isVisited: true, value:"name7"},
    {id:8, name:"check8", isVisited: false,value:"name8"},
    {id:9, name:"check9", isVisited: false,value:"name9"},
    {id:10, name:"check10", isVisited: false, value:"name10"},
    {id:11, name:"check11", isVisited: false, value:"name11"},
    {id:12, name:"check12", isVisited: false, value:"name12"},
    {id:13, name:"check11", isVisited: false, value:"name13"},
    {id:14, name:"check12", isVisited: false, value:"name14"}
],

//Outside the constructor:

dropdownButton(startIndex,endIndex){
    let uiButtons = [];
       this.state.buttons.slice(startIndex,endIndex).map((button)=>{
           uiButtons.push(
               <DropdownItem>

 {
                       this.clickHandler();
                       this.toggleCollapse2(button.name, button.isVisited)}} >

                           {button.value}

               </DropdownItem>
           );
       }
       );
    return uiButtons;
    }

 toggleCollapse2 = (sectionName) => {
        this.setState({check1: false, check2: false, check3: false, check4: false})
        let obj = {};
        obj[sectionName] = !this.state[sectionName];
        this.setState(state => (obj));
    }

   //in the render I have this code:/because I want the buttons distributed equally in 3 columns/
  let startIndexFirstColumn = 0;
let endIndexFirstColumn = 0;
let startIndexSecondColumn = 0;
let endIndexSecondColumn = 0;
let startIndexThirdColumn = 0;
let endIndexThirdColumn = 0;

if ( this.state.buttons.length % 3 === 2) {
    endIndexFirstColumn = (this.state.buttons.length / 3 + 1);
    startIndexSecondColumn = (this.state.buttons.length / 3 + 1);
    endIndexSecondColumn = ((this.state.buttons.length / 3) * 2 + 1);
    startIndexThirdColumn = ((this.state.buttons.length / 3) * 2 + 1);

    endIndexThirdColumn = (this.state.buttons.length / 3 * 3);
}

   //and in the return part I have 3 similar divs,containing:

    {this.dropdownButton(startIndexFirstColumn,endIndexFirstColumn)}

   //with different indexes for each column

A: I need to make the img source show the checkbox_yellow image instead of checkbox-empty image,when the div containing the image and text is clicked.And to change it back when the div is clicked again.


Q: Python - Split List into a Dictionary I am trying to split a big list into a dictionary. Given a list with say 363 elements I want to divide them such that each key in the dictionary will have a list of 10 values. So a list of 363 elements will have 37 keys (rounded up to nearest 10).The keys will start from 1 and go upto 37. I wrote a function for the rounding up but i dont know how to split the list while making sure the sequence is maintained and if all the lists (which will be the values of the keys) are joined they will mirror the original list.
This is my rounding up function:
def roundup(list_length, atatime=10):
    return ((atatime-(list_length%atatime))+list_length)/atatime

Any ideas , suggestions will be really helpfull

A: If you want to round up and slice appropriately:
l = list(range(363))
at_a_time = 10
n = len(l)
d, r = divmod(n, at_a_time)

# if there is a remainder, add 1 to the keys, 363 -> 37 keys 360 -> 36 keys
num_keys = d + 1 if r else d
# get correct slice size based on amount of keys
sli = n // num_keys

# create "sli" sized chunks
vals = (l[i:i+sli] for i in range(0, n, sli+1))
# make dict from `1 to num_keys inclusive and slices
dct = dict(zip(range(1,num_keys+1),vals))
print(dct)
{1: [0, 1, 2, 3, 4, 5, 6, 7, 8], 2: [10, 11, 12, 13, 14, 15, 16, 17, 18], 3: [20, 21, 22, 23, 24, 25, 26, 27, 28], 4: [30, 31, 32, 33, 34, 35, 36, 37, 38], 5: [40, 41, 42, 43, 44, 45, 46, 47, 48], 6: [50, 51, 52, 53, 54, 55, 56, 57, 58], 7: [60, 61, 62, 63, 64, 65, 66, 67, 68], 8: [70, 71, 72, 73, 74, 75, 76, 77, 78], 9: [80, 81, 82, 83, 84, 85, 86, 87, 88], 10: [90, 91, 92, 93, 94, 95, 96, 97, 98], 11: [100, 101, 102, 103, 104, 105, 106, 107, 108], 12: [110, 111, 112, 113, 114, 115, 116, 117, 118], 13: [120, 121, 122, 123, 124, 125, 126, 127, 128], 14: [130, 131, 132, 133, 134, 135, 136, 137, 138], 15: [140, 141, 142, 143, 144, 145, 146, 147, 148], 16: [150, 151, 152, 153, 154, 155, 156, 157, 158], 17: [160, 161, 162, 163, 164, 165, 166, 167, 168], 18: [170, 171, 172, 173, 174, 175, 176, 177, 178], 19: [180, 181, 182, 183, 184, 185, 186, 187, 188], 20: [190, 191, 192, 193, 194, 195, 196, 197, 198], 21: [200, 201, 202, 203, 204, 205, 206, 207, 208], 22: [210, 211, 212, 213, 214, 215, 216, 217, 218], 23: [220, 221, 222, 223, 224, 225, 226, 227, 228], 24: [230, 231, 232, 233, 234, 235, 236, 237, 238], 25: [240, 241, 242, 243, 244, 245, 246, 247, 248], 26: [250, 251, 252, 253, 254, 255, 256, 257, 258], 27: [260, 261, 262, 263, 264, 265, 266, 267, 268], 28: [270, 271, 272, 273, 274, 275, 276, 277, 278], 29: [280, 281, 282, 283, 284, 285, 286, 287, 288], 30: [290, 291, 292, 293, 294, 295, 296, 297, 298], 31: [300, 301, 302, 303, 304, 305, 306, 307, 308], 32: [310, 311, 312, 313, 314, 315, 316, 317, 318], 33: [320, 321, 322, 323, 324, 325, 326, 327, 328], 34: [330, 331, 332, 333, 334, 335, 336, 337, 338], 35: [340, 341, 342, 343, 344, 345, 346, 347, 348], 36: [350, 351, 352, 353, 354, 355, 356, 357, 358], 37: [360, 361, 362]}

If you don't want the list sliced evenly and the remainder to be added to the last key just use your atatime for each slice (10 in the example code):
 vals = (l[i:i+at_a_time] for i in range(0, n, sli+1))

We can also use num_keys = n + (at_a_time - 1) // at_a_time to round as any value that has a remainder // at_a_time will be rounded up adding at_a_time - 1 to it , any number evenly divisible  will not.
You can do it  all in a dict comprehension making some changes to the code but I think you will hopefully learn more from explicit code.

A: The following dict comprehension slices the list into the required number of slices.
In other words, idx+1 is the key, whereas lst[atatime*idx:atatime*(idx+1)] is the value of a dictionary defined using dict-comprehension. The value is a slice of atatime length. We iterate over the (rounded upwards) size of the list divided by the chunk-size using an xrange iterator.
from math import ceil
{idx+1: lst[atatime*idx:atatime*(idx+1)] for idx in xrange(int(ceil(float(len(lst))/atatime)))}


Q: Enriching Gensim W2V with spatial Information (such as geo-location) Anyone have experince, or idea of the best way to train a W2V model , while enrichnig is with geo-location context (using Gensim library)?

*

*I have a dataset of scripted conversations from different english specking coutries.

*I would like to train the model to understand the relation between words, but also consider the location in which the conversations took place.

*So when I'm "questioning" the model, I can give it a context to a certain country and potentially improve its relevancy.

What I have in mind, is to inject a geo-location ID with every phrase, as a (fake) word.
Example -
p1 [us, the, lion, king, is, a, great, movie, us]
p2 [uk, king, charles, ascended, the, throne, uk]
The desired result should be something along the lines of:
vec(“us”) + vec(“king”) --> vec ("Lion")
vec(“uk”) + vec(“king”) --> vec ("Charles")
Anyone have a more sturctured idea to do that, while still sticking to the Gensim library?

A: I've not seen any proven techniques for your need.
But, it is a bit similar to how people try to track the drift in word meanings over different eras. There's been some published work like HistWords from Stanford on that task.
I have also in past answers suggested people working on the eras-drift task try probabilistically replacing words whose sense may vary with alternate, context-labeled tokens. That is, if king is one of the words that you expect to vary based on your geography-contexts, expand your training corpus to sometimes replace king in UK contexts with king_UK, and in US contexts with king_US. (In some cases, you might even repeat your texts to do this.) Then, at the end of training, you'll have separate (but close) vectors for all of king, king_UK, & king_US – and the subtle difference between them may be reflective of what you're trying to study/capture.
You can see other discussion of related ideas in previous answers:
https://stackoverflow.com/a/57400356/130288
https://stackoverflow.com/a/59095246/130288
I'm not sure how well this approach might work, nor (if it does) optimal ways to transform the corpus to capture all the geography-flavored meaning-shifts.
I suspect the extreme approach of transforming every word in a UK-context to its UK-specific token, & same for other contexts, would work less well than only sometimes transforming the tokens – because a total transformation would mean each region's tokens only get trained with each other, never with shared (non-regionalized) words that help 'anchor' variant-meanings in the same shared overall context. But, that hunch would need to be tested.
(This simple "replace-some-tokens" strategy has the advantage that it can be done entirely via corpus preprocessing, with no change to the algorithms. If willing/able to perform big changes to the library, another approach could be more fasttext-like: treat every instance of king as a sum of both a generic king_en vector and a region king_UK (etc) vector. Then every usage example would update both.)