text:
Q: Is it possible for me to remove this last if statement? I've written a small utility to open up executables and spit out certain printable strings it finds.
It works fine but I was wondering, is there some way I could remove one of these if statements?  I was trying to see how I could arrange my conditionals so I wouldn't need the 3 different if statements but I don't see how I can do it with the current structure.
#include <stdio.h>

#define MAX_STR_SIZE 0x666
#define MIN_STR_SIZE 0x5

int main(int argc, char** argv)
{
    int ch;
    int pos = 0;
    FILE* f;
    char buff[MAX_STR_SIZE];

    if (argc>1 && (f=fopen(argv[1], "rb")))
    {
        while ((ch=getc(f)) != EOF)
        {
            if (ch >= ' ' && ch <= 'z') // is printable char?
            {
                buff[pos++] = ch;
                buff[pos] = '\0';
                if (pos == (MAX_STR_SIZE-1))  // is current string > max length?
                {
                    printf("%08x: %s\n", ftell(f), &buff[0]);
                    pos = 0;
                }
            }
            else // non-printable char, print any string in buffer and start over
            {
                if (pos > (MIN_STR_SIZE - 1)) // is current string > min string?
                {
                    printf("%08x: %s\n", ftell(f), &buff[0]); // print current string
                }
                pos = 0;
            }
        }

        if (pos > (MIN_STR_SIZE - 1)) // any remaining string left to print?
        {
            printf("%08x: %s\n", ftell(f), &buff[0]);
        }

        fclose(f);
    }
}

A: The last if seems to be necessary for the current logic of the code.
However, the check in your code is not entirely correct. Why don't you use isprint() function to check whether a character is printable or not? Something like this:
if (isprint(c)) // is printable char?
{
  //c is printable
}

A: I believe this version eliminates most of the if statements (or at least collapses them together:
#include <stdio.h>

#define MAX_STR_SIZE 0x666
#define MIN_STR_SIZE 0x5

int main(int argc, char** argv)
{
    int ch;
    int pos = 0;
    FILE* f;
    char buff[MAX_STR_SIZE];

    if (argc>1 && (f=fopen(argv[1], "rb")))
    {
        while ((ch = getc(f)) != EOF)
        {
            pos = 0;
            while (ch >= ' ' && ch <= 'z' && pos < (MAX_STR_SIZE-1)) {
                buff[pos++] = ch;
                ch = getc(f);
            }
            if (pos > (MIN_STR_SIZE - 1)) // is current string > min string?
            {
                buff[pos] = '\0';
                printf("%08x: %s\n", ftell(f), buff);
            }
        }

        fclose(f);
    }
}


text:
Q: Heroku and slug size bloat I'm starting to hit a wall with my Heroku app.
I'm well aware of the normal issues with slug size, re: images, PDFs, and other materials but my problem likely revolves around other assets brought in by bower or possibly build packs.
https://devcenter.heroku.com/articles/slug-compiler
Heroku Slug Size After Multiple Deployments
My Heroku compliled slug looks like so:
$ du -h --max-depth=1
4.0K    ./.bower-tmp
30M ./tmp
24K ./features
236K    ./config
195M    ./public
4.0K    ./log
34M ./bin
792K    ./db
355M    ./vendor
8.0K    ./.heroku
22M ./app
64K ./lib
8.0K    ./.bundle
136K    ./.bower-registry
22M ./.bower-cache
24M ./node_modules
12K ./.profile.d

By far the largest is Vendor (355M), but my local vendor folder is in fact empty as is public (195M).
But on heroku it looks like:
40M vendor/ruby-2.0.0
21M vendor/node
32K vendor/heroku
12K vendor/assets
103M vendor/jvm
192M vendor/bundle

195M public/assets (bower bloat?)

Which I'm guessing is one of several build packs for bower and for PDF generation.
https://github.com/heroku/heroku-buildpack-nodejs
https://github.com/heroku/heroku-buildpack-ruby
https://github.com/razorfly/wkhtmltopdf-buildpack

My app itself looks lean-ish at 22M, but my current heroku SLUG is 298.4MB! and the vendor directory alone is more than that according to du, should I not be using these build packs and instead migrate to asset compilation on my local machine between builds?  I'm not sure what a good deployment strategy (/ slug diet) should look like, any ideas would be greatly appreciated.
UPDATE:
I also tried rebuilding the slug from what I read had worked for others, but to no effect.  Slug size after compilation remained the same.
heroku plugins:install https://github.com/heroku/heroku-repo.git
heroku repo:rebuild -a appname

GIST of build: https://gist.github.com/holden/b4721fc798bdaddf52c6
UPDATE 2 (after following the excellent idea presented by drorb)
12K ./.profile.d
21M ./app
4.0K    ./log
812K    ./db
8.0K    ./.heroku
236K    ./config
195M    ./public
19M ./.bower-cache
60K ./lib
253M    ./vendor
4.0K    ./.bower-tmp
128K    ./.bower-registry
34M ./bin
30M ./tmp
24M ./node_modules
24K ./features
8.0K    ./.bundle

Vendor
12K vendor/assets
193M    vendor/bundle
21M vendor/node
32K vendor/heroku
40M vendor/ruby-2.0.0

Public/Assets (very long)
https://gist.github.com/holden/ee67918c79dd3d197a6b

A: The size of vendor/jvm is 103M. Since you are not using JRuby the only reason I could find for having it is using the yui-compressor gem. Looking at the heroku-buildpack-ruby it seems that the JVM is installed in this case:
def post_bundler
  if bundler.has_gem?('yui-compressor') && !ruby_version.jruby?
    install_jvm(true)
    ENV["PATH"] += ":bin"
  end
end

If you can avoid using yui-compressor you should be able to save 103M on your slug size.

A: FWIW, we removed Bower from our app and replaced it with the Rails Assets framework.  We came to the conclusion that using Bower in a Rails app was somewhat pointless as Bundler essentially serves the same function.

A: Part of the problem may be pointing at Git repos in your Gemfile. At one point I needed to point at a Rails commit that hadn't been released and it added > 100 MB to my slug size over pointing at a released version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can we get a response send by a mobile application I want to receive a code which is been send from the mobile application during confirmation process.And I should check through the database if the user is authorized.What should I do to receive and analyze the data?

A: I suggest you start by learning about RESTful API Design. RESTful principles provide strategies to handle CRUD actions using HTTP methods. REST for example would dictate the usage of PUT/PATCH to UPDATE a record in the database for whatever it may be (user/item/etc).
You could have a URI which handles the verification by checking the details the mobile application has sent to the server against the appropriate record in the database and then sending back an appropriate response.
Here's a good example of where you can get started; http://www.restapitutorial.com/lessons/restfulresourcenaming.html


text:
Q: IllegalStateException on sign to Google api client I am getting the following error:
java.lang.IllegalStateException: Cannot use sign-in mode: SIGN_IN_MODE_OPTIONAL. Mode was already set to SIGN_IN_MODE_NONE

What does this mean? How to prevent it?
The suggestion in other similar SO question was
 mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);

But I have been using this itself.
Here is the onActivityResult
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_OAUTH) {
        authInProgress = false;
        if (resultCode == RESULT_OK) {
            progressDialog.dismiss();
            if (!googleApiClient.isConnecting() && !googleApiClient.isConnected()) {
                googleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
            } else {
                onConnected(null);
            }
        } else if (resultCode == RESULT_CANCELED) {
            progressDialog.dismiss();
            startApiClientConnect();
        }
    } else {
        progressDialog.dismiss();
        startApiClientConnect();
    }
}

After the initial connection attempt if it was not successful then the googleApiClient.connect is reattempted in the onActivityResult. I believe this is reattempt is causing the problem. After initial connection failure / some user action makes the SIGN_IN_MODE_NONE.
How to handle this?

A: It looks like you're not allowed to provide a sign in mode to the connect(int) method more than once. The documentation says "It is an error to make multiple calls to this method passing different modes. Once a mode is selected, all future connect calls must use the same mode." So it might be that you're calling connect() with differing arguments. SIGN_IN_MODE_NONE doesn't seems to be an option for the parameter, so I think you're calling connect() in one case and connect(int) in another (with SIGN_IN_MODE_OPTIONAL). Check that out and see if you can make them consistent.
Also, I believe callbacks for GoogleApiClient are onConnected(Bundle) and onConnectionFailed(ConnectionResult)


text:
Q: Endogenous sample selection vs exogenous sample selection I am trying to understand how bias differs between exogenous sample selection and endogenous sample selection.
To give a concrete example, I am trying to understand the relationship between income, household size, and age on savings:
$$ savings = \beta_0+\beta_1\textrm{income}+\beta_2\textrm{householdSize}+\beta_3\textrm{age} + u$$
From my understanding of endogenous sample selection, if our sampling is biased such that we only manage to capture people with high savings (e.g. people who save over $50k), this is an issue as our sample is not representative of the true population parameter which we are estimating. Then there are issues with the biasedness of the estimators.
Now it seems that exogenous sample selection on the other hand is "unbiased [because] the regression function E(savings|income, age, size) is the same for any subset of the population described by income, age or size" - Woolridge, 2012.
What I struggle to understand is that if we are selecting a sample based on the exogenous variables (e.g. income, age etc.), then aren't we implicity also performing endogenous sample selection?
For example, if we are selecting of greater age, we might expect them to have more savings so therefore higher savings is over-represented in our sample --> this seems analogous to the endogenous sample selection described in my first example of selecting only 50k + savings individuals in the sample.


text:
Q: Map a half sliced unit disk to upper half plane  "half sliced unit disk"
Can somebody tell me how to map this conformally to the upper half plane? I think the symmetry principle should be applied here but stuck on that for hours. Pardon my hasty sketch, this is a unit disk cut at every 45 degree.

