text:
Q: Accessing multiple Gmail accounts via one .NET5 microservice (application) I've read some related questions, but they are not 100% related, as the requirements vary a bit.
I have a .NET5 web application, some kind of custom CRM for the company I work in.
We have multiple users (employees, my colleagues), which can create quotations, etc.
Also, they can send these quotations to customers. Every user has its email account name attached to it.
The current way this application works is that I've created and enabled Gmail API for each email account, and authorized it, by myself, manually.
The problem is that every time we need to add a new user (new employee for instance) - I need to enable Gmail API of his email account (company's one, but it doesn't matter), add the credential file and token manually to the server, authenticate it, and only then - the application can use the email.
I know that there are many sites (like Monday, etc) - that have automations and integrations with Gmail, and any time I want some integration - I get notified with the OAuth screen, and approve it. I want the same thing in my application.
I understand that I have to create some kind on "Gmail global credential", which will be "added" with account tokens or something like that (every app user will oauth and allow access)?
Just can't find the correct documentation for it.
My backend is written in Blazor Server, .NET5.
I would appreciate if one could explain the main stages of this procedure.
Thanks!


text:
Q: A question about $S^{-1}R\otimes_R M\cong S^{-1}M$ as $S^{-1}R$-modules I have found this online notes from Columbia University. However, I have a question (maybe very silly) about the proof.
It says that by the universal property, the map $f'$ induces a unique $S^{-1}R$-module homomorphism. But should it be an $R$-module homomorphism?
I think maybe I messed up with the universal property. I always assume that if we have an $R$-bilinear map from $M\times N$ to $L$, then it induces an $R$-module homomorphism from $M\otimes_RN$ to $L$. How could we induce a $S^{-1}R$ homomorphism if we have $\otimes_R$ instead of $\otimes_{S^{-1}R}$?

PS It says that the map $f'$ is bilinear. In the sense of $S^{-1}R$-bilinear or $R$-bilinear? I suppose it should be the latter, is it?
Thank you very much in advance!

A: You are 100% right that the map induced by the universal property is, a priori, just an $R$-linear map.
However, the following lemma shows it doesn't matter:
Lemma. Let $f: M \to N$ be an $R$-module map, where $M$ and $N$ are $S^{-1}R$-modules. Then in fact $f$ is $S^{-1}R$-linear.
This is because $s f(\frac{r}{s} m) = rf(m) $ in $N$, so, multiplying both sides by $1/s$ gives that $f$ is $S^{-1}R$-linear.

redpajama_set_name: RedPajamaStackExchange


text:
Q: possible to config Git line-endings specific to repo? I am working on both Windows and Mac against a repo with origin on GitHub.
On GitHub, I want line-endings to be LF.
On Mac OS X, I want line-endings to be LF.
On Windows, I want line-endings to be CRLF -- except for a specific repo where I want LF.
Is this possible ?

A: I would suggest that on windows you run
git config --global core.autocrlf true

which will automatically translate to and from windows line endings
and then in specific repositories, which don't want conversion, you should run
git config core.autocrlf false

as you will notice git config has a --global property which modifies your ~/.gitconfig ( or C:\Users\.gitconfig ) file.   Without this flag these settings are added to your repository.
See the git reference manual for a further explanation


text:
Q: Create new variables based on another df I'm trying to up my R game, and I clearly need some guidance. I wanna create a lot of variables (93, to be exact), but I wanna do that the smart way. But I'm stuck.
My problem: a dataframe (df) containing some variables, including the "main" one, which contains the stems of my description variable. Another dataframe (reference), more of a reference table, containing two columns - the category and the regex necessary to identify it; I kept only 3 entries, but its 93 originally.
The code:
library(tidyverse)

df <- tibble("FlawType" = c(rep("Medium", 5), rep("Major", 5)),
         "Description" = c("utilizaca indev equip final divers daquel justific aquisica",
                           "utilizaca modal indev licitac aquisica mater previst plan trabalh conveni nomd",
                           "aquisica indev lanch gener alimentici secret municip educaca mont r",
                           "uso indev recurs bloc atenca basic aquisica medic realizaca trat intim prefeit decisa judic",
                           "indici irregular favorec process licitato no aquisica medic farmac basic raza concentraca indevid empr certam",
                           "localizaca bem vist realiz equip fiscalizaca cgu escol municip abril municipi palestin par",
                           "telecentr inat ausenc equip local instalaca equip defeit",
                           "equip local",
                           "equip mater permanent adquir implantaca banc aliment send utiliz outr local simples encontr in loc realiz equip",
                           "mater equip gener alimentici adquir recurs cra por entreg local atend"))

reference <- tibble(var = c("Aquisição indevida", "Equipamentos não localizados", "Despesa irregular"),
                    regex = c("(aquisica.*indev|indev.*aquisica)", "(equip.*local|local.*equip)", "(desp.*irregul|irregul.*desp)"))

I kinda can create three new variables in my sample df, but it turns out to be a list, and I have to extract it. I thought it wouldn't be a problem, but when I try to run it my original df (60k+ lines), it gets stuck...
The idea is: use the reference$var as the name of each new variable, using the associated regex (reference$regex) to create a dummy for every entry in the reference.
Code that works in the sample but not in the original df, just for reference:
varnames <- unique(reference$var)

for(varname in varnames){

  fd[[varname]] <- df %>%
    mutate(!!paste0(varname) := ifelse(str_detect(df$Description, reference$regex), 1, 0))

}

df <- bind_cols(df, map_df(fd,3))

Thanks in advance.

A: There's probably a more elegant way to do this (I'm not a huge fan of having to use bind_cols at the end to bring back the original variables), but this should work:
add_vars <- function(df, x, y) {
  x <- quo_name(x)
  transmute(df, !! x := ifelse(str_detect(Description, y), 1, 0))
}

bind_cols(df, map2_dfc(reference$var, reference$regex, ~ add_vars(df, .x, .y)))

# A tibble: 10 x 5
   FlawType Description                                                 `Aquisição indevi~ `Equipamentos não loc~ `Despesa irregul~
   <chr>    <chr>                                                                    <dbl>                  <dbl>             <dbl>
 1 Medium   utilizaca indev equip final divers daquel justific aquisica                  1                      0                 0
 2 Medium   utilizaca modal indev licitac aquisica mater previst plan ~                  1                      0                 0
 3 Medium   aquisica indev lanch gener alimentici secret municip educa~                  1                      0                 0
 4 Medium   uso indev recurs bloc atenca basic aquisica medic realizac~                  1                      0                 0
 5 Medium   indici irregular favorec process licitato no aquisica medi~                  1                      0                 0
 6 Major    localizaca bem vist realiz equip fiscalizaca cgu escol mun~                  0                      1                 0
 7 Major    telecentr inat ausenc equip local instalaca equip defeit                     0                      1                 0
 8 Major    equip local                                                                  0                      1                 0
 9 Major    equip mater permanent adquir implantaca banc aliment send ~                  0                      1                 0
10 Major    mater equip gener alimentici adquir recurs cra por entreg ~                  0                      1                 0


text:
Q: Algorithm complexity of create array with size N with unique elements from N arrays There are 2-dimentional array A[n][m] where n = 2*m.
Each array A[i] contains m unique integers in [0;n). Note, that elements in A[i] and A[j] can intersect if i != j. Each array A[i] is sorted.
Task: construct array B[n] that contains unique elements by taking only one element from each array of A. Or there is not solution if B[n] can't construct.
Example:
A[0] = {0, 2}
A[1] = {1, 2}
A[2] = {0, 3}
A[3] = {0, 3}

Result:
Take A[0][1], A[1][0], A[2][0], A[3][1] => B = {2, 1, 0, 3}

I have a recursive algorithm that solves the task:
// level = 0 at first call
fn recursive_choice(a: &mut Vec<Vec<usize>>, b: &mut Vec<usize>, level: usize) {
    if level >= a.len() {
        return;
    }

    for idx in 0..a[level].len() {
        if !b.contains(&a[level][idx]) {
            b.push(a[level][idx]);
            recursive_choice(a, b, level + 1);

            if a.len() == b.len() {
                return;
            } else {
                b.pop();
            }
        }
    }
}

Is there a better algorithm - and what is it? What is the complexity of this algorithm in the worst case?

A: This can be viewed as the problem of finding a maximum matching between arrays and values.  If the matching includes all arrays, then you have your answer.  If it does not, then the answer is no.
Which can be solved by standard approaches such as the Blossom Algorithm in time O(n^4).  If you're willing to use a more complex and optimized algorithm, you can reduce that to O(n^3).


text:
Q: Replaced matched text in Vim with pattern Here's a minimal example of what I'm trying to do.  Start with:
"this")
"that")
[hundreds of lines like this]
End with:
"this",&this)
"that",&that)
[hundreds of lines like this]
I have gotten this far:
g/"\p*"/s/)/[what to put here?]

So it correctly identifies the string that I want to copy.  What I'm not sure is how to tell it that I want it to paste that string at the end.  I've tried using &, but that matches the ), not the "\p*".

A: could you just use a search and replace on every line?
:% s/"\([a-z]*\)"/"\1"\,\&\1/g


text:
Q: Generate identically distributed dependent normal random numbers with prespecified sum How do I generate $n$ identically distributed but not independent normal random numbers such that their sum falls within a prespecified interval $[a,b]$ with probability $p$?
(This question is motivated by generating a random walk that ends up at a prespecified point: Random process not so random after all (deterministic). Since a continuous random variable has zero probability of reaching an exact number, we do the second best thing and ask for an entire interval to end up in.)

EDIT: Generating samples from singular Gaussian distribution has been proposed as a duplicate, which in turn is closed as a duplicate of Generate normally distributed random numbers with non positive-definite covariance matrix. I agree that both of these are helpful. However, the point of the current question (more specifically, of the answer) is to first figure out that we can use a multivariate normal distribution to address the question, and second, what kind of covariance matrix works. How to sample from a distribution with that covariance is a third step, where the linked threads are helpful.

A: We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$.
As a common mean, we choose
$$ \mu_1 = \dots = \mu_n = \frac{a+b}{2n}. $$
In order that $Z\in[a,b]$ with probability $p$, its standard deviation should fulfill
$$ \sigma_Z = \frac{b-a}{q_\alpha}, $$
where $q_\alpha$ is the standard normal quantile to the level $\alpha$, here $\alpha=1-\frac{1-p}{2}$.
We now need to specify $\Sigma$. We have a lot of leeway here. Let us assume that we want each $X_i$'s variance to be $\sigma^2$ and the covariance be $\text{cov}(X_i,X_j)=\tau$ for $i\neq j$. The key to creating a "good" $\Sigma$ is this previous answer by probabilityislogic. It yields that the sum of our $X_i$s has variance
$$ n\sigma^2 + n(n-1)\tau $$
so we need that
$$ n\sigma^2 + n(n-1)\tau = \frac{b-a}{q_\alpha}.$$
We also need to ensure that $\Sigma$ is positive definite, but this is not overly hard. The easiest way to do this is to ensure that all entries in $\Sigma$ are positive, e.g., by setting
$$ \sigma^2 := \frac{\sigma_Z^2}{2n}, \quad \tau := \frac{\sigma_Z^2}{2n(n-1)}, $$
but this gives very small values and very boring cumulative sums and trajectories:

Less boring is to set
$$ \sigma^2 := 1, \quad \tau := \frac{1}{n-1}\big(\frac{\sigma_Z^2}{n}-\sigma^2\big), $$
which yields much more interesting trajectories:

Note that setting this does indeed yield a valid covariance matrix, because $\Sigma$ is then of the form $\Sigma_{ij} = m(i-j)$, namely
$$ m(0) = \sigma^2, \quad m(j) = \tau\text{ for }j>0, $$
and we have that
$$ \sum_{j>0} |m(j)| = (n-1)|\tau| = \big|\frac{\sigma_Z^2}{n}-\sigma^2\big| = \big|\frac{\sigma_Z^2}{n}-1\big| < 1 = \sigma^2 = m(0), $$
which is a sufficient condition for $\Sigma$ to be strictly positive definite by Wikipedia (Point 7 under "Further Properties").
R code below, but first, please go and upvote probabilityislogic's answer.
n_steps <- 1000
target_min <- 1.99
target_max <- 2.01
target_prob <- 0.99

target_mean <- mean(c(target_min,target_max))
target_sd <- (target_max-target_mean)/qnorm(p=1-(1-target_prob)/2)

mm <- rep(target_mean/n_steps,n_steps)

# boring setting:
# sigma_sq <- target_sd^2/(2*n_steps)
# tau <- target_sd^2/(2*n_steps*(n_steps-1))

sigma_sq <- 1
tau <- (target_sd^2/n_steps-sigma_sq)/(n_steps-1)

CC <- matrix(tau,nrow=n_steps,ncol=n_steps)
diag(CC) <- sigma_sq

library(MASS)
foo <- mvrnorm(1,mu=mm,Sigma=CC)
sum(foo)

plot(cumsum(foo),type="l",xlab="",ylab="")
abline(h=target_mean,lty=2)


text:
Q: How To Scale Font With Device Size Using flutter_screenutil I am unable to make the font scale to a larger size on bigger screens. The font size remains the same regardless of device size. How do I achieve this?
Here is my MaterialApp code;
ScreenUtilInit(
          designSize: Size(412, 869),
          builder: () => MaterialApp(
            debugShowCheckedModeBanner: false,
            title: 'Progressive Institute Events',
            theme: ThemeData(
              primarySwatch: Colors.blue,
              textTheme: TextTheme(
                bodyText1: TextStyle(fontSize: 16.sp),
                bodyText2: TextStyle(fontSize: 16.sp),
              ),
            ),
            home: _runIntroSlider
                ? IntroScreen(
                    disableIntroScreen: _disableIntroScreen,
                  )
                : auth.isAuth
                    ? HomeScreen()
                    : FutureBuilder(
                        future: auth.tryAutoLogin(),
                        builder: (ctx, authResultSnapshot) =>
                            authResultSnapshot.connectionState ==
                                    ConnectionState.waiting
                                ? Center(child: CircularProgressIndicator())
                                : AuthScreen(),
                      ),
            routes: {
              TabsScreen.routeName: (ctx) => TabsScreen(),
              SponsorDetailsScreen.routeName: (ctx) => SponsorDetailsScreen(),
              QuestionScreen.routeName: (ctx) => QuestionScreen(),
              SendPushNotificationScreen.routeName: (ctx) =>
                  SendPushNotificationScreen(),
              AboutAppScreen.routeName: (ctx) => AboutAppScreen(),
            },
          ),
        ),

A: This is how you can create your own size manager.
Create SizeManager class as below. (size_manager.dart)
class SizeManager {
  static Orientation _orientation;
  static DeviceType _deviceType;
  static double _width;
  static double _height;

  void init(Size size, Orientation orientation) {
    _orientation = orientation;
    if (orientation == Orientation.portrait) {
      _width = size.width;
      _height = size.height;
    } else {
      _width = size.height;
      _height = size.width;
    }

    //for mobile and tablet screen
    if (0 < _width && _width <= 310) {
      _deviceType = DeviceType.SMobile;
    } else if (310 < _width && _width <=600) {
      _deviceType = DeviceType.Mobile;
    } else {
      _deviceType = DeviceType.Tablet;
    }
  }

  static fs(var i) {
    return _width / 100 * (i / 3);
  }

  static get orientation => _orientation;

  static get deviceType => _deviceType;
}

enum DeviceType {
  SMobile,
  Mobile,
  Tablet,
}

double getSize({double tabVal, double mobVal, double sMobVal}) {
  switch (SizeManager.deviceType) {
    case DeviceType.Tablet:
      return tabVal;
      break;

    case DeviceType.Mobile:
      return mobVal;
      break;

    case DeviceType.SMobile:
      return sMobVal;
      break;

    default:
      return mobVal;
  }
}

Then Create an extension. (size_manager_extensions.dart)
extension SizeManagerExtensions on double {
  double get fs => SizeManager.fs(this);
}

Finally, you have to initialize SizeManager with the help of an OrientationBuilder
return Scaffold(
        body: OrientationBuilder(builder: (context, orientation) {
          SizeManager().init(MediaQuery.of(context).size, orientation);
          return Text(
            'How to scale font size',
            style: TextStyle(
                //fontSize: 12.0.fs - this also works but you can controll it base on device size as below
                fontSize:getSize(tabVal: 8.0.fs, mobVal: 12.0.fs, sMobVal: 16.0.fs),
                color: Color(0xFF67AD5B),
                fontWeight: FontWeight.w600),
          );
        }));

A: It turns out the size of font is mainly calculated based on the minimum of width and length and if there is a slight change in width and alarger change in height the font resizing may be small.
I also noticed that setting a smaller design size worked better. See this GitHUb thread.


text:
Q: Does ping omit iptables / postrouting rules I have a server with a proxmox installation and only 1 outbound connection (eth0).
To make the machines network between each other I created a network bridge (vmbr0) in the interfaces configuration and configured it accordingly to the Proxmox Network Model (Subpoint NAT).
The bridge has the IP 10.1.1.1 and acts in my understanding as a getway between the local network and the wide world.
To achieve this, following iptable policies are implemented on the server:
Chain FORWARD (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  10.1.1.0/24          anywhere
ACCEPT     all  --  anywhere             10.1.1.0/24

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
SNAT       all  --  10.1.1.0/24          anywhere             to:x.x.x.x

When I ping the Google DNS server from one of the vms installed on the server and connected via the bridge using: ping 8.8.8.8, the vm is able to get a ping result from the Google DNS server so the NAT seems to be working.
(The nat is again for the whole Subnet (10.1.1.0/24) )
If I do: ping -I vmbr0 8.8.8.8 on the host machine however, the ping command fails. This ping commands uses the bridge interface to ping the Google DNS server and my expectation was, that the POSTROUTING policies would make it able to communicate with the Google DNS server too.
So in short, when other clients using the bridge as gateway they can connect to the internet, but if the interface itself is selected as outgoing interface it can't find a route.
So this leads me to my question, is explicitly using an interface somehow skipping postrouting rules and is really taken as the absolute endpoint for routing on the concerning machine? - in a sense: vmbr0 stays vmbr0 and never will be masqueraded to eth0 if you choose to ping over it -

A: man ping, bolds mine:

-I interface
      interface is either an address, or an interface name. If interface is an address, it sets source address to specified interface address.
  If interface in an interface name, it sets source interface to specified interface.

The issue is with forcing the interface with ping -I vmbr0 instead of letting the system choose in the end the right interface with ping -I 10.1.1.1.
Also, even if this doesn't make a difference with nat/POSTROUTING (see later), you should understand that you're not routing when running a command on the host, so some chains (eg: filter/FORWARD) might not apply (but nat/POSTROUTING still does, see later). Keep in mind that this might give different results when running commands on the host instead of a routed VM depending on your rules, even if that's not the case here with the right ping command.
this Packet Flow in Netfilter and General Networking schematic shows that after the different OUTPUT chains are traversed for a packet coming from a local process, nat/POSTROUTING still gets traversed after, so yes had your packet be going outside through eth0 it would still have been SNATed: that's by using ping -I 10.1.1.1 8.8.8.8
Instead when forcing the interface with ping -I vmbr0 8.8.8.8, if you run tcpdump on vmbr0 you'll likely see ARP requests from 10.1.1.1 to 8.8.8.8 which won't get answers.
And for the final question: yes forcing the route can't let the packet go to the right destination. You can't ever have vmbr0 be masqueraded, because SNAT/MASQUERADE is done on packets' IP, not on an interface, and its application depends on their route to the destination.


text:
Q: Crosswalks on ios - can not find the XWalkView module I am trying to use crosswalk to make my web app into iOS app
and I following the steps of Quickstart in this page https://github.com/crosswalk-project/crosswalk-ios
but I keep facing the problem:
in the ViewController.swift
When I import XWalkView, It always appears that It can't find the XWalkView module which makes me stop from my development...

Somebody help me.

Here's the code of ViewController.swift:
import UIKit
import WebKit
import XWalkView

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        var start_url = "index.html"
        var xwalk_extensions = ["Extension.load"]
        if let plistPath = NSBundle.mainBundle().pathForResource("manifest", ofType: "plist") {
            if let manifest = NSDictionary(contentsOfFile: plistPath) {
                start_url = manifest["start_url"] as? String ?? start_url
                xwalk_extensions = manifest["xwalk_extensions"] as? [String] ?? xwalk_extensions
            }
        }

        let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
        webview.scrollView.bounces = false
        view.addSubview(webview)

        for name in xwalk_extensions {
            if let ext: AnyObject = XWalkExtensionFactory.createExtension(name) {
                webview.loadExtension(ext, namespace: name)
            }
        }

        if let root = NSBundle.mainBundle().resourceURL?.URLByAppendingPathComponent("www") {
            var error: NSError?
            let url = root.URLByAppendingPathComponent(start_url)
            if url.checkResourceIsReachableAndReturnError(&error) {
                webview.loadFileURL(url, allowingReadAccessToURL: root)
            } else {
                webview.loadHTMLString(error!.description, baseURL: nil)
            }
        }
    }

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

A: perhaps you forget to link the XWalkView.framework in your app target?
Try this step:
Open Xcode, select your app project, in 'General' -> 'Linked Frameworks and Libraries', select '+', choose 'XWalkView.framework' to add it into the linking frameworks. Then shot another build. It's ok if the XWalkView.framework turns red.


text:
Q: Mysql Query "OR" and "AND" $assault_checker=mysql_query("SELECT * FROM assaults WHERE host_id='".$_SESSION['user']."' OR guest_id='".$_SESSION['user']."' AND status='0'");
$assault_checker=mysql_num_rows($assault_checker);

I keep getting the wrong expected result.
I just want to count the number of rows where the user id is in host_id or guest_id. Also the status row should be 0.
What am I missing?

A: yes you should use brackets, your query should be:
$assault_checker=mysql_query("SELECT * FROM assaults WHERE (host_id='".$_SESSION['user']."' OR guest_id='".$_SESSION['user']."') AND status='0'");


text:
Q: vscode HTML script Code hints how to jump to lib.dom.d.ts? <!DOCTYPE html>
<html lang="en">

 <!-- ... -->

<body>
  <script>
      console.log('1');
</script>
</body>
</html>

When CTRL + left-click, he does not jump to lib.dom.d.ts

I want him to jump here. Same as a .js file

What plug-ins should I install or how to set them up?


text:
Q: Converting to text file from dataframe doesnt separate lines I use export from pandas data frame in Jupyter:
        df_merged.to_csv(text_file, index=True, mode='a', sep=' ')

In Jupyter all looks nice:

But when I download it I see that the lines are not separated:

Please, dont you know where the issue might be?
Thanks!
RESULT: this helped for Windows:
        df_merged.to_csv(text_file, index=False, mode='a', sep='\t', line_terminator='\r\n')

A: It looks like:

*

*you are on Windows

*you are viewing the file in Notepad

Pandas will write out the csv file with newline '\n' only as the line separator.  Notepad will only break a line if it has carriage returns '\r'.
I would recommend using a different text editor such as Notepad++


text:
Q: How to change aws dynamic default region - SAML federated users I am following this aws documentation to generate and use federated user login.
When i use Federation STS token to log into AWS console, it logs into Ohio(us-east-2) region by redirecting to https://console.aws.amazon.com/region/dynamic-default-region .
How to change region to N.Virginia(us-east-1) so that when i use the federation login it will automatically login into N.virginia region?
I have tried passing region=us-east-1 in the URL, however it did not work.
AWS has dynamic default region : If you signed up for an AWS account on or after May 17, 2017, the default region when you access a resource from the AWS Management Console is US East (Ohio) (us-east-2); for older accounts, the default region is either US West (Oregon) (us-west-2) or US East (N. Virginia) (us-east-1).

A: You need to use the Destination parameter (url-encoded). For example:
&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1


text:
Q: VisualStudio cannot run code on MonoGame I am having issues with running code that is written in VisualStudio 2015 in MonoGame 3.5.
My two versions are compatible, from all I can see. VisualStudio has no issues running Console application codes, and also connects to Unity just fine (I can write code in VisualStudio for Unity and it runs).
I can also open up MonoGame and convert png files into xnb's to use in VisualStudio. It is only when I try to actually run the VisualStudio code and Windows tries to open MonoGame, it fails.
To better show what is happening, I created an empty project specifically by clicking "MonoGame for Windows" in VisualStudio, and called it EmptyGame. By default, running this should yield a cornflower blue screen. Instead, it shows this error message:
error message Ctrl+F5 MonoGame
I then tried to debug the completely default code (it shouldn't have any bugs as it is the default provided by VisualStudio but I did it anyway) and got this:
debugging error message VisualStudio
I have tried googling this error message and not gotten very far. Somebody had a similar error message for Duality2D (https:// forum.adamslair. net/viewtopic.php?f=4&t=732) but the answers they gave don't apply here I don't think...
I have also tried uninstalling and reinstalling both programs, making sure that I ticked VisualStudio 2015 in the MonoGame installation, and turning off my anti-virus while trying to run (Ctrl+F5) - I was desperate at this point.
Anyone got any ideas? I can't possibly be the first person to have issues trying to get VisualStudio and MonoGame to communicate, but Google has gotten me nowhere. I just found this website which had a lot of great reviews so hopefully someone here has an answer for me!
Appreciate it!
-M.


text:
Q: "Unable to load DLL 'SQLite.Interop.dll' or one of its dependencies" running an application in Docker, but locally it works fine Introduction
There seems to be frequent issues with the SQLite.Interop.dll library. Just look at these other StackOverflow questions:

*

*Unable to load DLL 'SQLite.Interop.dll'

*Visual Studio C# - SQLite.Interop.dll not found

*"Unable to load DLL 'SQLite.Interop.dll' error on client machine
I've gone through all of the above and more:

*

*I installed the System.Data.SQLite.Core NuGet package,

*I specified these elements in the *.csproj,

*I set x64 instead of Any CPU,

*and so on

with no success. The key element is that the application runs just fine locally, but I need to make it run on Docker, and that's where the problems start. The situation is that I'm working on a .NET Core 3.1 console application with Visual Studio 2022. The application will be finally deployed on AKS (Azure Kubernetes Service). Of course, first I need to make it work on the local installation of Docker in my development machine. Building the console application project on Visual Studio gives me no error and it runs fine from Visual Studio. Building its Docker image with the appropriate Dockerfile also gives no problems, but running the same image on Docker raises the following exception: Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E). Currently, the project has the System.Data.SQLite.Core NuGet package installed and doesn't have these elements in the *.csproj. The exception is raised by a project referenced by the one of the console application; this project both has the System.Data.SQLite.Core and System.Data.SQLite NuGet packages installed. The console application's project has only the System.Data.SQLite.Core package installed (I already tried to install also the System.Data.SQLite, with no success). All the projects, now, has the System.Data.SQLite NuGet package installed (to give it a try), which causes the System.Data.SQLite.Core to be installed as a dependency.
What I tried
I used the Dockerfile pre-assembled by Visual Studio 2022, which deals with all the various referenced projects:
FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["ProjectA/ProjectA.csproj", "ProjectA/"]
COPY ["ProjectB/ProjectB.csproj", "ProjectB/"]
#COPY all the other referenced projects
RUN dotnet restore "ProjectA/ProjectA.csproj"
COPY . .
WORKDIR "/src/ProjectA"
RUN dotnet build "ProjectA.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "ProjectA.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ProjectA.dll"]

Since this Dockerfile is based on a multi-stage build, it has the following lines:
...
RUN dotnet build "MyProject.csproj" -c Release -o /app/build
...
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish
...

to first build the code, and then publish it. Given that dotnet publish, I decided to take a step back and be sure that, at least, I was able to publish the project myself, to narrow down the issue. I found that publishing it locally on a folder also gave me some problems, in particular the NU1605 error, which was preventing me to end the process successfully. I resolved the issue using what Microsoft suggests. Now, if I run the .exe located inside the publish destination folder, the application works as expected.
It was time to finally make it a Docker image. The image building process went well, but then the Unable... error appeared at runtime. Reading online, to solve the SQLite.Interop.dll issue, they suggest to move the SQLite.Interop.dll file directly in the bin folder; in fact, originally, I found it lived inside the bin\Release\netcoreapp3.1\runtimes\ folder, both in its win-x86 and win-x64 sub-directories. To "get rid" of this runtimes folder, I tried to publish the project locally on a folder, with the following settings:

This in fact made the SQLite.Interop.dll appear directly inside the bin folder and got rid of the runtimes folder. So, to obtain the same result with Docker, I modified the Dockerfile like this:
...
RUN dotnet build "MyProject.csproj" -c Release -o /app/build -r win-x64
...
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish -r win-x64
...

and now the SQLite.Interop.dll file appears directly also inside the bin folder in the Docker running container, so I thought everything was just fine at that time, but still I got the exception.
One last thing
I found that running the application locally (not in Docker) without specifying the destination runtime (so, keeping the build process as Any CPU instead of x64), raised no exceptions (that is, keeping the runtimes/ folder and the two SQLite.Interop.dll files inside of it, in the win-x86 and win-x64 sub-folders).

A: I ended up switching to Linux containers.

A: Solution
To run a dotnet application (e.g. dotnet test) inside a windows docker container with the System.Data.SQLite.Core nuget package you can use the following docker file
# escape=`
FROM mcr.microsoft.com/windows/servercore:ltsc2019