A: It is easier to map onto the unit disk, because it has the same sort of symmetry as this domain. (Then of course you can map it onto halfplane.) So, the goal is to somehow "retract" these spikes  into the boundary of the disk.
Take one of these eight pieces, say the sector $0<\theta<\pi/4$. This means we make additional cuts along $re^{i\theta }$ with $0\le r<1/2$, $\theta=0,\pi/4$. Mark them with dashed lines. The sector can be mapped on upper halfdisk  by $z\mapsto z^4$, and then onto lower halfplane   by $z\mapsto \left(z+\frac{1}{z}\right)$ (Joukowski map). In the process, the dashed lines turned into $(-\infty, a)$ and $(a,\infty)$ where $a$ is some positive number that you can find yourself.
Apply $z\mapsto 2z/a$, so that the dashed line turn to $(-\infty,-2)$ and $(2,\infty)$. Then apply the inverse of the Joukowki map, thus mapping the lower halfplane back to upper half-disk. The dashed lines become radii $(-1,0)$ and $(0,1)$. Finally, apply $z\mapsto z^{1/4}$ to return to the sector of the opening angle $\pi/4$. The only thing we achieved so far was to map all solid lines to the circular boundary, leaving the radii dashed. Finally, use reflection across dashed lines, in effect erasing them. This means that, without any changes in the formula, you now have a map of the entire domain onto the unit disk.

A: Did you look at the Cayley Transform,
$$f(z) = \frac{z- i}{z + i}$$
which maps (conformally) the upper half-plane onto the unit disk?


text:
Q: Calculate cumulative sum (cumsum) floored at zero I'd like to modify the cumsum functions. I would like negative values to be changed into 0. And also when there is a new D value different from 0 then use D-S.
Below example:
TD <- data.frame(product = rep("A", 7),
                 data = seq(as.Date("2020-01-01"), as.Date("2020-01-07"), by = "day"),
                 D = c(74, 0, 0, 0, 0, 20, 10), S = c(20, 30, 20, 5, 2, 4, 5))

TD <- TD %>% group_by(product) %>%  mutate(result = cumsum(D) - cumsum(S))

> TD
# A tibble: 6 x 5
# Groups:   product [1]
  product data           D     S result      I expected
  <chr>   <date>     <dbl> <dbl>  <dbl>
1 A       2020-01-01    74    20     54          54
2 A       2020-01-02     0    30     24          24
3 A       2020-01-03     0    20      4           4
4 A       2020-01-04     0     5     -1           0
5 A       2020-01-05     0     2     -3           0
6 A       2020-01-06    20     4     13          16
7 A       2020-01-07    10     5     18          21

A: I think this function does what you want
pos_cumsum <- function(x) {
  cs <- cumsum(x)
  cm <- cummin(cs)
  return (cs - pmin(cm, 0))
}

TD<- TD%>% group_by(product) %>%  mutate(result = pos_cumsum(D-S))
TD
#> # A tibble: 7 x 5
#> # Groups:   product [1]
#>   product data           D     S result
#>   <chr>   <date>     <dbl> <dbl>  <dbl>
#> 1 A       2020-01-01    74    20     54
#> 2 A       2020-01-02     0    30     24
#> 3 A       2020-01-03     0    20      4
#> 4 A       2020-01-04     0     5      0
#> 5 A       2020-01-05     0     2      0
#> 6 A       2020-01-06    20     4     16
#> 7 A       2020-01-07    10     5     21

Although I'd wonder about whether the D happens before or after the S...

A: You can customize the rule of cumulative sums by accumulate() from purrr.
library(dplyr)
library(purrr)

TD %>%
  group_by(product) %>%
  mutate(result = accumulate(D-S, ~ pmax(0, .x + .y), .init = 0)[-1])

# # A tibble: 7 x 5
# # Groups:   product [1]
#   product data           D     S result
#   <chr>   <date>     <dbl> <dbl>  <dbl>
# 1 A       2020-01-01    74    20     54
# 2 A       2020-01-02     0    30     24
# 3 A       2020-01-03     0    20      4
# 4 A       2020-01-04     0     5      0
# 5 A       2020-01-05     0     2      0
# 6 A       2020-01-06    20     4     16
# 7 A       2020-01-07    10     5     21


text:
Q: Search proc_dir_entry by name I need to get pointer to proc_dir_entry by it's name (path).
I see in the Linux source that proc entries are in double-linked list
struct proc_dir_entry {
    .....
    struct proc_dir_entry *next, *parent, *subdir;

So, I could probably loop over the list.
Is there any ready solution for it or should I do myself?

A: This code exists but definitely not exported. See xlate_proc_name at fs/proc/generic.c.


text:
Q: trying to pull from multiple tables and displaying the different information So I have been searching and doing trial and error for several days now, and Im turning to here for help.
I have created a page on my website that pulls a schedule information from a table on a database and displays it to the webpage. I am trying to pull a color scheme from a second table in the same DB, when the name on the first table matches the name on the second table, only that name will be displayed in the different color assigned to it. MY tables look as follows:
TBL1:
id    time    timeframe   Mon     Tues    Wed     Thur    Fri     Sat     Sun
1      12a     00:00:00   Name1   Name2   Name3   Name2   Name5   Name6   Name7
2      1a      01:00:00   Name1   Name2   Name3   Name2   Name5   Name4   Name3
3      2a      02:00:00   Name1   Name2   Name4   Name2   Name2   Name6   Name2
4      3a      03:00:00   Name2   Name2   Name4   Name2   Name3   Name3   Name2
ect
TBL2:
id    Name    Color
1     Name1   #hexcolor
2     Name2   #hexcolor2
3     Name3   #hexcolor3
ect

    $query = array('select' => "*",
               'tbl' => "Schedule");
$query2 = array('select' => "name, color",
               'tbl' => "dj_colors");

$name = "select t1.*, Monday.color, Tuesday.color, Wednesday.color, Thursday.color, Friday.color, Saturday.color, Sunday.color

FROM Schedule t1
     JOIN dj_colors Monday
     ON t1.Monday = Monday.name,
     JOIN dj_colors Tuesday
     ON t1.Tuesday = Tuesday.name,
     JOIN dj_colors Wednesday
     ON t1.Wednesday = Wednesday.name,
     JOIN dj_colors Thursday
     ON t1.Thursday = Thursday.name,
     JOIN dj_colors Friday
     ON t1.Friday = Friday.name,
     JOIN dj_colors Saturday
     ON t1.Saturday = Saturday.name,
     JOIN dj_colors Sunday
     ON t1.Sunday = Sunday.name";

$DB = new DB();
$result = $DB->select_multi($query);

foreach ($result as $arrayLoop) {
    $printout .= "
";
    foreach ($arrayLoop as $field => $data) {
        if ($field == 'id' || $field == 'TimeFrame') continue;
        if ($data === $name) $printout .= "".$data."	";
        else $printout .= "".$data."	";
    }
    $printout .= "
";
}

EDIT* This is what I've come up with and trying, but I think I am still missing something as its still not working like I want it to. I went a head and gave the names of the actual tables that I'm using in proper format. Still not pulling colors, but I'm not getting any errors. Please bear with me, I am still learning. I'm not asking for the answer, just where to look and some helpful tips.

A: I think you need to learn about joins.  You can return the colors in the same query as the names, by joining them in:
select t1.*, mon.color, tue.color, . . . sun.color
from table1 t1 join
     table2 mon
     on t1.name = mon.name join
     tale2 tue
     on t1.tue = tue.name
     . . .
     table2 sun
     on t1.sun = sun.name

The expression:
SELECT color FROM tbl2 WHERE name

Will probably return no rows.  With no comparison, name will be converted to an int, based on the initial digits at the front.  If it starts with an alpha character, it will be transformed to 0, which is false, so no rows are returned.


text:
Q: Getting source of the websites using file_get_content I have a list of a couple of thousands websites. I have to iterate over them, and in each iteration - call file_get_contents of the given url, search for some information from the source using regex, and write it to another file.
Ok, the thing is - it's very, very slow. I divided the whole process into searching for about 50 urls each time I refresh the page. But:

*

*I'd have to refresh the page until I get to a couple of thousand

*even with only 50 urls, I get 30sec time exceeded

Is there a way to speed this up?

A: set_time_limit ( int $seconds ) could help you to increase the maximum execution time.
http://php.net/manual/fr/function.set-time-limit.php
I assume you're using your script frow a browser. Maybe you should consider execution from command line, since it's better for long execution time scripts.


text:
Q: c# reflection on ObservableCollection We're reflecting a .net dll that is a silverlight dll:
Type:System.Collections.ObjectModel.ObservableCollection`1[product.entity.Customer]

How to handle the '1?
The observable collection is declared like this:
ObservableCollection<product.entity.Customer> list = new ObservableCollection<product.entity.Customer>();

Where product.entity.Customer is just a POCO.
My question is not around the POCO but the reflection with the '1.
How to determine when/how to reflect the object held by the observable collection?
...
existingTypes = loadedAssembly.GetTypes();
...
flags_plus = BindingFlags.DeclaredOnly | BindingFlags.Public |    BindingFlags.Instance | BindingFlags.Static;

propertyInfo = type.GetProperties(flags_plus);
...
propertyInfo.PropertyType had the '1 in it...

A: Call GetGenericTypeArguments() to see the list of types passed as type parameters.


text:
Q: Meaning of flux 2-integral Can someone please explain the meaning of flux 2-integral in this sentence:

Mass is evaluated as a flux 2-integral at the asymptotic infinity.

For asymptotic infinity, I believe it is as explained in this Math.SE post.

A: A 2-integral means an integral over a two-dimensional hypersurface.
Flux means the "flow" of some quantity across this surface. Mathematically, you are usually integrating the components of some tensor perpendicular to the hypersurface.


text:
Q: python - finding cosine similarity between two groups of vectors in the most efficient way I am trying to calculate the average cosine similarity between two groups of sentences. After converting the sentences to embeddings, I need to calculate avg. similarities in the most efficient way. Here, what I have tried and the time is taken. Is there any way to improve this calculation?
I also put the slower approaches to help you to understand the case.
X_num is the pandas.Series of embedding vectors, each row is generally 512, 768, 1024 or 2048 long.
class1_indexes : all the indexes of the instances that belong to class 1.
class2_indexes : all the indexes of the instances that belong to class 2.
I need to calculate cosine similarities between each vector pair from class 1 and class 2. Totally, my output should be a cosine similarity vector of len(class1_indexes)*len(class2_indexes ) long.
I edited the code as it includes the test case and you can see that run times for the approaches are like:
t1 > t2 > t3
The third approach is faster 20x times. But I'm looking for much faster approaches.
Thanks in advance.
sample_in_each_class = 1000
X_num = pd.Series([np.random.random(10) for i in range(2*sample_in_each_class)])
class1_indexes = list(range(sample_in_each_class))
class2_indexes = list(range(sample_in_each_class,2*sample_in_each_class))

approach 1
def cosine_similarity(vec1, vec2):
    norm1 = np.linalg.norm(vec1)
    norm2 = np.linalg.norm(vec2)
    if norm1 == 0:
        norm1 += 0.00001
    if norm2 == 0:
        norm2 += 0.00001
    return np.dot(vec1, vec2)/(norm1*norm2)

approach1 = []
for idx1 in class1_indexes:
    for idx2 in class2_indexes:
        approach1.append(cosine_similarity(X_num.loc[idx1], X_num.loc[idx2]))

approach 2
import itertools
vectors_product = itertools.product(X_num[class1_indexes], X_num[class2_indexes])
vectors_product = pd.Series(list(vectors_product))
approach2 = vectors_product.apply(lambda x: cosine_similarity(x[0], x[1]))

approach 3
vectors_product = itertools.product(X_num[class1_indexes], X_num[class2_indexes])
vectors_product = np.array(list(vectors_product))
first_part = vectors_product[:,0,:]
second_part = vectors_product[:,1,:]

numerator = np.sum(np.multiply(first_part, second_part), axis=1)
denominator = (np.multiply(np.linalg.norm(first_part, axis=1),
                           np.linalg.norm(second_part, axis=1)))
approach3 = numerator / denominator

A: I think the most efficient way is:

*

*Convert your data to two numpy ndarrays, an array for each group. I assume rows are embedding vectors and arrays are called X1 and X2.

*Do X/np.linalg.norm(X, axis=1) on each array.

*Then do np.dot(X1, X2.T)

*Then flatten the resulting matrix if you want.


text:
Q: Best Way to Send Scheduled E-Mail in .NET MVC3 Application using MVCMailer I am working on a .NET MVC3 C# Application. This application is hosted on our own Server.
Now I want to Send Scheduled Email in my application like daily(at a specific time),Weekly, monthly and so on...
Currently I am using MVCMailer to send Emails in my application.
I tried Fluent Scheduler to send scheduled Emails, but it doesn't works with MVCMailer. It Works fine if I send mails without MVCMailer and for other scheduling jobs.
It gives me a ERROR NULLReferenceException and says HTTPContext cannot be null.
What can I do to solve this problem.
Also suggest me which will be the best way to send E-mails in my applicaton.

*

*Windows Service (Having own server)

*Scheduler (Fluent Scheduler)

*SQL Scheduled jobs

I am attaching ERROR snapshot:

A: It could be that MVCMailer depends on an HttpContext, which will not exist on your scheduled threadlocal's.
You could consider scrapping MvcMailer and implementing your own templating solution.  Something like RazorEngine (https://github.com/Antaris/RazorEngine), which gives you the full power of Razor without having to run ontop on an Http stack.  You could still source your templates from disk so that your designers could modify it.
Then you could mail the results using the standard classes available from .net.
For e.g.:
string template = File.ReadAllText(fileLocation);//"Hello @Model.Name, welcome to RazorEngine!";
string emailBody = Razor.Parse(template, new { Name = "World" });

SmtpClient client = new SmtpClient();
client.Host = "mail.yourserver.com";
MailMessage mm = new MailMessage();
mm.Sender = new MailAddress("foo@bar.com", "Foo Bar");
mm.From = new MailAddress("foo@bar.com", "Foo Bar");
mm.To.Add = new MailAddress("foo@bar.com", "Foo Bar");
mm.Subject = "Test";
mm.Body = emailBody;
mm.IsBodyHtml = true;
client.Send(mm);

Obviously you could clean this all up.  But it wouldn't take to much effort to use the above code and create some reusable classes.  :)
Since you already have the FluentScheduler code set up, you may as well stick with that I guess.  A windows service does also sound appealing, however I think that it's your call to make.  If it's a simple mail service you are after I can't think of any reason not to do it via FluentScheduler.

I have created a full example of this available here: https://bitbucket.org/acleancoder/razorengine-email-example/src/dfee804d526ef3cd17fb448970fbbe33f4e4bb79?at=default
You can download the website to run locally here: https://bitbucket.org/acleancoder/razorengine-email-example/downloads
Just make sure to change the Default.aspx.cs file to have your correct mail server details.
Hope this helps.

A: Since MVC Mailer works best in the HTTP stack (i.e. from controllers), I've found that a very reliable way to accomplish this is by using Windows Task Schedule from a server somewhere.  You could even spin up a micro instance on Amazon Web Server.
Use "curl" to call the URL of your controller that does the work and sends the emails.
Just setup a Scheduled Task (or Cron if you want to use *IX) to call "c:\path_to_curl\curl.exe http://yourserver.com/your_controller/your_action".
You could even spin up a *IX server on AWS to make it even cheaper.


text:
Q: Parse From Text File into String output So I have a text file called employees.txt that looks like this...
Billy Madderson, M, 34
Allison McGever, F, 32
Bill Nye, M, 35

I'm trying to write a sed script that will read in the text file then output it in the format
"< name > is a < gender >, and is < age > years old now."
I know I need to set the IFS=, but I'm stuck on how to place the information in the string. Any input is greatly appreciated!

A:
I know I need to set the IFS=

I don't see why this would be necessary. As far as I know sed doesn't use IFS at all.
Replace the first , with is a, M/F by man/woman, the second , with and is and so on. The only tricky part is to only replace the M/F in the second column instead of the first M/F you come across. Luckily, after the second column there are no letters anymore, so that simplifies things.
sed 's/, M/ is a man/;s/, F/ is a woman/;s/, /, and is /;s/$/ years old now./' file

For your example the output is
Billy Madderson is a man, and is 34 years old now.
Allison McGever is a woman, and is 32 years old now.
Bill Nye is a man, and is 35 years old now.


text:
Q: Operator overloading Why is overloaded operator= mandated to be a member function ($13.5.3), but not a compound assignment operator e.g. operator+= ($13.5.2)? Am I overlooking something here?

A: A copy assignment operator=, as a member, is always provided by the compiler if the user doesn't define one. I believe that it was only for simplicity and to avoid unexpected ambiguities that it was made a requirement that operator= can't be defined as a free function.
Conversion operators take care of the case when you want to assign from a user-defined type to a built-in type.

A: The sections you reference have this to say about hiding base class implementations of operator=

Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user (12.8),

This may also be the answer to your question, since the compiler needs to know if it should generate an operator= it must know if such an operator was defined, if it could be defined outside the class the compiler couldn't know if it was defined in a different translation unit.
e.g.
//a.h
class A { }; // compiler thinks A::operator= should be implicitly defined

//b.h
#include "a.h"
A& operator=(A& This, const A& other) { /*...*/ } // Oops it's explicitly defined

Compound operators, on the other hand, are not implicitly defined therefore there is no reason to force them to be declared as member functions.

A: Along with default and copy constructors, operator= is also treated specially in C++. That means, even if you don't declare one, the compiler will provide a default implementation for you. But default implementations are not always the behaviour that suits your class' needs, that's why you should declare them explicitly (or hide them, by assigning private visibility).
And why is default constructor, copy constructor and assignment operator so special? Because  they are involved in standard variable initialization and parameter passing: when you pass a class-typed parameter to a function by value (not by reference or pointer), these operations are called to copy it's content to the stack.

A: As stated by Charles, a copy assignment operator= is always provided by the compiler if the user doesn't define one. This compiler provided member function would always have precedence over a non-member function, so even if you could define it as a non-member function, it wouldn't be called.


text:
Q: Not Able to Install Angular CLI I am getting below error while installing angular cli.
Please help me
 C:\Users\A737539>npm install -g @angular/cli@6.1.3
    npm ERR! code E502
    npm ERR! 502 Parent proxy unreacheable: @angular/cli@6.1.3

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\A737539\AppData\Roaming\npm-cache\_logs\2018-11-21T09_33_42_128Z-debug.log

Thanks,
Pushkar

A: Here is how you can get npm work when on a proxy network :
create a .npmrc file with below fields :

registry= //local artifactory site if any - remove if not
strict-ssl=false
cache=.\npmcache
prefix=.\npm
package-lock=false
loglevel=verbose
proxy= http://domain\username:password@servername:port/
https-proxy= http://domain\username:password@servername:port/
unsafe-perm=true
sass-binary-site= // if any local binary site is present - remove if not

Now place this file into mentioned location :  C:\Users\A737539> and then
run npm install command it will work.
Once done , You can place this file inside repository (any new app created using cli) so that each time you don't have to set proxies manually.


text:
Q: Removing Json object name using Logtash I'm trying to parse the following json using logstash
   {
    "payload": "{\"class\":\"OpenLoyalty\\\\Component\\\\Account\\\\Domain\\\\Event\\\\PointsTransferHasBeenExpired\",\"payload\":{\"accountId\":\"1cbd42b8-1b1f-4a13-a28f-eefeb73a64b0\",\"pointsTransferId\":\"e82c96cf-32a3-43bd-9034-4df343e5f111\"}}"
}

using this filter :
    input {
        jdbc {
            jdbc_connection_string => "jdbc:postgresql://localhost:5432/openloyalty"
            jdbc_user => "openloyalty"
            jdbc_password => "openloyalty"
            jdbc_driver_library => "C:\logstash\postgresql-42.2.12.jar"
            jdbc_driver_class => "org.postgresql.Driver"
            statement => "SELECT payload from events where events.id=130;"
        }
    }
    filter {
          json {
            source => "payload"
            remove_field => ["class"]
          }

    }
    output {
        stdout { codec => json_lines }
    }

I get this output:
    {
    "@version": "1",
    "@timestamp": "2020-05-12T11:27:15.097Z",
    "payload": {
        "accountId": "1cbd42b8-1b1f-4a13-a28f-eefeb73a64b0",
        "pointsTransferId": "e82c96cf-32a3-43bd-9034-4df343e5f111"
    }
   }

however, what I'm looking for is like this:
{
"@version": "1",
"@timestamp": "2020-05-12T11:27:15.097Z",
 {
    "accountId": "1cbd42b8-1b1f-4a13-a28f-eefeb73a64b0",
    "pointsTransferId": "e82c96cf-32a3-43bd-9034-4df343e5f111"
 }
}

how can I remove the "payload" name from my Json object?

A: You can use the mutate filter with the following config after your json filter.
mutate {
    rename => {
        "[payload][accountId]" => "accountId"
        "[payload][pointsTransferId]" => "pointsTransferId"
    }
    remove_field => ["[payload]"]
}

This will rename your fields and remove the empty payload json object after the rename.


text:
Q: Updating a table with over 25,000 entries I want to try to set two values in a SQL table based on a search in another table. My query is the following:
UPDATE $postmeta
SET meta_key = '_bbps_topic_status',
    meta_value = '1'
    WHERE post_id IN (
    SELECT ID
    FROM $posts
    WHERE post_type='topic'
   )

I want to do this for the entire table of 25,148 rows, but I get a memory error even after increasing all the limits on the server. I know that MySQL doesn't allow you to batch operations in groups of, say 500, but is there any way to write a script that would divide this operation up into smaller chunks?
Thanks in advance!
EDIT: The query includes a date range:
UPDATE $postmeta
SET meta_key = '_bbps_topic_status',
    meta_value = '1'
    WHERE post_id IN (
    SELECT ID
    FROM $posts
    WHERE post_type='topic'
    AND DATE_SUB(
        CURDATE(),
        INTERVAL 30 DAY
        ) <= post_date
   )

A: Use join method and an index on post_id from $postmeta table  will be helpful
UPDATE $postmeta  m
JOIN $posts p ON(p.ID = m.post_id )
SET m.meta_key = '_bbps_topic_status',
    m.meta_value = '1'
 WHERE p.post_type='topic'
 AND p.post_date <= NOW() - INTERVAL 30 DAY

Note you are using a sub query which will run for each row instead use join also add index on your date column to improve the performance of your query


text:
Q: Preparing for "differential forms in algebraic topology"? I'd very much like to read "differential forms in algebraic topology".
Apart from background in calculus and linear algbra I've thoroughly went through the first 5 chapters of Munkres.
I'm thinking of reading "An introduction to manifolds" by Tu next.
1) Will it provide me with all I need to tackle Bott\Tu?
2) Are the exercises in it sufficient or should i complement it with another text for problems? (I read in a review somewhere that the exercises are too easy)

A: You would definitely need some basic understanding of manifolds, but I don't think you will need too much. I think you will need definitions, closed submanifolds, immersions/submersions, tangent and cotangent bundles, vector fields and differential forms. Though the book defines differential forms, it chooses algebraic approach. So it would be difficult to read if you don't know what differential forms really are. But you don't need to read the whole book on manifolds. If you will need some extra-stuff, you can always look it up.
Loring Tu's book seems to be a bit too slow (at least for me). I would recommend Frank Warner's "Foundations of Differentiable Manifolds and Lie Groups". You will only need Chapters 1 and 2 (except "Differential ideals"). Altogether it is only about 50 pages, and I think Warner gives a concise and clear introduction to the subject.
In general, I recommend after getting a bit comfortable with manifolds to start reading Bott-Tu. If you will see some unfamiliar term, you can always return back and learn about it. Otherwise you have a risk of spending too much time for learning a lot of things that you don't need for the book, and some of them might not be important at all for you in the near future.
Speaking about exercises in Bott-Tu, there are indeed not too many of them, and most of them are pretty easy. But surprisingly enough, even though I didn't solve tons of exercises, I have learned a lot, and I have gained a lot of skills from this book. So I personally don't think you will need some extra-book with exercises.
But if you will feel that you need some more problems on algebraic topology, there are a lot of nice books. I can recommend Hatcher's book (though it is again a bit too wordy in my opinion), or these notes by Sossinsky. They are not following Bott-Tu book, but there are a lot of common topics.


text:
Q: Angular Elements doesn't include Material Theme css properly I have included Angular Material in my angular element project. I have included all the references how the documentation suggests, but when I build seems like angular the material theme isn't included at all.
This is the link for watching what I mean: https://next.plnkr.co/edit/3JIbOfnyKiefS31N?open=lib%2Fscript.js
Material module for wrapping all the components
import {NgModule} from '@angular/core';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatFormFieldModule} from '@angular/material';

@NgModule({
  exports: [
    MatSelectModule,
    MatIconModule,
    MatInputModule,
    MatFormFieldModule,
  ]
})
export class MaterialModule {}

AppModule
import { BrowserModule } from '@angular/platform-browser';
import {Injector, NgModule} from '@angular/core';

import {GalleryComponent} from './gallery/gallery.component';
import {createCustomElement} from '@angular/elements';

import {ImageService} from './gallery/image.service';
import { ImageComponent } from './gallery/image/image.component';
import { ImageDetailsComponent } from './gallery/image-details/image-details.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from './material.module';

@NgModule({
  declarations: [
    GalleryComponent,
    ImageComponent,
    ImageDetailsComponent
  ],
  imports: [
    MaterialModule,
    BrowserAnimationsModule,
    BrowserModule
  ],
  entryComponents: [GalleryComponent],
  providers: [ImageService],
})
export class AppModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    const custom = createCustomElement(GalleryComponent, { injector: this.injector });
    customElements.define('slim-gallery', custom);
  }
}

The Style
@import "~@angular/material/prebuilt-themes/deeppurple-amber.css";

body {
  font-family: Roboto, Arial, sans-serif;
  margin: 0;
}

.basic-container {
  padding: 30px;
}

.version-info {
  font-size: 8pt;
  float: right;
}

Component template html
<mat-form-field>
  <mat-label>Favorite food</mat-label>
  <mat-select>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

A: I was facing the same issue.
Try adding this line (this is for indigo theme) on you app.component.css
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

And then on your component ts use encapsulation none, like follows:
@Component({
 ...,
 encapsulation: ViewEncapsulation.None
})

A: In case someone is interested in the solution. My problmen was caused by ngZone: 'noop' in the main.ts file. It disables change detection.
So changing this
platformBrowserDynamic()
.bootstrapModule(AppModule, {
ngZone: 'noop'
})
.catch(err => console.error(err));
to this
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch((err) => console.error(err));
solved my problem with Angular Material Elements.

A: You have imported this:
import {MatFormFieldModule} from '@angular/material';

But the Material API documentation specifies the import like this:
import {MatFormFieldModule} from '@angular/material/form-field';

On stackBlitz:
https://stackblitz.com/edit/angular-3l12yn


text:
Q: Permission denied on apache2.conf (ubuntu, new linux user here) I am new to Linux and Apache and have beginners permissions issues ...
I installed Ubuntu and has installed and configured apache and PHP via SSH (putty) from my windows box. apt-get
I have installed WinSCP and has used that for file transfers from Windows to Ubuntu. That is working fine after i figured out how to the permissions on the website directory.
Now I have new permission problems when I try to edit /etc/apache2/apache2.conf
No matter what i try i get a permission denied.
I am trying to download the file using WinSCP, edit it windows and then upload the file again. This results in a
Permission denied.
Error code: 3
Error message from server: Permission denied
This is my current permissions:
drwxrwxr-x  8 root root    4096 Nov 16 16:24 apache2
-rwxrwxr-x 1 root root  7115 Jul 21 19:56 apache2.conf
Can anyone point me in to direction?

A: 1) try to SCP as root user
2) try to login as root with SSH and use mcedit to edit the file
please note: in some systems, ssh to root user is prohibited by default, so you have to ssh to your user, and give the command: su (and enter the password) or sudo su if you have sudo rights.
to access via ssh, use PUTTY.
once you're in, install mc: apt-get install mc
after this, you can use mcedit: mcedit /etc/apache2/apache2.conf
mcedit is a really well designed editor, it's quite easy to use.


text:
Q: Trying to get a result not displaying I'm just trying to get something basic to appear for now and it's not working. It should display 1 on the screen. Is my logic wrong? I paste my statement in console and get 1.
<?php

$sql = mysqli_query("Select moist_measure_avail from sigh_in_account where moist_measure_avail = '1'");

$result = mysqli_fetch_array($sql);

echo $result['moist_measure_avail'];

A: $sql = mysqli_query("Select moist_measure_avail from sigh_in_account where moist_measure_avail = '1'");

pass connection as first param in above method. something like this
$sql = mysqli_query($conn,"Select moist_measure_avail from sigh_in_account where moist_measure_avail = '1'");

where $conn is mysql connection

A: First of all you should have to create a connection
<?php
    $conn = mysqli_connect("localhost "," root","","dbname");
?>

And then you have to include the conn variable in your query
$sql = mysqli_query( $conn, " SELECT moist_measure_avail from sigh_in_account WHERE moist_measure_avail = '1'");

The sql statements must be either all caps or all small


text:
Q: Change console text kerning in vb.net I'm trying to make each letter a "square" essentially, so each letter is no more tall than it is wide, in vb.net. Is this possible? If so, how? I can't seem to find anything, and I've been searching hard.
Thanks for the help!

A: Why dont you just use a fixed size font ? Or create your own font ?

A: The Windows API has a function called SetCurrentConsoleFontEx which you could pinvoke. It accepts a width and height, font etc. Depending on how it handles these you may also need to make and add a 'square font' to the registry list of allowed fonts (example of adding a new font to the console here.)


text:
Q: I wrote a JavaScript to move a cat on canvas: "ฅ(*ΦωΦ*) ฅ" But the cat jumps weirdly I created a script that uses HTML input buttons to move a cat on canvas. Each click moves the cat by 10 pixels in the direction that is clicked (moveUp(); moveDown();moveLeft(); moveRight();). This script works fine for the first 10-20 clicks, but then the cat eventually jumps around or is stuck in one spot.
I have no idea why it behaves in this way. can anyone help?
The program is on jsfiddle, you can test it out
https://jsfiddle.net/rockmanxdi/h2sk2sjz/2/
JavaScript code is hereunder:
let surface=document.getElementById("drawingArea");
let ctx=surface.getContext("2d");
let cor_x;
let cor_y;

/** draw a cat
    *   input the coordinates x and y for the center of the cat
    *   does not return, output the drawing only.
    */
let drawCat = function (x, y) {

        ctx.save();
        ctx.translate(x, y);
        ctx.fillText("ฅ(*ΦωΦ*) ฅ", -20,-5);
        ctx.restore();

        };

let updateCoordinate = function(x_increment,y_increment){
        console.log("before:" + cor_x + "/" + cor_y);
        cor_x += 10 * x_increment;
        cor_y += 10 * y_increment;
        console.log("updated:" + cor_x + "/" + cor_y);
};

let moveUp = function (){
    updateCoordinate(0,-1);
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

let moveLeft = function (){
    updateCoordinate(-1,0);
    console.log( cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

let moveRight = function (){
    updateCoordinate(1,0);
    console.log( cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

let moveDown = function (){
    updateCoordinate(0,1);
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

let reset =  function(){
    cor_x=surface.width/2.0;
    cor_y=surface.height/2.0;
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
}

drawCat(200,200);

html body:

<canvas width="400" height="400" id="drawingArea" style="border:solid">cat image</canvas>

    <input type="button" id="resetBtn" value="reset" onclick="reset();" />

    <input type="button" id="upBtn" value="Up" onclick="moveUp();"/>

    <input type="button" id="leftBtn" value="Left" onclick="moveLeft();"/>

    <input type="button" id="rightBtn" value="Right" onclick="moveRight();"/>

    <input type="button" id="downBtn" value="Down" onclick="moveDown();"/>

By the way, I put console.log() inside updateCoordinate(); and move UP/Down/Right/Left(); functions to track the value of the x and y coordinates of the cat. Press F12 to track the value.

A: 1) I replaced only all let to var (everything is working good):

var surface=document.getElementById("drawingArea");
var ctx=surface.getContext("2d");
var cor_x;
var cor_y;

/** draw a cat
 * input the coordinates x and y for the center of the cat
 * does not return, output the drawing only.
 */
var drawCat = function (x, y) {

  ctx.save();
  ctx.translate(x, y);
  ctx.fillText("ฅ(*ΦωΦ*) ฅ", -20,-5);
  ctx.restore();

  };

var updateCoordinate = function(x_increment,y_increment){
        console.log("before:" + cor_x + "/" + cor_y);
        cor_x += 10 * x_increment;
        cor_y += 10 * y_increment;
        console.log("updated:" + cor_x + "/" + cor_y);
};

var moveUp = function (){
    updateCoordinate(0,-1);
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

var moveLeft = function (){
    updateCoordinate(-1,0);
    console.log( cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

var moveRight = function (){
    updateCoordinate(1,0);
    console.log( cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

var moveDown = function (){
    updateCoordinate(0,1);
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
};

var reset =  function(){
  cor_x=surface.width/2.0;
  cor_y=surface.height/2.0;
    console.log(cor_x + "/" + cor_y );
    ctx.clearRect(0,0,surface.width,surface.height);
    drawCat(cor_x,cor_y);
}

drawCat(200,200);

    <canvas width="400" height="400" id="drawingArea" style="border:solid">cat image</canvas>

        <input type="button" id="resetBtn" value="reset" onclick="reset();" />

        <input type="button" id="upBtn" value="Up" onclick="moveUp();"/>

        <input type="button" id="leftBtn" value="Left" onclick="moveLeft();"/>

        <input type="button" id="rightBtn" value="Right" onclick="moveRight();"/>

        <input type="button" id="downBtn" value="Down" onclick="moveDown();"/>

It is bug with let variable:
From console log:

(index):96 before:160/390
(index):99 updated:160/400
(index):126 160/280

Within updateCoordinate: cor_x = 160; cor_y = 400 BUT within moveRight (or moveLeft, moveUp, moveDown) cor_x = 160; cor_y = 280


text:
Q: Settings only applying on second time sidebar opened REFrostedViewController I'm trying to resize my sidebar, but the changes are only reflecting after the only time I open the sidebar.
@implementation MenuViewController

- (void)viewDidLoad
{
    [self.frostedViewController setLimitMenuViewSize:TRUE];
    [self.frostedViewController setMenuViewSize:CGSizeMake(200, [[UIScreen mainScreen] bounds].size.height)];
}

If someone could help me, that would be great.
Thank you!

A: You could put these configurations in the REFrostedViewController subclass. For example (supposing you are using storyboards), you could configure the menu right below the view controllers assignment, e.g. (but, remember, you can put the config everywhere in the REFrostedViewController initialization code)
- (void)awakeFromNib
{
    self.contentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
    self.menuViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"menuViewController"];

    self.limitMenuViewSize  = YES;
    self.menuViewSize       = CGSizeMake(200.0, [UIScreen mainScreen].bounds.size.height);
}

Doing this configuration in the MenuViewController viewDidLoad method causes the config to be applied only AFTER the menu view is loaded for the first time, and so your changes show up only the second time.
Just put the code in the REFrostedViewController subclass (or even in the contentViewController you are using) and you should be fine.


text:
Q: keep getting error "Unresolved reference: valueOf" In in the notes portion of my app i get the error "Unresolved reference: valueOf" in my EquipmentTrackerAllnotes.kt file.
the way my app operates is when you open the app initially it opens up to the dashboard the main home screen, then there is a navigation drawer on the side. One of the fragments in the navigation drawer is my "EquipmentTracker" aka the area where you can make notes of equipment the user may have. In side there you can add notes, delete and edit.
I'm open ears to any recommendations on possible changes i should make as well. But for now my main focus is fixing this error listed above.
EquipmentTracker.kt
package com.example.mechanicsapp

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.FragmentEquipmentTrackerBinding

class EquipmentTracker : Fragment() {

    private var _binding: FragmentEquipmentTrackerBinding? = null
    private val binding get() = _binding!!
    var intent = Intent(requireContext(), EquipmentTracker::class.java)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        //return inflater.inflate(R.layout.sign_in_fragment, container, false)

        // Inflate the layout for this fragment
        _binding = FragmentEquipmentTrackerBinding.inflate(inflater, container, false)
        binding.root
        val helper = MySqliteHelper(requireContext())
        binding.btnDisplay.setOnClickListener(View.OnClickListener {
            intent = Intent(activity, FragmentEquipmentTrackerBinding::class.java)
            startActivity(intent)

            return@OnClickListener

        })
        binding.btnSave.setOnClickListener(View.OnClickListener {
            val model = noteModel()
            model.bumpernumber = binding.bumpernumber.text.toString()
            model.description = binding.description.text.toString()
            model.nsn = binding.nsn.text.toString()
            model.serialnumber = binding.serialnumber.text.toString()
            model.date = binding.date.text.toString()

            if (model.bumpernumber.isEmpty()) {
                binding.bumpernumber.error = "Enter bumper number"
                return@OnClickListener
            }
            if (model.description.isEmpty()) {
                binding.description.error = "Enter description"
                return@OnClickListener
            }
            if (model.nsn.isEmpty()) {
                binding.nsn.error = "Enter nsn"
                return@OnClickListener
            }
            if (model.serialnumber.isEmpty()) {
                binding.serialnumber.error = "Enter serial number"
                return@OnClickListener
            }
            if (model.date.isEmpty()) {
                binding.date.error = "Enter date"
                return@OnClickListener
            }
            val r = helper.saveNote(model)
            if (r) {
                Toast.makeText(context, "note is saved", Toast.LENGTH_SHORT)
                    .show()
            } else {
                Toast.makeText(context, "some thing want wrong", Toast.LENGTH_SHORT)
                    .show()

            }
        })
        return binding.root

    }

}

EquipmentTrackerAllnotes.kt
package com.example.mechanicsapp

import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.adapter.NoteAdapter
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.ActivityEquipmentTrackerAllnotesBinding

@Suppress("NAME_SHADOWING")
class EquipmentTrackerAllnotes : AppCompatActivity() {
    private var adapter: NoteAdapter? = null
    private var binding: ActivityEquipmentTrackerAllnotesBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEquipmentTrackerAllnotesBinding.inflate(layoutInflater)
        setContentView(binding!!.root)
        fetchNotes()
    }

    private fun fetchNotes() {
        val helper = MySqliteHelper(this)
        adapter = NoteAdapter(this, helper.allNotes)
        adapter!!.setOnNoteItemClickListener(object : NoteAdapter.OnNoteItemClickListener {

            override
            fun Onclick(model: noteModel) {
                val builder = AlertDialog.Builder(this@EquipmentTrackerAllnotes)
                builder.setTitle("Important")
                builder.setMessage("Are your sure?")
                builder.setPositiveButton("Yes" ) {

                        dialogInterface, _ ->
                    val helper = MySqliteHelper(this@EquipmentTrackerAllnotes)
                    val check = helper.delNoteById(String.valueOf(model.id))
                    if (check) {
                        fetchNotes()
                        Toast.makeText(this@EquipmentTrackerAllnotes, "Deleted", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(
                            this@EquipmentTrackerAllnotes,
                            "something went wrong",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                    dialogInterface.dismiss()
                }.setNegativeButton(
                    "No"
                ) { dialogInterface, _ -> dialogInterface.dismiss() }
                builder.create().show()
            }

            override fun OnEdit(model: noteModel) {
                val builder = AlertDialog.Builder(this@EquipmentTrackerAllnotes)
                val view: View = LayoutInflater.from(this@EquipmentTrackerAllnotes)
                    .inflate(R.layout.edit_note, null, false)
                val bm = view.findViewById<EditText>(R.id.bumpernumber)
                val des = view.findViewById<EditText>(R.id.description)
                val nsn = view.findViewById<EditText>(R.id.nsn)
                val sn = view.findViewById<EditText>(R.id.serialnumber)
                val date = view.findViewById<EditText>(R.id.date)
                val btnUpdate = view.findViewById<Button>(R.id.btnUpdate)
                bm.setText(model.bumpernumber)
                des.setText(model.description)
                nsn.setText(model.nsn)
                sn.setText(model.serialnumber)
                date.setText(model.date)
                builder.setView(view)
                val alertDialog = builder.create()
                btnUpdate.setOnClickListener {
                    val model1 = noteModel()
                    model1.id = model.id
                    model1.bumpernumber = bm.text.toString()
                    model1.description = des.text.toString()
                    model1.nsn = nsn.text.toString()
                    model1.serialnumber = sn.text.toString()
                    model1.date = date.text.toString()
                    updateNote(model1)
                    alertDialog.dismiss()
                }
                alertDialog.show()
            }
        })
        this.binding?.recyclerView?.setHasFixedSize(true)
        this.binding?.recyclerView?.layoutManager = LinearLayoutManager(this)
        this.binding?.recyclerView?.adapter = adapter
    }

    private fun updateNote(model: noteModel) {
        val helper = MySqliteHelper(this@EquipmentTrackerAllnotes)
        val check = helper.updateNoteById(model)
        if (check) {
            fetchNotes()
            Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "something went wrong", Toast.LENGTH_SHORT).show()
        }
    }
}

in my adapter folder I have NoteAdapter.java
NoteAdapter.java
package com.example.mechanicsapp.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mechanicsapp.Model.noteModel;
import com.example.mechanicsapp.R;
import com.example.mechanicsapp.database.MySqliteHelper;

import java.util.List;

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.viewHolder> {

    List<noteModel> list;
    Activity activity;
    OnNoteItemClickListener listener;
    public NoteAdapter(Activity activity,List<noteModel> list) {
        this.list=list;
        this.activity=activity;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.row_note,null,false);
        return new viewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position) {
        noteModel model=list.get(position);
        holder.bumpernumber.setText(model.getBumpernumber());
        holder.description.setText(model.getDescription());
        holder.nsn.setText(model.getNsn());
        holder.serialnumber.setText(model.getSerialnumber());
        holder.date.setText(model.getDate());
        holder.more.setOnClickListener(view -> {

            PopupMenu menu=new PopupMenu(activity,holder.more);
            menu.getMenuInflater().inflate(R.menu.more_menu,menu.getMenu());
            menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()){
                        case R.id.edit:
                            listener.OnEdit(model);
                            break;
                        case R.id.delete:
                            listener.Onclick(model);
                            break;
                    }
                    return false;
                }
            });
            menu.show();
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    public static class viewHolder extends RecyclerView.ViewHolder{
        TextView bumpernumber,description,nsn,serialnumber,date;
        ImageView more;
        public viewHolder(@NonNull View itemView) {
            super(itemView);
            bumpernumber=itemView.findViewById(R.id.bumpernumber);
            description=itemView.findViewById(R.id.description);
            nsn=itemView.findViewById(R.id.nsn);
            serialnumber=itemView.findViewById(R.id.serialnumber);
            date=itemView.findViewById(R.id.date);
            more=itemView.findViewById(R.id.more);

        }
    }
    public interface OnNoteItemClickListener{
        void Onclick(noteModel model);
        void OnEdit(noteModel model);
    }
    public void setOnNoteItemClickListener(OnNoteItemClickListener listener){
        this.listener=listener;
    }
}

in my database folder i have MySqliteHelper.java & TableSchema.java
MySqliteHelper.java
package com.example.mechanicsapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.google.android.material.tabs.TabLayout;
import com.example.mechanicsapp.Model.noteModel;

import java.util.ArrayList;
import java.util.List;

public class MySqliteHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="note.db";
    private static final int VERSION=1;
    public MySqliteHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String table1="create table "+TableSchema.note.TABLE_NAME+"("+TableSchema.note.ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TableSchema.note.BUMPERNUMBER+" TEXT, "+TableSchema.note.DESCRIPTION+" TEXT,"+TableSchema.note.NSN+" TEXT,"+TableSchema.note.SERIALNUMBER+" TEXT, "+TableSchema.note.DATE+" TEXT );";
        sqLiteDatabase.execSQL(table1);
    }

    public boolean saveNote(noteModel model){
        SQLiteDatabase database=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
        cv.put(TableSchema.note.DESCRIPTION,model.getDescription());
        cv.put(TableSchema.note.NSN,model.getNsn());
        cv.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
        cv.put(TableSchema.note.DATE,model.getDate());
        long id= database.insert(TableSchema.note.TABLE_NAME,null,cv);
        return id != -1;
    }
    public List<noteModel> getAllNotes(){
        SQLiteDatabase database= this.getReadableDatabase();
        String[] cols={TableSchema.note.ID,TableSchema.note.BUMPERNUMBER,TableSchema.note.DESCRIPTION,TableSchema.note.NSN,TableSchema.note.SERIALNUMBER,TableSchema.note.DATE};
        Cursor cursor=database.query(TableSchema.note.TABLE_NAME,cols,null,null,null,null,TableSchema.note.ID+" DESC");
        ArrayList<noteModel> list=new ArrayList<>();
        while (cursor.moveToNext()){
            noteModel model=new noteModel();
            model.setId(cursor.getInt(cursor.getColumnIndexOrThrow(TableSchema.note.ID)));
            model.setBumpernumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.BUMPERNUMBER)));
            model.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DESCRIPTION)));
            model.setNsn(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.NSN)));
            model.setSerialnumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.SERIALNUMBER)));
            model.setDate(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DATE)));
            list.add(model);
        }
        cursor.close();
        database.close();
        return list;
    }

    public boolean delNoteById(String id){
        SQLiteDatabase database=this.getWritableDatabase();
        int d_id=database.delete(TableSchema.note.TABLE_NAME,TableSchema.note.ID+"=?",new String[]{id});
        if (d_id==-1){
            database.close();
            return false;
        }
        database.close();
        return true;
    }

    public boolean updateNoteById(noteModel model){
        SQLiteDatabase database=this.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
        values.put(TableSchema.note.DESCRIPTION,model.getDescription());
        values.put(TableSchema.note.NSN,model.getNsn());
        values.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
        values.put(TableSchema.note.DATE,model.getDate());
        int u_id=database.update(TableSchema.note.TABLE_NAME,values,TableSchema.note.ID+"=?",new String[]{String.valueOf(model.getId())});
        if (u_id==-1){
            database.close();
            return false;
        }
        database.close();
        return true;
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        if (i<i1){
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TableSchema.note.TABLE_NAME);
        }

    }
}

TableSchema.java
package com.example.mechanicsapp.database;

public class TableSchema {

    public static class note{

        public static final String TABLE_NAME="tbl_note";
        public static final String ID="id";
        public static final String BUMPERNUMBER="bumpernumber";
        public static final String DESCRIPTION="description";
        public static final String NSN="nsn";
        public static final String SERIALNUMBER="serialnumber";
        public static final String DATE="date";
    }

}

in my Model folder i have noteModel.java
//noteModel.java
package com.example.mechanicsapp.Model;

public class noteModel {

    private int id;
    private String bumpernumber;
    private String description;
    private String nsn;
    private String serialnumber;
    private String date;

    public noteModel() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBumpernumber() {
        return bumpernumber;
    }

    public void setBumpernumber(String bumpernumber) {
        this.bumpernumber = bumpernumber;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    public String getNsn() {
        return nsn;
    }

    public void setNsn(String nsn) {
        this.nsn = nsn;
    }

    public String getSerialnumber() {
        return serialnumber;
    }

    public void setSerialnumber(String serialnumber) {
        this.serialnumber = serialnumber;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}

fragment_equipment_tracker.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EquipmentTracker">

    <LinearLayout
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/bumpernumber"
            android:hint="Bumper Number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/description"
            android:hint="Enter description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/nsn"
            android:hint="Enter nsn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/serialnumber"
            android:hint="Enter serial number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/date"
            android:hint="Enter date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnSave"
            android:text="Save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnDisplay"
            android:text="Display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

activity_equipment_tracker_allnotes.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EquipmentTrackerAllnotes">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

edit_note.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EquipmentTracker">
    <LinearLayout
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/bumpernumber"
            android:hint="Bumper Number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/description"
            android:hint="Enter description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/nsn"
            android:hint="Enter nsn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/serialnumber"
            android:hint="Enter serial number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/date"
            android:hint="Enter date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btnUpdate"
            android:text="Update"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</RelativeLayout>

//row_note.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_margin="10dp"
        android:padding="10dp"
        cardElevation="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="vertical"
                android:padding="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/bumpernumber"
                    android:textSize="16dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/nsn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/serialnumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/date"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
            </LinearLayout>
            <ImageView
                android:id="@+id/more"
                android:src="@drawable/baseline_more_vert_24"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </RelativeLayout>

    </androidx.cardview.widget.CardView>

</RelativeLayout>

more_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/edit" android:title="edit"/>
    <item android:id="@+id/delete" android:title="Delete"/>
</menu>


text:
Q: Gatsby.js: how to migrate all *.js files to *ts? I'm actively migrating my personal website from pure React to Gatsby. Doing good so far.
Being a TypeScript fan, I make use of it already. One question I have however is whether there's a way to use TypeScript for Gatsby's configuration files or not (gatsby-browser.js, gatsby-config.js, gatsby-node.js, and gatsby-ssr.js). Same question applies to Gatsby plugin configuration/bootstrap files (e.g. typography.js).
Here's what my file system tree looks like.

A: *

*Whatever files in src can be written in ts/tsx, including typography.js.

*All configuration files has to be .js, unfortunately. There's nothing to stop you from compiling those config files with tsc first though!


text:
Q: Unix Touch in Matlab to create a file? This is probably very easy thing but help touch does not return anything, I am trying to create a file. I could find mkdir in Matlab but not touch so how to create a file in Matlab ie the unix-style command $ touch newFile?

A: How about system('touch newfile')?

A: try this then hopefully help !
    http://www.mathworks.com/help/matlab/matlab_env/creating-opening-changing-and-deleting-files-and-folders.html


text:
Q: Symmetric difference of cycles Let C and C' be cycles in a graph G. Prove that the symmetric difference of C and C' decomposes into cycles.
I know that the symmetric difference of C and C' contains only the edges that are in exactly one of C or C'. Since both C and C' are cycles, so d(v) for all v in V(G) must be even. So the difference would include a bunch of edges whose endpoints have even degree. If the degree is at least 2, we have cycle(s). But what if degree = 0? I am not really sure if it could be 0. I need a leg up, please! Thanks.

A: In the context of a question like this one you are only interested in edges
and it is convenient to 'disregard' vertices.
After all you want the symmetric difference of two cycles that have exactly one vertex in common
to be just the same two cycles: you do not want to 'subtract a vertex'.
You also do not want to answer the question: how many vertices has the symmetric
difference of a cycle with itself.
So we will simply assume that you have some underlying set of vertices,
some of which are spanning your cycles, but we do not care about the vertices.
This answers your question "But what if degree=0?": if the degree is 0, there
are no incident edges, so we do not care.
For the rest you can follow the argument you already started:
first show that all degrees in the symmetric difference of two cycles are even,
then show that any graph with only even degrees decomposes into cycles.
Let me know if you need help with any of these parts.
Note that your proof will in fact demonstrate a stronger result:
you can have an arbitrary number of cycles, but as long as you only use
the operations union and symmetric difference the result can be decomposed into cycles.


text:
Q: Where do I place JSON data in Expo project Does having assets in your app mean your app will rely on internet connection when you build and deploy with expo?
My app is using JSON data, and images, and I don't want users to need internet connection to use it, but after releasing it doesn't load up without internet connection and sometimes even crashes.
I am using es6 imports to read the JSON in assets and set Redux state.

A: Edit: from SDK 24 onwards, the answer has changed. You can now bundle some assets within your app binary and do not depend from the CDN anymore.
From the documentation:

Bundle your assets inside your standalone binary
  Expo can bundle assets into your standalone binary during the build process so that they will be available immediately, even if the user has never run your app before. This is important if:
  Your users may not have internet the first time they open your app, or
  If your app relies on a nontrivial amount of assets for the very first screen to function properly.

See the announcement with some neat explanations and graphs here.
Old accepted answer below: I decided to change this as it is no longer correct and I was finding my own answer in a google search. This way we avoid people don´t get wrong information.
Yes, currently your users will need an internet connection. As described in the documentation, assets are currently uploaded to a Content Delivery Network (CDN) and not packaged with your app. Quoting the documentation:

In production
  Each time you publish your app, Expo will upload your assets to Amazon CloudFront, a blazing fast CDN. It does this in an intelligent way to ensure your deploys remain fast: if an asset has not changed since your previous deploy, it is skipped. You don't have to do anything for this to work, it is all automatically handled by Expo.

I hope they change it or make it optional in the future, as I am also interested in apps without internet connection.


text:
Q: Express $2+\sqrt{3} + i$ in the form $ r(\cosθ+i\sinθ)$ I am struggling with $2+\sqrt{3} + i$, to be expressed in the form $r(\cosθ+i\sinθ)$.
The above should transofrm to  $(\sqrt{6}+\sqrt{2})(\cos(\frac{\pi}{12}) + i\sin(\frac{\pi}{12}))$

A: $$2+\sqrt3=\csc30^\circ+\cot30^\circ=\cdots=\cot15^\circ$$
$$2+\sqrt3+i=\cot15^\circ+i=\dfrac1{\sin15^\circ}(\cos15^\circ+i\sin15^\circ)$$
Now $\sin15^\circ=\sin(45-30)^\circ$ or $=\sin(60-45)^\circ$
Alternatively,
if equating real & imaginary parts $r\cos\theta=2+\sqrt3$
and $r\sin\theta=1$
Square & add
Now use this, to find $\theta$

A: Do you know that if $x + iy = r(\cos \theta + i \sin \theta)$ then $|x + iy| = \sqrt {x^2 + y^2} = r$?
So if $2 + \sqrt 3 + i =  r(\cos \theta + i \sin \theta)$ then $r = \sqrt{(2 + \sqrt 3)^2 + 1^2} = \sqrt{4 + 4\sqrt 3 + 3 + 1} =
\sqrt{8 + 4 \sqrt 3}= \sqrt{6 + 2\sqrt{2}\sqrt{6} +2}=\sqrt {(\sqrt{6} + \sqrt{2})^2} =\sqrt{6} + \sqrt{2}$
So now we need to solve $\cos \theta = \frac{2 + \sqrt 3}{\sqrt{6} + \sqrt{2}}=$
$\frac {(2+ \sqrt 3)(\sqrt{6} - \sqrt{2})}{(\sqrt{6} + \sqrt{2})(\sqrt{6} - \sqrt{2})}= \frac {2\sqrt{6} + 3\sqrt{2}- 2\sqrt{2} - \sqrt{6}}4=\frac{\sqrt 6 + \sqrt 2}{4}$
And $\sin \theta = \frac 1{(\sqrt{6} + \sqrt{2})} = \frac {\sqrt{6} - \sqrt{2}}4$
$\sin 2\theta = 2\sin \theta \cos \theta = $
$2* \frac {6-2}{16} = \frac 12$ so $2\theta = \frac {\pi}6| \frac {5\pi}6$
$\cos 2\theta = \cos^2 \theta - \sin^2 \theta $
$= \frac {8 + 2\sqrt{12}}{16}- \frac {8 - 2\sqrt{12}}{16}=\frac {\sqrt 3}{2}$
So $2\theta = \pm \frac {\pi}6$.
So $2\theta = \frac {\pi}6$ and $\theta = \frac {\pi}{12}$.


text:
Q: Android game dev: switching between views I am working on creating a simple game using Android and I have this question on best practices for how to transition between a couple of the game screens.
The game screens are very simple in my game (like MainGameScreen, PauseScreen, SettingsScreen, etc.) with just a couple of buttons and some text. So I am thinking to put everything in one activity, create a separate view for each of the screens and then have something to transition between these views.
I was thinking of using ViewAnimator to switch between the screens (see here android game pause screen , dialog or activity dialog?), but I have the problem of ViewAnimator only lets me switch based on an index (ie. I can't switch to my desired view using a layout id). So I think maybe ViewAnimator is not the best class for the job.
Is there another class that is more suitable for switching between views of my choice?
Thankyou everybody for help.

A: I think what are you looking for is a ViewPager , you can also store the id of the pages and then navigate through them


text:
Q: Interaction effect of 2x2 ANOVA in meta-analysis I want to meta-analyze the interaction effect of a 2x2 ANOVA.
(I am not talking about an interaction in the meta-regression, as in this question but about an interaction as the focal effect that should be meta-analytically summarized).
What is the best way to code the interaction effect size for a subsequent meta-analysis?
(preferably in the metafor package)

A: In a 2x2 ANOVA with factors A and B you can easily turn it into one number. Calculate the effect for A, the effect for B, and subtract them. And, of course, you need the error term for the interaction. This may not be included but can be derived in the case of a reported F and means. Going through ANOVA hand calculations you can derive the numerator to the F from means and N and therefore the MSE can also be derived.


text:
Q: How to pop / clean Lua call stack from C I want to pop / clean the Lua call stack while within a C function called from Lua. Is this possible?
Background:
I want my C library and its extension scripts to use the same test framework. (I am aware various unit testing tools exist for Lua. I don't care; I want one report) I'm wrapping CUnit in a thin layer of Lua. CUnit provides a choice of fatal and non-fatal test assertions. Fatal assertions cause an immediate longjmp out of the test and back into the framework runner. This seems like it would do bad things to the Lua VM if I did not clean the stack first.
The stack will probably look something like:
#0. C:   assert_wrapper_fcn(test, fatal)
#1. Lua: assert_fcn(bool)
#2. Lua: test_fcn()
#3. C:   runner(&test_fcn)

I want to clean up everything between #0 and #3. I know the method signatures of test_fcn() and assert_fcn(bool), but that's it.

A: To empty the stack is really easy. Just use lua_settop with 0 as argument.
lua_settop(L, 0);

A: Not sure I'm understanding the question quite right... but to clear out Lua's stack:
int stackSize = lua_gettop(L);
lua_pop(L, stackSize);

A: My suggestion is to use Lua's own assert system, and then trap that in your runner and then forward the error to your unit testing framework:
Launch your Lua code with lua_pcall.
From within your Lua code, trigger fatal errors with the standard assert command.
From where you launched your Lua code, check the result of lua_pcall and when you get != 0, trigger your CUnit fatal assertion failure.
This will avoid mixing any longjmp's between Lua and CUnit.


text: Q: Possible error with asset initialization in AFrame1.0.4 that leavs me on an infinite loading screen Making a WebVR site, sadly whenever I try and preview the following code however I'm left on an infinite screen of the AFrame loading scene -- three white dots, a light blue background, and a dark blue bar overhead. At first I tried switching the "tree-05.obj" asset to a lower-poly one, as my initial suspicion was that the model I was using was a little too complicated to load properly in AFrame as I'm not familiar with it's abilities well yet. Sadly I still get the same error, and the code below is the only code in my site other than the AFrame 1.0.4 source script and the basic html tags.


text:
Q: Why is RestClient throwing null pointer exception when trying to post a JSON data to a restful web service? I am trying to use the RESTClient class to do a post to a RESTful web service. I am getting an NPE at setBody in groovyx.net.http.HTTPBuilder$RequestConfigDelegate.
My code is
postParam = [
  sourceAccountNo         : fundTransfer.fromAccount.accountNumber,
  sourceBankCode          : fundTransfer.fromAccount.bank.bankCode,
  destinationBankCode     : fundTransfer.toAccount.bank.bankCode,
  destinationBankAccountNo: fundTransfer.toAccount.accountNumber,
  amount                  : fundTransfer.amount,
  narrationOne            : fundTransfer.note,
  uniqueId                : fundTransfer.uniqueId
]

String balanceTransferURL = ApplicationProperty.propertiesMap.get(ApplicationProperty.PropertyKey.BULK_BALANCE_TRANSFER_URL)
def restClient = new RESTClient(balanceTransferURL)
def restResponse = restClient.post(requestContentType:JSON,body:postParam)

My error log is as follows
message: null
    Line | Method
->> 1200 | setBody                     in groovyx.net.http.HTTPBuilder$RequestConfigDelegate
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|   1111 | setPropertiesFromMap        in     ''
|    946 | <init> . . . . . . . . . .  in     ''
|    140 | post                        in groovyx.net.http.RESTClient

What is exactly missing? What am I doing wrong?

A: I ran into this same issue and figured out that it goes away when you add the requestContentType parameter:
import static groovyx.net.http.ContentType.JSON

requestContentType:JSON


text:
Q: Dual monitor setup issue, 2nd monitor constantly goes black 1-2 seconds ever so often when I use an application that uses a microphone (ex. Discord) I currently use an Asus TUF FX504GE and want to have a double monitor setup using this new monitor I bought (Viewsonic VA2432) however, my monitor constantly goes black for 1-2 seconds whenever I use an application that uses a microphone like discord or whenever I'm on a zoom meeting for my online classes. I've exhausted all possible solutions I could find on the internet so any help would be much appreciated. When I'm not using any app that uses a microphone, the 2nd monitor seems to never give a black screen so I suspect there's something wrong with my microphone drivers. I tried updating it on the device manager, uninstalling it, and even installing the new drivers provided by realtek.

A: You can have problem with Driver or Power.
Try to use SoundCard on USB.


text:
Q: Leaflet: get layer in GeoJSON with pixel coordinates instead of lat long coordinates In my Angular 7 project with ngx-leaflet and leaflet 1.4.0 and leaflet-draw 0.4.14 I want to export each drawn rectangle (and circle,...) to GeoJSON.
That works fine using
 public onDrawCreated(e: any) {
    const layerType = e.layerType;
    const layer = e.layer;
    const gj = layer.toGeoJSON();
// .... save gj
}

Now I also want to have the GeoJSON with pixel coordinates instead of the latlng coordinates as they come from the layer.
So I suppose I need to execute a project on all coordinates using
this.map.project(ltlng, this.map.getMaxZoom()).round();

However: this.map.project returns a point object not a latlng object.
I tried to apply this conversion on the _latlngs property of the layer object, but obviously it does not work.
Should I do the conversion on the GeoJSON object?
Any tips on how I can make this conversion work?

A: If you really want geojson with pixel coordinates at max zoom level, see code below. Since I'm not familiar with Angular, syntax is plain Java Script:
map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;
    var geojson = layer.toGeoJSON();
    geojson.geometry.coordinates.forEach( function(point, index, arr)  {
      arr[index] = map.project(point, map.getMaxZoom());
    });
    // save pixel gj
});


text:
Q: Illegal instruction (core dumped) error: scanf in a while loop until EOF So I wrote a function in C which gets input until EOF
while (scanf(" %c", &input) != EOF) {
     // do stuff
}

I tried to use the following test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
10 20 30 40 50 _66_ 15 66bb

As an input to the program. It actually runs the program but at the end it finishes with the following error: Illegal instruction (core dumped).
Other tests work fine, and after a quick check I found out that the problem begins after the last 50 (if I use only the numbers until 50 - it works fine). How to solve this problem?


text:
Q: How to remove extra space in bottom of x axis label ie below zero mpandroidchart Hi I used MpAndroidChart library.  I mentioned label at bottom of the chart but it takes extra space to assign for label ie below 0 value. How to reduce or remove space at bottom of zero?
You can see screenshot below where there is a huge space between 0 and the label. How to remove that spacing?

  barChart = (BarChart) findViewById(R.id.chart);
    XAxis xAxis = barChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.setDrawAxisLine(true);
    leftAxis.setDrawGridLines(true);
    YAxis rightAxis = barChart.getAxisRight();
    rightAxis.setDrawAxisLine(true);
    rightAxis.setDrawGridLines(true);

A: Try to add:
leftAxis.setAxisMinValue(0f);
rightAxis.setAxisMinValue(0f);

Hope, this answer will solve your problem.
Edit 1:
For newer version, method has been changed to:
leftAxis.setAxisMinimum(0f);
rightAxis.setAxisMinimum(0f);

A: In version 3.0.2 method setAxisMinValue marked as @deprecated.
New method is xAxis.setAxisMinimum(0f);


text:
Q: regular expression for pair of letters in the same word I need to find all the words which has the same occurrence of pair of letters at least twice (word is all non white space characters between spaces, ie chochol , 9933499 ). I came up with this regex however its not working and i cant figure out how to write it properly.
[ ]\S*(\S\S)\S*\1\S*[ ]

A: The [ ] in your pattern are redundant and even harmful since they prevent from matching overlapping (subsequent, after 1 space) substrings.
You need to use
grep -oP '\S*(\S\S)\S*\1\S*'

See the online demo
If you only need to match "words" with two repeated identical consecutive letters, replace (\S\S) with ([A-Za-z]{2}) or even \p{L}{2}.


text:
Q: Starling Feathers tilerow clickable I am making a data view based off tileRow layout and I will have 3-5 columns
col1     col2     col3     col4
---------------------------------------
row1-1   row1-2   row1-3   row1-4
row2-1   row2-2   row2-3   row2-4

etc
At the moment I have set it up to use a for loop to create the items and set the width of each item 1/4 the total size of the container and this works great filling up an entire row with 4 quads so really the layout is like:
col1    col2    col3    col4
---------------------------------------
tile1   tile2   tile3   tile4
tile5   tile6   tile7   tile8

I want to add an event listener to trigger a function when a row is clicked. I am assuming I wont be able to really do this because each row is made up of 4 separate tiles.
Is there a better way to achieve the desired effect or should I just add a fifth column with a button that is clickable?
I can't really use the list as I need multiple columns.

A: I would create a new Sprite which represents a row.
Take the rowSprite from a pool, and add the items for each row into it.  Then you can put a click handler on the row, and grab the children of the currentTarget of the event.


text:
Q: Calculating Quartiles Dilemma When I am calculating the lower quartile and upper quartile, why am I taking (n+1)/4 and 3(n+1)/4, instead of n/4 and 3n/4?
According to me, if total number of observations are n, then that should be counted figuring out the quartiles, isn't it?

A: You need to look at the definition of quartile you are using.  For large $n$ it will not matter much, but it appears the definition you are using is the datum that exceeds $25\%$ or $75\%$ of the data.  The $+1$ is there for the "exceed".  Wikipedia gives three different definitions of quartile, with a data set that shows the differences.

A: Without a formula, you can always finding the first and third quartiles using two easy steps.
First, find the median of the entire set. Then divide the set into two subsets: elements that are lesser than the median, and elements that are greater than the median. (Note: if the median is repeated in the set, include the duplicates in these subsets.)
Now find the medians of these two subsets. Those are the first and third quartile values.
Example 1, odd number of elements:
$\{1,3,4,4,5,7,8\}$
The median is 4 (the second one), so the lower subset is $\{1,3,4\}$ and the upper subset is $\{5,7,8\}$.
The medians of those 2 subsets are 3 and 7. So the first quartile value is 3 and the third quartile value is 7.
Example 2, even number of elements:
$\{2,4,6,8,10,12\}$
The median is 7, so the lower subset is $\{2,4,6\}$ and the upper subset is $\{8,10,12\}$. So the first and third quartiles are 4 and 10, respectively.


text:
Q: Fetch returns null when fetch API - I have a function that fetches data from the URL , on console log value is coming but on I try to pass value to HTML code come null
What is the problem here? Why does it work that way?
(() => {
  let binData = null;

  fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then((res) => res.json())
    .then((data) => {
      binData = data;
      console.log("binData :", binData);
    })
    .then((out) => console.log(binData.userId));
  document.getElementById("add_after_me").innerHTML = binData.userId;
})();

GeeksforGeeks

      This is the text which has already been typed into the div


text:
Q: js code works for one variable(?), how to make it work for many? I have working code of js, it shows different div for selected option.

<select id="thechoices">
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

Box 1 stuff...

Box 2 stuff...

Box 3 stuff...

Please, I have no js experience, so I don't know how to make it work several times on one page for many "thechoices". Something like copy paste but more suitable than this:

<select id="thechoices">
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

Box 1 stuff...

Box 2 stuff...

Box 3 stuff...

<select id="thechoices2">
<option value="box4">1</option>
<option value="box5">2</option>
<option value="box6">3</option>
</select>

1 stuff...

2 stuff...

3 stuff...

I know you can help me, it seems to be simple but I can't handle with this.
How can I change my second code to work in the same way but not only for two selectors. I need it for many. Don't want to copy paste the same section like in my second code.

A: Avoid repeating IDs and provide a means for each select menu to address its corresponding boxes.
In the HTML:

*

*change id="thechoices" to class="thechoices"

*change id="boxn" to class="boxn" all through

*wrap each select and its corresponding boxes in
...

Now use the following jQuery:
$(document).ready(function(){
    $(".thechoices").change(function(){
        $this = $(this);
        $this.closest(".boxWrapper").find("." + $this.val()).show().siblings().hide();
    }).change();
});

Be sure to use $this.val() and not this.value for cross browser reliability.

A: This will run on any select tag:
$("select").change(function(){
    $("#" + this.value).show().siblings().hide();
});

A: I modified your code a little bit. Check this one:

<select class="thechoices" id="thechoices_1">
<option value="1">Box 1</option>
<option value="2">Box 2</option>
<option value="3">Box 3</option>
</select>

Box 1 stuff...

Box 2 stuff...

Box 3 stuff...

<select class="thechoices" id="thechoices_2">
<option value="1">Box 1</option>
<option value="2">Box 2</option>
<option value="3">Box 3</option>
</select>

Box 1 stuff...

Box 2 stuff...

Box 3 stuff...


text:
Q: mouseover on dynamic table I have been trying to make a scoreboard where when you mouseover one of the games it gives you pitching information for that game but cant seem to make the mouseover work.
Here is my scoreboard code:

The game information is in XML form from http://gd2.mlb.com/components/game/mlb/year_2015/month_06/day_08/miniscoreboard.xml
and im looking for the information from home_probable_pitcher and home_probable_pitcher