RUN setx /M PATH "%PATH%;C:\Program Files\dotnet;C:\nodejs"

# Install Microsoft Visual C++ Runtime Library
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';$ProgressPreference='silentlyContinue';"]

# Install .NET 6.0 for x86 (just change it to the platform you need)
RUN Invoke-WebRequest `
            -UseBasicParsing `
            -Uri https://dot.net/v1/dotnet-install.ps1 `
            -OutFile dotnet-install.ps1; `
        ./dotnet-install.ps1 `
            -InstallDir '/Program Files/dotnet' `
            -Channel 6.0 `
            -Architecture x86

Here is the releveant part of my csproj file:
   <ItemGroup>
      ...
      <PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" />
    </ItemGroup>

What worked for me
After switching to the script method, to install the .NET framework (and not using the binary) it worked for me.
Beforehand, like you, I tried a ton of different things!
What you can try
What might work is also to add the PrivateAssets="none" in the csproi. See this answer. After adding this to the csproj files I got a different error, because I must use a x86-dll in my project.
After installing .NET 6 x86 correctly, I reverted even this change in the csproj and it still worked!
What else
What I also tried, but was not necessary in the end, was Microsoft Visual C++ Runtime Library.
Quote from https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

All downloadable packages on this web page that do not include the word "static" in their file name require the appropriate version (e.g. 2005, 2008, 2010, 2012, 2013, 2015, 2017) of the Microsoft Visual C++ Runtime Library, to be successfully installed on the target machine, prior to making use of the executables contained therein.

...
# Install Microsoft Visual C++ Runtime Library
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';$ProgressPreference='silentlyContinue';"]
RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; `
    Invoke-WebRequest "https://aka.ms/vs/17/release/vc_redist.x64.exe" -OutFile "vc_redist.x64.exe"; `
    Start-Process -filepath C:\vc_redist.x64.exe -ArgumentList "/install", "/passive", "/norestart" -Passthru | Wait-Process; '
    Remove-Item -Force vc_redist.x64.exe;

More information on How-To install .NET in a docker container can be found at the dotnet-docker github repo
TL/DR
Use dotnet-install.ps1 in your dockerfile to install .NET and the SDK. Somehow, it does some magic, so that you can run dotnet apps which are using the SQLite.Interop.dll library (included via nuget)


text:
Q: How can I access a class from a external maven dependency in GWT? I am reading a project of gwt and maven. I have a maven project of server side implementation which contain all method of DML opretion. now this project is use in a maven-gwt project as a dependency. and in a RPC call of server side they directly creating the instance of side implementation to communicate with database. but as per the gwt conviction it should reside in server side. so how this is working
My server Implementation in maven
  ModuleImp
     src
       imp1.java
       imp2.java
       imp3.java

My GWT maven project
   GWTparent
       client
       shared
       server

please help....Thanks in advance.

A: GWT complier only cares about code in client and shared package(defined in *.gwt.xml under source tag). It ignores everything used and referred in server packages. In fact you can create a separate maven module for your server layer as well by adding appropriate dependencies to your GWT webapp


text:
Q: gzip in bash vs python In Bash, when you gzip a file, the original is not retained, whereas in Python, you could use the gzip library like this (as shown here in the "Examples of Usage" section):
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

By default, this retains the original file. I couldn't find a way to not retain it while gzipping. Do I have to wait till gzip is done to delete the file?

A: Considering that when GZip runs (in Bash, or anywhere else for that matter):

*

*GZip requires the original data to perform the zipping action

*GZip is designed to handle data of basically arbitrary size

*Therefore: GZip isn't likely to be creating a temp file in memory, rather it is almost certainly deleting the original after the gzip is done anyway.

With those points in mind, an identical strategy for your code is to do the gzip, then delete the file.
Certainly deleting the file isn't onerous — there are several ways to do it —  and of course you could package the whole thing in a procedure so as to never have to concern yourself with it again.

A: If you are on a unix-like system, you can unlink the file after opening so that it is no longer found in the file system. But it will still take disk space until you close the now-anonymous file.
import gzip
import shutil
import os
with open('deleteme', 'rb') as f_in:
    with gzip.open('deleteme.gz', 'wb') as f_out:
        os.unlink('deleteme') # *after* we knew the gzip open worked!
        shutil.copyfileobj(f_in, f_out)

As far as I know, this doesn't work on Windows. You need to do the remove after the zip process completes. You could change its name to something like "thefile.temporary" or even move it to a different directory (fast if the directory is the same file system, but copied if its a different one).

A: The code below (partially based on tdelaney's answer), will do the following:

*

*read the file, compressing on the fly, and storing all the compressed data in memory

*delete the input file

*then write the compressed data

This is for the use case where you have a full filesystem, which prevents you from writing the compressed data at the same time that the uncompressed file exists on disk.  To get around this problem, it is therefore necessary to store all the data in memory (unless you have access to external storage), but to minimise this memory cost as far as possible, only the compressed data is fully stored in memory, while the uncompressed data is read in chunks.
There is of course a risk of data loss if the program is interrupted between deleting the input file and completing writing the compressed data to disk.
There is also the possibility of failure if there is insufficient memory, but the input file would not be deleted in that case because the MemoryError would be raised before the os.unlink is reached.
It is worth noting that this does not specifically answer what the question asks for, namely deleting the input file while still reading from it.  This is possible under unix-like OSes, but there is no practical advantage in doing this over the regular command-line gzip behaviour, because freeing the disk space still does not happen until the file is closed, so it sacrifices recoverability in the event of failure, without gaining any additional space to juggle data in exchange for that sacrifice.  (There would still need to be disk space for the uncompressed and compressed data to coexist.)
import gzip
import shutil
import os
from io import BytesIO

filename = 'deleteme'

buf = BytesIO()

# compress into memory - don't store all the uncompressed data in memory
# but do store all the compressed data in memory
with open(filename, 'rb') as fin:
    with gzip.open(buf, 'wb') as zbuf:
        shutil.copyfileobj(fin, zbuf)

# sanity check for already compressed data
length = buf.tell()
if length > os.path.getsize(filename):
    raise RuntimeError("data *grew* in size - refusing to delete input")

# delete input file and then write out the compressed data
buf.seek(0)
os.unlink(filename)
with open(filename + '.gz', 'wb') as fout:
    shutil.copyfileobj(buf, fout)


text:
Q: Install MFP 7.1 CLI I'm trying to install MFP 7.1 CLI using the following URL:
https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/advanced-client-side-development/using-cli-to-create-build-and-manage-mobilefirst-project-artifacts/
All my platform is set for npm, but when I run npm install -g mfpdev-cli,
mfp 8.0 is getting installed instead.
$ mfpdev -v

8.0.0-201603280000

How can I get the MFP 7.1 CLI package?

A: By not installing the CLI for v8.0... although they can co-exist.
You can download the CLI for v7.1 from here: http://public.dhe.ibm.com/ibmdl/export/pub/software/products/en/MobileFirstPlatform/mobilefirst_cli_installer_7.1.0.zip
Or get the very latest iFix from IBM Fix Central.


text:
Q: WPF: Create XpsDocument Pagination I am trying to create a Paginator that will in turn create an XpsDocument that I can preview with the  and then print. I have the following code that I found on the web but do not understand how it is working.
The issue I am having is that if I run this as is, the pages are generated successfully.  If I comment out the lines within OnRender() that generate the actual values of data (all the lines after Random...) I get pages that are about one row high and no text on them but they appear to be the correct length.  What is it that is keeping the values of "Row Number" & "Column i" from being shown?
I have included 2 screen shots to illustrate.
public class TaxCodePrintPaginator : DocumentPaginator
{
    private int _RowsPerPage;
    private Size _PageSize;
    private int _Rows;
    private List<TaxCode> _dataList;

    public TaxCodePrintPaginator(List<TaxCode> dt, int rows, Size pageSize)
    {
        _dataList = dt;
        _Rows = rows;
        PageSize = pageSize;
    }

    public override DocumentPage GetPage(int pageNumber)
    {
        int currentRow = _RowsPerPage * pageNumber;
        var page = new PageElement(currentRow, Math.Min(_RowsPerPage, _Rows - currentRow))
        {
            Width = PageSize.Width,
            Height = PageSize.Height
        };

        page.Arrange(new Rect(new Point(0, 0), PageSize));

        return new DocumentPage(page);
    }

    public override bool IsPageCountValid
    { get { return true; } }

    public override int PageCount
    { get { return (int)Math.Ceiling(_Rows / (double)_RowsPerPage); } }

    public override Size PageSize
    {
        get { return _PageSize; }
        set
        {
            _PageSize = value;

            _RowsPerPage = 40;

            //Can't print anything if you can't fit a row on a page
            Debug.Assert(_RowsPerPage > 0);
        }
    }

    public override IDocumentPaginatorSource Source
    { get { return null; } }
}

public class PageElement : UserControl
{
    private const int PageMargin = 75;
    private const int HeaderHeight = 25;
    private const int LineHeight = 20;
    private const int ColumnWidth = 140;

    private int _CurrentRow;
    private int _Rows;

    public PageElement(int currentRow, int rows)
    {
        Margin = new Thickness(PageMargin);
        _CurrentRow = currentRow;
        _Rows = rows;
    }

    private static FormattedText MakeText(string text)
    {
        return new FormattedText(text, CultureInfo.CurrentCulture,
          FlowDirection.LeftToRight,
          new Typeface("Tahoma"), 14, Brushes.Black);
    }

    public static int RowsPerPage(double height)
    {
        return (int)Math.Floor((height - (2 * PageMargin)
          - HeaderHeight) / LineHeight);
    }

    protected override void OnRender(DrawingContext dc)
    {

        Point curPoint = new Point(0, 0);
        dc.DrawText(MakeText("Row Number"), curPoint);

        curPoint.X += ColumnWidth;
        for (int i = 1; i < 4; i++)
        {
            dc.DrawText(MakeText("Column " + i), curPoint);
            curPoint.X += ColumnWidth;
        }

        curPoint.X = 0;
        curPoint.Y += LineHeight;

        dc.DrawRectangle(Brushes.Black, null, new Rect(curPoint, new Size(Width, 2)));
        curPoint.Y += HeaderHeight - LineHeight;

        Random numberGen = new Random();
        for (int i = _CurrentRow; i < _CurrentRow + _Rows; i++)
        {
            dc.DrawText(MakeText(i.ToString()), curPoint);
            curPoint.X += ColumnWidth;
            for (int j = 1; j < 4; j++)
            {
                dc.DrawText(MakeText(numberGen.Next().ToString()), curPoint);
                curPoint.X += ColumnWidth;
            }
            curPoint.Y += LineHeight;
            curPoint.X = 0;
        }
    }
}

Before

After


text:
Q: Can anyone clarify this whole jQuery method? What's the purpose of this line of jQuery? I know what .scrollTop() does, but documentation claims it cannot be passed arguments --- > http://api.jquery.com/scrolltop/. I takes the pixels scrolled from top and then the scrollHeight property as an argument, I don't get the idea behind it.
$("#container").scrollTop($("#container").prop("scrollHeight"));

A: Setting scrollTop to value of scrollHeight will result in the page scrolling down the height of the entire page, i.e. this will scroll a webpage page down to the very bottom.

A: The 2nd entry for scrollTop docs say it does take an integer value - where the scroll to. So, this bit of code grabs the value of the "scrollHeight" property from the element at ID=container and telling #container to scroll to that value.


text:
Q: Aspects generated by Roo no longer on Classpath I have been using Spring Roo with SpringSource Tool Suite for the past 10 months with no problem. Now, while my code continues to compile in Maven, none of the generated aspects are on the classpath in Eclipse, so I am getting red flag errors for all of invocations of code generated by Roo, for example: getters and setters, finders on the entities and the toString().
The roo .aj files are generated side by side with the entities, so
@RooJavaBean
@RooToString
@RooEntity
public class Applicant extends Responsibility {

    @OneToOne(cascade=CascadeType.ALL, mappedBy = "applicant")
    private ApplicantProfile applicantProfile;

}

produces Applicant_Roo_Configurable.aj, Applicant_Roo_ToString.aj, Applicant_Roo_Entity.aj
e.g.
privileged aspect Applicant_Roo_JavaBean {

public ApplicantProfile Applicant.getApplicantProfile() {
    return this.applicantProfile;
}

public void Applicant.setApplicantProfile(ApplicantProfile applicantProfile) {
    this.applicantProfile = applicantProfile;
}

}

A: Two possibilities that I can see:

*

*Your project is not an AspectJ project.  In the .project file (hidden by default, but "Open resource can find it), you should see org.eclipse.ajdt.ui.ajnature as one of the natures.

*The .aj files have been excluded from the build.

if #1, then select project, right-click, Configure -> Convert to AspectJ project.  If #2, then Project -> Properties -> Java Build Path -> Source and remove all exclusion filters from all source folders.

A: Thanks for the pointers Andrew. As you mentioned in point #2 above, for some reason, my .aj files were automatically excluded from the build.
I included '*/.aj' in  Project -> Properties -> Java Build Path -> Source. Worked like a charm.


text:
Q: Strange behavior with Mongoose First, this code works perfectly since today, I don't know why, this have changed, and I didn't modify it. This is the code:
app.post('/upload', function (req, res){

  var tags = req.body.tags.split(" ");

  usermodel.findOne({ user: req.session.user }, function (err, user){

    console.log(user);

   var img = user.imagen.push({

     title: req.body.title,
     name: req.files.art.name,
     author: user.user,
     description: req.body.description,
     index: user.imagen.length + 1,
     path: './users/' + user.user + '/' + req.files.art.name,
     dowload: req.body.share,
     tags: tags

  });

    user.save(function (err, suser){

     if (err) throw err;

    fs.readFile(req.files.art.path, function(err, data){

       if (err) throw err;

       fs.writeFile(user.path + '/' + req.files.art.name, data, function(err){

             if(err) throw err;

             res.redirect('/home');

      });
     });
    });
  });

And when I checked an user, the imagen array of that user, looks like this '[object Object]'. Why this happens? Any solution for this...?
Thank's advance!
EDITED:
This is the Schema:
var userschema = new mongoose.Schema({
  user: String,
  pass: String,
  imagen: [{

              title: String,
              name: String,
              views: Number,
              type: String,
              author: String,
              tags: [String],
              description: String,
              index: Number,
              path: String,
              date: { type: Date, default: Date.now },
              dowload: String,
              like: Number,

           }],

});


text:
Q: In my layout there is recyclerview and bottom navigation bar but navigation bar goes behinf the recycler view In my layout there is recyclerview and bottom navigation bar but the problem is that the recyclerview occupies all the view and the bottom navigation bar and the header bad goes behind the recycler view. I've sucessfully implemented the material dependency.
this is the layout:

This is the code of the layout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/baseLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--status bar-->
    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/default_activity_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:backgroundTint="@color/buttoncolor"
        app:menu="@menu/default_menu" />

    <!--add button-->
    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/buttoncolor"
        app:fabAlignmentMode="end"
        app:fabCradleMargin="6.2sp"
        app:fabCradleRoundedCornerRadius="15sp"
        app:menu="@menu/app_bar_menu" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:backgroundTint="#ED4444"
        android:onClick="openCamera"
        android:src="@drawable/ic_add"
        app:layout_anchor="@id/bottomAppBar"

        app:maxImageSize="35sp"
        app:tint="@color/white" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rw"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/empty_list" />

        <LinearLayout
            android:id="@+id/empty_list"
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/empty_list_icon"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:background="@drawable/ic_no_data" />

            <TextView
                android:id="@+id/empty_list_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="Scan the files"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textSize="24dp"
                android:gravity="center_horizontal"/>

            <TextView
                android:id="@+id/empty_list_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Scan to make something great"
                android:paddingLeft="40dp"
                android:paddingRight="40dp"
                android:gravity="center_horizontal" />

        </LinearLayout>

    </RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

A: Try this by giving specific height to the BottomAppBar. Then provide margin top and Bottom to the RelativeLayout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/baseLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--status bar-->
    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/default_activity_button"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="top"
        android:backgroundTint="@color/buttoncolor"
        app:menu="@menu/default_menu" />

    <!--add button-->
    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:backgroundTint="@color/buttoncolor"
        app:fabAlignmentMode="end"
        app:fabCradleMargin="6.2sp"
        app:fabCradleRoundedCornerRadius="15sp"
        app:menu="@menu/app_bar_menu" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:backgroundTint="#ED4444"
        android:onClick="openCamera"
        android:src="@drawable/ic_add"
        app:layout_anchor="@id/bottomAppBar"

        app:maxImageSize="35sp"
        app:tint="@color/white" />

    <RelativeLayout
        android:layout_marginTop="50dp"
        android:layout_marginBottom="50dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rw"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/empty_list" />

        <LinearLayout
            android:id="@+id/empty_list"
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/empty_list_icon"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:background="@drawable/ic_no_data" />

            <TextView
                android:id="@+id/empty_list_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="Scan the files"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textSize="24dp"
                android:gravity="center_horizontal"/>

            <TextView
                android:id="@+id/empty_list_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Scan to make something great"
                android:paddingLeft="40dp"
                android:paddingRight="40dp"
                android:gravity="center_horizontal" />

        </LinearLayout>

    </RelativeLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
Q: What is the least-dirty way to expose private javascript vars for testing? I've got a state machine in JS which (to simplify) has an initial state that is only set before anything happens.
define(function() {
  var state = 'initial',
      exports = {};

  exports.getState = function() {
    return state;
  };

  exports.doSomething = function() {
    state = 'newState';
  };

  return exports;
});

Because the state is permanent until the app is reloaded, after the first test the state will never be 'initial' again, and so I need a way to reset it.
Which is the least dirty way of doing this? Should I...
a) simply make state public but mark it as private with _?
define(function() {
  var exports = {};

  exports._state = 'initial'

  exports.getState = function() {
    return this.state;
  };

  exports.doSomething = function() {
    this.state = 'newState';
  };

  return exports;
});

b) make the state writable via a function?
define(function() {
  var state = 'initial',
      exports = {};

  exports.getState = function() {
    return state;
  };

  exports.doSomething = function() {
    state = 'newState';
  };

  if(window.xxTests) {
    window.xxTests.Module = {
      setState: function(newState) {
        state = newState;
      }
    };
  }

  return exports;
});

(where xx is the app prefix and xxTests is defined only as part of the test runner)
or
c) do something else entirely I didn't think of?
Your thoughts and suggestions are appreciated.

A: General answer: The better way of testing a component without exposing private data is putting test code inside that component. Of course this becomes quite dirty if your language doesn't support this in a clean way (like D does).
In your case I suggest the second way (I mean your option b), because it doesn't expose private data unless explicitly needed (only during tests):
if(youAreDoingATest)
{
    exports.reset=function() { state='initial'; };
}

A: There's not a lot of context on how you're running your tests.
Most test runners have beforeEach(), beforeAll(), afterEach(), and afterAll() methods that can be used for setup and tear-down that run as their names suggest.
To solve your specific problem I would not change your "state machine" code at but instead I would create a new state machine in the beforeEach() function so that each test gets the new function object with the state set to 'initial'.


text:
Q: Suppress parskip BEFORE (sic!) a specific paragraph? Imagine the following document:
\documentclass{article}
\setlength{\parskip}{8pt}
\begin{document}
This is the first paragraph

This is the second paragraph

This is the third paragraph
\end{document}

I now want to modify the second (not the third!!) paragraph so that there is no spacing between the second and the third paragraph.
There are many ways to modify the third paragraph so that there is no parskip between the second and the third - but i must modify the second one.
Simplest example for a solution that does NOT fit for me:
{\setlength{\parskip}{0pt}This is the third paragraph}

Why?
The document seen here is a minimal example of LaTeX code generated by the WYSIWYM editor LyX.
In LyX, I need to create a paragraph layout style (for the second paragraph) that avoids spacing between a paragraph using that style and the following paragraph which is of any other style.
I can only modify the output of the second paragraph, because it is free to the user which style he uses for the following paragraph. All other paragraph styles are "normal" and generate a parskip, which is the normal desired behaviour. (except for the special paragraph style I want to generate)
Unfortunately, there seems to be no way to tell LyX not to generate \n\n after each style without modifying the source code.
Any ideas appreciated!
Update 1:
I found that a negative \vspace with the length of a single \parskip might do the trick, but am unsure about unforeseen consequences:
\documentclass{article}
\setlength{\parskip}{8pt}
\begin{document}
This is the first paragraph

This is the second paragraph\vspace{-\parskip}

This is the third paragraph
\end{document}

What could happen when i use the negative vspace in this context inside a large, auto-generated document?

A: While I show \noparskip at the end of the 2nd paragraph, it can appear anywhere in the paragraph (INCLUDING the very beginning) and achieve the same effect.
EDIT: My concern with using a simple negative \vspace revolves around pagination that might be artificially brought on by the larger \parskip, prior to the invocation of the negative \vspace.  Whether that is an issue in Lyx, I have no experience to know.  I suppose though, that issuing the negative \vspace prior to the closing \par may be a safe option, but I'll let others comment.
\documentclass{article}
\setlength{\parskip}{8pt}
\let\svpar\par
\edef\svparskip{\the\parskip}
\def\revertpar{\svpar\setlength\parskip{\svparskip}\let\par\svpar}
\def\noparskip{\leavevmode\setlength\parskip{0pt}%
  \def\par{\svpar\let\par\revertpar}}
\begin{document}
This is the first paragraph

This is the second paragraph\noparskip

This is the third paragraph

This is the fourth paragraph
\end{document}

A: With the awesome help of @Inkane, I've tried to develop a version of Steven's code that interacts more nicely with enumerate and itemize environments. It's used like Steven's implementation, but has the following changes:

*

*It does not prevent the parskip when the next paragraph is an enumerate or itemize.

*It does not change the internal spacing in a list following \noparskip.

Here's the implementation:
\makeatletter
\newlength\noparskip@parskip % used to store a backup of the parskip value
\newboolean{noparskip@triggered} % flag to indicate that noparskip was run in the current paragraph
\setboolean{noparskip@triggered}{false}
\newboolean{noparskip@active} % flag to indicate that parskip should be restored after this paragraph
\setboolean{noparskip@active}{false}
\let\noparskip@par\par % store a backup of the \par command
\@setpar{% redefine \par with the means of ltpar.dtx to stay compatible to enumerate and itemize
    \ifhmode% since we're counting occurrences of \par, \par\par would be a problem, so check that we are actually ending a paragraph
        \ifthenelse{\boolean{noparskip@active}}{%
            \setlength\parskip\noparskip@parskip% restore parskip
            \setboolean{noparskip@active}{false}% remember not the restore parskip again
        }{}%
        \ifthenelse{\boolean{noparskip@triggered}}{%
            \ifthenelse{\boolean{noparskip@active}}{}{
                % we are triggering noparskip and not currently in a noparskip already
                \setlength\noparskip@parskip\parskip % copy the current parskip into the backup variable
            }%
            \setboolean{noparskip@triggered}{false}% paragraph is ending, so noparskip is no longer triggered
            \setlength\parskip{0pt}% no parskip when the next paragraph begins
            \setboolean{noparskip@active}{true}% parskip must be restored by the next par
        }{}%
    \fi%
    \noparskip@par% run the original par command
}
\def\noparskip@backout{%
    \ifthenelse{\boolean{noparskip@active}}{%
        % a list is beginning and parskip is currently set to zero, wich would mess up the list
        \setlength\parskip{\noparskip@parskip}% restore parskip before the list begins
        \setboolean{noparskip@active}{false}%
    }{}%
    \setboolean{noparskip@triggered}{false}% there's no sense in keeping noparskip triggered throughout a list
}
\xpretocmd\begin{%
    \ifstrequal{#1}{enumerate}{\noparskip@backout}{}%
    \ifstrequal{#1}{itemize}{\noparskip@backout}{}%
    \ifstrequal{#1}{list}{\noparskip@backout}{}%
}{}{}
\def\noparskip{%
    \leavevmode% ensure that we are within a paragraph
    \setboolean{noparskip@triggered}{true}% trigger noparskip
}
\makeatother

It needs \usepackage{xpatch} to run.


text:
Q: How to change size of logcat buffer in Android? I noticed that the size of the logcat buffer varies on different devices. Assuming I have root permissions on my device, is there a way to change the buffer size of the main buffer at runtime? If not, then assuming I can rebuild the Android image, how do I change it at compile time? I'm looking to enlarge it for diagnostic purposes.

A: According to the newsgroup Android Developers, logcat buffer size:

The log buffers on the device are 64 KB. The timestamp, process ID,
  and log level are stored in a compact format, so you may actually get
  more than 64 KB of formatted data out of logcat -d -v <mode>.

A: No, as per here it seems that the log buffers on the device are 64 KB. The timestamp, process ID, and log level are stored in a compact format, so you may actually get more than 64 KB of formatted data out of logcat -d -v <mode>.
See also Stack Overflow question What is the size limit for Logcat?.
Anyway, for saving logs elsewhere, you have Reading and Writing Logs. That maybe could help you.

A: The buffer size is determined by the kernel, found in */drivers/staging/android/logger.c.
Which buffers are used and the size has changed with Android versions. Android 3.0 (Honeycomb) and newer also have a system buffer, and all four are 256 KB. You have to recompile the kernel to change it.

A: "Logger buffer size option" in "Developer options"
It allows to change the size to a few values between 64k and 16M.
adb logcat -g then immediately shows the update limit.
Tested on 5.1.1, and this answer claims that it is a recent addition.

A: See current buffer size
adb logcat -g

Set all type buffer size (main, system, crash)
adb logcat -G 16M # 16M can be replace by (128K ~ 16M)

Set specific type buffer size (main, system, crash)
adb logcat -b system -G 8M # system can be replaced with 'main' or 'crash'

A: Set the size of the log ring buffer
adb logcat -G <size>

Append K or M to indicate kilobytes or megabytes
Example: adb logcat -G 512K

A: You can increase the value of idea.cycle.buffer.size=1024 in property file android-studio\bin\idea.properties. This worked for me.

A: To set logcat buffer to 16Mb for a specific Android device through adb, I used:
adb -s 2615a1d4e3174a6e logcat -G 16M

But you can use just:
adb logcat -G 16M

Or set previous buffer size with:
adb logcat -G 256K


text:
Q: winexe error: Cannot connect to svcctl pipe. NT_STATUS_ACCESS_DENIED Am trying to execute the following winexe command, but it throws 'ERROR: Cannot connect to svcctl pipe. NT_STATUS_ACCESS_DENIED.'
winexe -U domain/username%password //windows_machine ipconfig

debug info shows,
ERROR: smb_raw_open_recv - NT_STATUS_ACCESS_DENIED
ERROR: on_ctrl_pipe_error - NT_STATUS_ACCESS_DENIED
ERROR: Cannot open control pipe - NT_STATUS_ACCESS_DENIED

When i have 'winexesvc.exe' in Windows machine, the command works.
My understanding according to http://opensourceinfo.blogspot.com/ is that winexe itself creates winexesvc service, starts it and tries to connect to control pipe.  If that's the case, what setting should i have in Windows to resolve Access Denied error and get the service installed successfully? Please correct me if am wrong.
I also came across similar issue in https://sourceforge.net/p/winexe/bugs/35/ post, but am unable to understand the given resolution 'I was trying to log on via a domain user, but only local users were configured'
Note that I have already set,
1. Network Access: Sharing and security model for
local accounts" to "Classic – local users authenticate as themselves
2. LocalAccountTokenFilterPolicy to 1.
So do we need to manually place winexesvc.exe in Windows machine for winexe to work or can we fix the above Access Denied error?
Thanks in advance.


text:
Q: Possible to resolve Git conflict on single file using Ours / Theirs? I've found many instructions on Stack Overflow and elsewhere for resolving conflicts using the OURS/THEIRS dynamic, in cases where you simply want to overwrite one file with another (particularly binary files). However in almost every example I find, it's always been applied en masse to all conflicts, whereas I only want to apply it to a single conflicted file.
One supposed solution I found is to use the git mergetool command. However the mergetool is giving me issues, where I select "choose left" or "choose right" and nothing happens.
Regardless of mergetool though, I'd like to know anyway if there is a way to do this from the command line. I'm sure there is, and if anyone would let me know the command, or otherwise link me to the SO question I must not be finding, I'd appreciate it greatly.
I've also tried using...
git checkout --theirs PATH/TO/CONFLICTED/FILE
But then when I enter 'git status', it still shows the file as conflicted.
Thank you so much for your time.

A: TL;DR
You will need to git add the final resolution, unless you use a different method to extract the "ours" or "theirs" version.
Long
Each merge tool is independent of Git (Git just runs them and lets them do their things) so for that particular sub-part of this question, you must consult the merge tool itself.
As for the git checkout --ours or git checkout --theirs, well, this is where what Git calls the index shows its full bit of complexity.  Remember that the index, which is otherwise kind of mysterious and is also called the staging area and sometimes the cache, is essentially where you and Git build up the next commit you will make.
When you run:
git merge <commit-or-branch-specifier>

Git finds three commits:

*

*One is your current commit, which is the one you're always working with at any given time, so that's not really special, except that you can refer to it by the name HEAD or the single character @ (e.g., git rev-parse HEAD or git rev-parse @ to get its hash ID).

*One is the commit you just named.  If you ran git merge otherbranch, you can run git rev-parse otherbranch to see what its commit hash ID is right now.  (Branch names have the property of moving: that is, the commit identified by a branch name right now is not necessarily as the commit identified by that name yesterday, or tomorrow.  This motion of branch names is how branches grow.)  Of course if you ran git merge a123456, the other commit, the one for --theirs, is hash ID a123456.

*The last commit is the merge base, which Git finds for you automatically.  It finds this commit by using the parent linkages from your commit and the other commit, to work backwards through both branches until it finds the appropriate point where the two branches first come back together.

Having found the three commits, Git runs, in effect:
git diff --find-renames <merge-base> <ours>    # see what we changed
git diff --find-renames <merge-base> <theirs>  # see what they changed

The merge process—to merge as a verb, as it were—consists of finding these three commits, doing the diff, and combining the changes.  You get a merge conflict when the two sets of changes affect the same lines.
In a file where there are no merge conflicts, Git puts the result into both your work-tree (as an ordinary file) and the index (as the special Git-form of the file, ready to be committed).  So for unconflicted files, there is generally nothing else you need to do.
When there's a merge conflict, though, Git does two unusual things: first, it writes the merge-conflicted version into the work-tree, so that you can edit it as a plain file.  Second, it writes into the index, not one version of the file, but all three: the merge base version, the "ours" version, and the "theirs" version.
Git calls these extra versions higher stages.  Stage number is the merge base, and there's no --base option to access it, but you can use git show :1:path to see it.  Stage number two is the "ours" version: there's --ours but you can also run git show :2:path to see it.  Stage number 3 is the "theirs" version, available through git show :3:path.  These three stages replace the normal stage-zero entry, which is now missing.
In fact, when you run git mergetool, what that does is find the three versions in the index, extract them into regular (non-Git-ified) files, and run the actual merge tool on those three files.  The merge tool is assumed to Do The Right Thing (whatever that turns out to be) to combine the three files into one merged file, after which git mergetool can run git add on the result.
From the command line, though—which is how I do my merges—you can just edit the work-tree file, with its conflict markers, and figure out what the right result is.  Write that out, git add the resulting file, and you're good, because git add notices that the file exists in the three-staged-versions form and erases those three versions, writing instead into stage number zero.
Once there's a stage zero (and no longer stages 1-3), the file is considered resolved.
Now, git checkout --ours -- path just tells Git: Take the stage-2 version out of the index and put it into the work-tree.  The version with --theirs tells Git to take the stage-3 version instead.  In both cases, the index, with its three staged versions, is left alone.  This only extracts from the index, to the work-tree.  (The -- here is just in case the path part is, say, a file named --theirs.  If the file name doesn't resemble an option, you don't need the --.  It's kind of a good habit to use the -- all the time, but most people don't.)
Since the index still has all three staged versions, the file is not yet resolved.  Running git add takes the work-tree file and puts it in slot zero, wiping out the 1-through-3 entries, and now the file is resolved.
Curiously, running git checkout HEAD -- path or git checkout otherbranch -- path causes the file to become resolved.  This is an artifact of Git letting the implementation dictate the interface: internally, when you use git checkout name -- path, Git has to first locate the Git form of the file in the given name (a commit hash or a name like HEAD or otherbranch).  Then it has to copy that Git form into the index ... and this copying wipes out the slot 1-3 entries, writing into the normal slot-zero entry.  Last, Git then extracts the (Git-form) file from index entry zero to the work-tree.
The side effect of this "write to index first, then extract from index to work-tree" is that if the file was in conflicted state—had stages 1-3 active—it's no longer conflicted!  Hence:
git checkout --ours -- file

doesn't resolve the file (because it extracts from index slot 2), but:
git checkout HEAD -- file

does resolve the file (because it extracts from the current commit, going to index slot 0, wiping out 1-3; then extracts from the slot 0 entry it just wrote).
Edit, Jun 2022: Since I wrote the above, Git acquired a new pair of commands, git switch and git restore, that split up the multiple different jobs that git checkout used to combine.  If your Git is version 2.23 or later, you might wish to use git restore rather than git checkout for extracting individual files.  (When using the old git checkout, it's too easy to invoke it the wrong way: even experienced Git users will sometimes mess up here.)  Still, the --ours and --theirs flags to git restore work the same way as with git checkout: they select slots 2 and 3 respectively, always, even during a rebase (see the Postscript below).
Postscript
The above describes the merge-as-a-verb process invoked by the git merge command.  Git's internal merge engines—"merge as a verb"—are also used by git cherry-pick, git revert, and git rebase (among others).  When using these, the "merge base" commit—the entity that fills slot 1—is picked via a different process, and the "ours" and "theirs" commits—the things that go into slots 2 and 3, as named by, e.g., --ours with git checkout or git restore for instance, aren't always straightforward.  I will leave the details for other StackOverflow questions-and-answers, as this is plenty to digest.

A: This is a (slightly) modified version of my answer to this question.
Whenever you want help merging a single file I find it is best to write a custom mergetool which does what you want.  To this end I propose adding the following lines to your .gitconfig file (or equivalent):
[merge]
  conflictstyle = diff3
[mergetool.getours]
  cmd = git-checkout --ours ${MERGED}
  trustExitCode = true
[mergetool.mergeours]
  cmd = git-merge-file --ours ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keepours]
  cmd = sed -I '' -e '/^<<<<<<</d' -e '/^|||||||/,/^>>>>>>>/d' ${MERGED}
  trustExitCode = true
[mergetool.gettheirs]
  cmd = git-checkout --theirs ${MERGED}
  trustExitCode = true
[mergetool.mergetheirs]
  cmd = git-merge-file --theirs ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keeptheirs]
  cmd = sed -I '' -e '/^<<<<<<</,/^=======/d' -e '/^>>>>>>>/d' ${MERGED}
  trustExitCode = true

The get(ours|theirs) tool just keeps the respective version of the file and throws away all of the changes from the other version (so no merging occurs).  This is the method you request with regards to binary files.
The merge(ours|theirs) tool re-does the three way merge from the local, base, and remote versions of the file, choosing to resolve conflicts in the given direction.  This has some caveats, specifically: it ignores the diff options that were passed to the merge command (such as algorithm and whitespace handling); does the merge cleanly from the original files (so any manual changes to the file are discarded, which could be good or bad); and has the advantage that it cannot be confused by diff markers that are supposed to be in the file.
The keep(ours|theirs) tool simply edits out the diff markers and enclosed sections, detecting them by regular expression.  This has the advantage that it preserves the diff options from the merge command and allows you to resolve some conflicts by hand and then automatically resolve the rest.  It has the disadvantage that if there are other conflict markers in the file it could get confused.
These are all used by running git mergetool -t (get|merge|keep)(ours|theirs) [<filename>] where if <filename> is not supplied it processes all conflicted files.
Generally speaking, assuming you know there are no diff markers to confuse the regular expression (and you're not dealing with binary files which cannot be merged), the keep* variants of the command are the most powerful.  If you leave the mergetool.keepBackup option unset or true then after the merge you can diff the *.orig file against the result of the merge to check that it makes sense.  As an example, I run the following after the mergetool just to inspect the changes before committing:
for f in `find . -name '*.orig'`; do vimdiff $f ${f%.orig}; done

Note: If the merge.conflictstyle is not diff3 then the /^|||||||/ pattern in the sed rule needs to be /^=======/ instead.


text:
Q: Tkinter Missing possitional argument I'm trying to make a GUI, that will tell me when I press numbers: 1,2,3,4, It works fine, but It throws an error message in background, when I press the button. It looks like this
    xception in Tkinter callback
    Traceback (most recent call last):
    File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
    File "/usr/lib/python3.7/tkinter/__init__.py", line 749, in callit
    func(*args)
    TypeError: shukkin() missing 1 required positional argument: 'event'

Can someone please tell my, how to make a def shukkin(event): stop throwing that error msg? Where is a problem.
Here is the code
from tkinter import *
from tkinter import ttk
from tkinter import font
from tkinter import Button as bt
import time

def quit(*args):
    root.destroy()

def show_time():
    txt.set(time.strftime("%H:%M:%S"))
    root.after(1000, show_time)

def shukkin(event):
    txt2.set("1")
    fm3.after(100, shukkin)
def taikin(event):
    txt2.set("2")
    fm3.after(100, taikin)
def shuuchou(event):
    txt2.set("3")
    fm3.after(100, shuuchou)
def hoka(event):
    txt2.set("4")
    fm3.after(100, hoka)

root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
for i in range(10):
    root.bind(str(1), shukkin)
    root.bind(str(2), taikin)
    root.bind(str(3), shuuchou)
    root.bind(str(4), hoka)
root.bind("<Escape>", quit)
root.bind("x", quit)
root.after(1000, show_time)

fnt = font.Font(family='Helvetica', size=96, weight='bold')
fnt2 = font.Font(family='Helvetica', size=30)
txt = StringVar()
txt.set(time.strftime("%H:%M:%S"))
fm = Frame(root)
fm.configure(background='black')
lbl = ttk.Label(fm, textvariable=txt, font=fnt, foreground="#469aff", background="black").pack(anchor=NW,padx=40, pady=40)
fm.pack(side=LEFT, fill=BOTH)

fm2 = Frame(root)
lbl = ttk.Label(fm2, text="ボタンを押して下さい \n 1:出勤 \n 2:退勤 \n 3:出張 \n 4:その他",
                font=fnt2, foreground="#469aff", background="black").pack(side=RIGHT)
fm2.pack(side=TOP, padx=8, pady=130)

fm3 = Frame(root,  width=500, height=500)
txt2 = StringVar()
but = ttk.Label(fm3, textvariable=txt2, font=fnt, foreground="#469aff", background="black").pack()
fm3.pack(side=TOP)

root.mainloop()

A: Your shukkin takes an event as arg, but there is no event generated by the after method, hence the error.
Simply make a small change to your shukkin function to make event optional:
def shukkin(event=None):
    txt2.set("1")
    fm3.after(100, shukkin)


text:
Q: How to calling a function in a .net dll through an interface loaded through reflection Hello I'll try my best to explain this.
Basically, I am loading a library through reflection using the Assembly.LoadFile.
From there I have an interface IFace that defines a method "GetStrings" that returns an array of strings.
The dynamically loaded DLL has a class named "Class1" that implements IFace.
I need a way to call this interfaced method through the dynamically loaded lib.  I'd like to keep it tightly coupled, which leaves me wondering what to do.  I know I can use MethodInvoker to call the method, but I'm trying to find a way I can do something like this:
IFace obj = (IFace)ReflectionAssembly.Class1;
string[] strs = obj.GetStrings();

Any ideas?

A: Something like:
    var assm = Assembly.Load("ClassLibrary1");
    var type = assm.GetType("ClassLibrary1.Class1");
    var instance = Activator.CreateInstance(type) as IFace;
    string[] strings = instance.GetStrings();

A: Use Assembly.CreateInstance() to create the object, pass it a 'well known name'.  Cast the return value to IFace, the rest is easy.  Oh, don't use LoadFile, use LoadFrom.

A: Once you have the Type via Reflection (using something like Assembly.GetType), you can use Activator.CreateInstance:
IFace obj = (IFace)Activator.CreateInstance(class1Type);
string[] strs = obj.GetStrings();


text:
Q: Sequential testing for a Bernoulli variable Suppose $T$ is a Bernoulli random variable, such that $T = 1$ with probability $s$, $s$ is not known.
I am interested in checking hypothesis $H_1$ that $s \neq 1/2$ ($H_0$ is that $s = 1/2$). One way to do that is to get some 100K of realizations of $T$, and run the binomial test, check the p-value etc. However, sometimes $s$ is pretty far from $1/2$, and in that case I want to stop my experiment as early as possible once I've got enough evidence to reject $H_0$ (low $s$ means that the experiment participants are 'suffering', and generally I want to avoid that; high $s$ means that I can improve life for everyone and generally I want to do that asap).
My idea was to deploy a sequential testing procedure: I split the experiment in 5 equally sized stages (e.g. 20K realizations each) and after each stage I calculate p-values, compare to the predefined thresholds, and decide to stop the experiment or to continue. This idea is inspired by O'Brien & Fleming procedure (O'Brien & Fleming, Biometrics '79).
There exist quite extensive literature on sequential testing, R package gsDesign, etc. However, as the topic is mostly studied in the medical context, usually a control/test split is assumed. Thus I failed to find a guidance how to design the sequential experiment protocol for my set-up: given pre-fixed values for Type I and II errors, the number of stops, I want to find p-value thresholds (or other stopping criteria) for each of the stops.
Could anyone provide me with a relevant link?

A: It might be that the group sequential testing approach is overkill for your application.  That is most useful when it is costly to perform interim analyses.  If you have very little cost to analysis, then you can just do sequential testing.
There are many references to cover the theory of sequential testing.   Your case is usually covered as an example along with the normal distribution.  (For example, see II.3 of (Siegmund, 1985)).
There is plenty of literature on acceptance sampling and process monitoring that also bears on this problem if you need to perform batch sampling.
However, for sequential testing, the original paper on the sequential probability ratio test by (Wald, 1945) is very readable and available online.  Your case is covered in Section 5.2.
To apply the procedure, you will need to specify a probability that is good enough to accept ( $p_0$), and a probability that is bad enough to reject ($p_1$), in addition to your usual error rates $\alpha$ and $\beta$.  Then, you monitor the number of bad outcomes.
Let $d_m$ be the number of bad outcomes at the $m$th trial.  Then you accept $H_0$ if $d_m \le A_m$, accept $H_1$ if $d_m \ge R_m$, and continue sampling if $A_m < d_m < R_m$.
$A_m$ is called the acceptance number and $R_m$ is called the rejection number.  They are calculated as
$$A_m =
\frac{
\log \frac{\beta}{1-\alpha}
}
{
\log \frac{p_1}{p_0} - \log \frac{1-p_1}{1-p_0}
}
+
m
\frac{
\log \frac{1-p_0}{1-p_1}
}
{
\log \frac{p_1}{p_0} - \log \frac{1-p_1}{1-p_0}
}
$$
and
$$R_m =
\frac{
\log \frac{1-\beta}{\alpha}
}
{
\log \frac{p_1}{p_0} - \log \frac{1-p_1}{1-p_0}
}
+
m
\frac{
\log \frac{1-p_0}{1-p_1}
}
{
\log \frac{p_1}{p_0} - \log \frac{1-p_1}{1-p_0}
}.
$$
There is plenty of theory there if you want, including certainty of stopping, expected sample sizes, and efficiency.  This formulation does not incorporate economic costs.
References:
Siegmund, D. (1985) Sequential Analysis:  Tests and Confidence Intervals.  Springer-Verlag.
Wald, A. (1945). Sequential tests of statistical hypotheses. The Annals of Mathematical Statistics, 16(2), 117-186.


text:
Q: Show that if $X$ is $T_0$ and $T_3$, then $X$ is regular.
Show that if $X$ is $T_0$ and $T_3$, then $X$ is regular.

I need to show that $T_0$ and $T_3$ implies that $X$ is $T_1$. So let $a,b \in X$ s.t $a \ne b$. As $X$ is $T_0$ there exists nbhd of $a$ namely $U_a$ such that $a \in U_a$ and $b \notin U_a$.
Now since $U_a$ is open $U_a^c$ is closed and $b \in U_a^c$.
Since $X$ is $T_3$ we can find open nbhd's for $a$ and $U_a^c$, but $b \in U_a^c$ so we can find disjoint open nbhd's for $a$ and $b$ implying that the space is also $T_1$.
Am I correct here? I think that I can use the complement of $U_a$ to find the nbhd's for $a$ and $b$ such that they don't belong to their repsective nbhd's.

A: Yes, that works. $T_0$ gives an assymetric separation that the $T_3$ property can fix, straight to Hausdorff even:
If $a \neq b$, we have $U_a$ so that $a \in U_a$, $b \notin U_a$ WLOG. ($T_0$ just gives us one open set, not two, but you don't know a priori where each point lies, after renaming we can assume $a$ is in the open set).
Then we separate $a$ and the closed set $X\setminus U_a$ by disjoint open sets $a \in V_a$, $X\setminus U_a \subseteq W_b$ with $V_a \cap W_b = \emptyset$. Then $b \in W_b$ and $a \in U_a \cap V_a$ are open and disjoint neighbourhoods of $a$ and $b$ and $X$ is even $T_2$ (and hence $T_1$ a fortiori).


text:
Q: Is there any geometrical intuition for the Hurewicz theorem? I'm not well-versed in algebraic topology, so I'm not completely sure how to ask this.
If I understand correctly, the fundamental group of space $X$ at point $x$ is the group of equivalence classes of loops $l:I\rightarrow X$, $I$ is the unit interval and $l(0)=l(1)=x$, under the equivalence relation of homotopy - two loops, $l$ and $k$, are homotopic if there exists a continuous map $h:I\times I \rightarrow X$ s.t. $h(0, \cdot )=l$ and $h(1, \cdot )=k$. The group operation is concatenation of loops - just go through the first loop twice as fast and then the second loop twice as fast. The nth homotopy group is the same idea just extended to the nth dimension. If a 1-homotopy is a path (loops in this case), an n-homotopy is a continuous map from the n-cube into the space s.t. the map at each end of the cube is an (n-1)-homotopy. The nth homotopy group is the set of equivalence classes of n-homotopies under an operation which is basically a high-dimensional version of concatenation of loops whose endpoints agree.
I feel I have a much better grasp of homology groups so I won't explicate it here.
My question is whether or not there is any intuition for why there is a homomorphism from the nth homotopy group to the nth homology group. What about specifically the fact that $H_1$ is the abelianization of $\pi_1$? If there isn't intuition for either of these in general, is there a way to visualize the homotopy and homology groups of a specific space and see why there is a homomorphism from one to the other?

A: That there is a map is not surprising: An element of $\pi_n(X)$  is nothing but a map $S^n\rightarrow X$ satisfying some conditions. But any map induces maps in homology. More specifically there is a map $H_n(S^n;\mathbb{Z})\rightarrow H_n(X;\mathbb{Z})$. Now all these maps patch together to a map $\pi_n(X)\rightarrow H_n(X;\mathbb{Z})$. Geometrically you can think of this as follows: Choose a triangulation of $S^n$ (this generates $H_n(S^n;\mathbb{Z})$). Then the Hurewicz map puts this cycle into $X$. It turns out that this is a group homomorphism.
The homology group $H_1(X;\mathbb{Z})$ is abelian, while $\pi_1(X)$ is in general not. Hence the map $\pi_1(X)\rightarrow H_n(X;\mathbb{Z})$ must factor through the abelianization $\pi_1(X)_{\mathrm{ab}}$, i.e. we obtain a map $\pi_1(X)_{\mathrm{ab}}\rightarrow H_1(X;\mathbb{Z})$. It turns out that this is an isomorphism. Now more generally if $n>1$ the Hurewicz map $h:\pi_n(X)\rightarrow H_n(X;\mathbb{Z})$ is an isomorphism if $\pi_k(X)=0$ for $k<n$: If the low dimensional topology of $X$ is not too complicated the $n$ dimensional topology is generated by spheres. You can play around with surfaces to see that this map can't be always an isomorphism (how do you map $S^2\rightarrow \Sigma_g$ , where $\Sigma_g$ is a surface of genus $g>0$, non trivially?)


text:
Q: Using projection matrix on GLKMatrixStack Given this setup:
GLKMatrixStackRef transformHierarchy = GLKMatrixStackCreate (kCFAllocatorDefault);

float aspect = (float)self.drawableWidth / (float)self.drawableHeight;
float fov = PI * 0.125;
float height = 10.0f;
float cameraOffset = -height / (2.0f * tanf (fov / 2.0f));

GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective (fov, aspect, 0.01f, 1000.0f);
GLKMatrix4 T = GLKMatrix4MakeTranslation (0.0f, 0.0f, cameraOffset);

I would expect these two options to create an identical matrix on the top of the stack. Option A:
GLKMatrixStackLoadMatrix4 (transformHierarchy, projectionMatrix);
GLKMatrixStackTranslate (transformHierarchy, 0.0f, 0.0f, cameraOffset);

Option B:
GLKMatrixStackLoadMatrix4 (transformHierarchy, GLKMatrix4Multiply (projectionMatrix, T));

Option A gives me a black screen:
3.351560 0.000000 0.000000 0.000000
0.000000 5.027339 0.000000 0.000000
0.000000 0.000000 -1.000020 25.117201
0.000000 0.000000 -1.000000 0.000000

Option B (otherwise identical matrix but with a non-zero m44) gives me the visual result I expect:
3.351560 0.000000 0.000000 0.000000
0.000000 5.027339 0.000000 0.000000
0.000000 0.000000 -1.000020 25.117201
0.000000 0.000000 -1.000000 25.136698

So I've found a solution to my black screen, but the result using GLKMatrixStackTranslate() surprises me. Am I missing something here? Is it not considered a good practice to put the projection + world matrix at the bottom of the stack (to be followed by model transforms)?
UPDATE
Corrected mistake in my cameraOffset math and updated matrix output to match, although it has no effect on the problem as described. Also for clarity I transposed the matrix values (copy/pasted from xcode, which presents them in row-major order), to column-major (as OpenGL interprets them).
Also filed a bug with Apple to inquire if this is the expected behavior.

A: For the record, Apple determined my bug report on this issue to be a duplicate of bug 15419952. I expect people don't run into this much as they might typically keep the projection matrix separate from the model transform stack. In any case the workaround presented in the question works fine.


text:
Q: Sonar and findsecbugs Potential code injection when using Spring Expression We have a spring-boot (2.4.2) application and an Aspect class that does some handling "Around" methods annotated with a custom annotation, defined by us, and using SpEL handling.
The SpEL expressions are defined as fields in the annotation, by us.
When running the Sonar tool, together with Findsecbugs, we are told that we have a vulnerability in the code, with the error "This use of org/springframework/expression/ExpressionParser.parseExpression(Ljava/lang/String;)Lorg/springframework/expression/Expression; could be vulnerable to code injection (Spring Expression)". The offending line is line 4 below:
1. private final ExpressionParser elParser = new SpelExpressionParser();
...
2. @Around(value = "@annotation(myCustomAnnotation)")
3. public Object aroundAdviceHandler(ProceedingJoinPoint joinPoint, MyCustomAnnotation myCustomAnnotation) throws Throwable {
  ...
  4. **Expression expression = elParser.parseExpression(myCustomAnnotation.entityId());**

The annotated code that uses this Aspect looks like:
@Transactional
@MyCustomAnnotation(entityId = "[0].id") // some other methods my have here only "[0]" or "[0].otherId"
public Long save(JustADto dto) {

And finally, the custom Annotation looks like:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) public
@interface MyCustomAnnotation {
    String entityId() default "";
}

This code doesn't seem to have any vulnerability, because the input for the spring expression is provided by us. Is this a false positive by Findsecbugs? Is there any way to prevent the Sonar & Findsecbugs error from appearing, other than using the <@SuppressFBWarnings(value = {"SPEL_INJECTION"}, justification = "false positive")> annotation?

A: The value returned by MyCustomAnnotation.entityId() is an expression that is hard-coded in your code. Because of this I would consider the source to be safe.
You can trust the developers who wrote the code. You can't trust remote users.
Here the value is only controlled by the developer.

Side note: I think it would be reasonable that the tool considered annotations as always safe. I created a ticket to this effect.


text:
Q: Hand coded C# Coded UI Test , Control/Object location issue I have a dropdown menu sub-item ("logout") that I want to select. I need to hover over the menu first to make the logout link appear. There's a lot of div's surrounding it; the spy tells me it's an HTMLPANE, but there's no built-in support for HtmlPanes in VS code as far as I can see. (I try typing it in and intellisense doesnt recognize it, not from htmlcontrols namespace)
Just before trying to describe this main menu object, I'm defining the variable as an HtmlDiv. I've even tried to identify it generically by referring to it as an HtmlControl.
Here's the "view source" of the dropdown menu in question. I need to get to the "Logout" link which is the bottom option in the dropdown.

         Profile

                Edit Profile
                View ID Card
                Request ID Card
                Log Out

I'm not familiar with the `mouse.hover function. Can you please show me an actual example, preferably from this code? I'm not even sure if this is a way to identify it because from what I observed by recording the hover, browser resizing changes the coordinates.
I don't know if I am obliged to give a coordinate to mouse.hover, or can I just specify the name of the object control? (i.e. mouse.hover(varnameformainmenu))


text:
Q: Lua: What is the difference in these variable assignments? what is the difference between the variable assignment
    local newpos = {}
newpos.x = 1       ----- or --------- newpos[x] = 1

i know not what i speak but to me these seem to be the same thing if not similar?

A: newpos.x = 1 is the same as newpos["x"] = 1 that is they both set the value stored at key string "x" to 1.
newpos[x] = 1 is different. This is set the value stored at key contents of variable x to 1.
Try it and see.
local newpos = {}

newpos.x = 1
print(newpos.x, newpos["x"], x, newpos[x])

newpos["x"] = 2
print(newpos.x, newpos["x"], x, newpos[x])

local x = "var"
print(newpos.x, newpos["x"], x, newpos[x])

newpos[x] = 3
print(newpos.x, newpos["x"], x, newpos[x])

Results for the above:
1   1   nil nil
2   2   nil nil
2   2   var nil
2   2   var 3