text:
Q: 3V3 uC input protection from higher voltage? I wanted to confirm some of my suspicion on this particular matter.
This is a part of a switching circuitry with a button.
I derived this circuit from a circuit divider to make this part of the switch work under lower voltages (button tolerates <20V across). So the button enables the MOSFET switch. Yet I need to monitor the state of the button and thus have protected a uC inpt from the gate with a schottky diode.

simulate this circuit – Schematic created using CircuitLab
I can measure gate voltage from the voltage divider on the planned uC input pin node. The idea of the shottky diode was to protect the input from those 'high' voltages but ofcrs could be measured on that node (currently floating).
Should I consider input protection (such as a zener) to limit the voltage on that pin ? Although there's potentially low currents there (due to reverse current of the diode).

A: The MCU input is likely of quite high impedance. You can increase R4 into the kiloOhms to limit any current flowing in MCU protection diodes due to over voltage. Check your data sheet. Putting in D2 won't hurt either

A: As shown D1 blocks and positive voltage on SW1 so you will never get ANY voltage on R4 except due to leakage in D1.   Placing a resistor Rpu = say 10k from uC input to +3V3 will return 3V3 when SW1 is open and about 0.4V (Vfwd across D1) when SW1 is closed.
The ~~= 10 uA leakage current via D1 is notionally able to possibly cause unexpected effects in the uC but is unlikely to in practice.
 The most sensitive feature of a uC is often A2D inputs, which can be adversely affected by very low substrate diode problems.
Equipping D2 with a suitable value zener can prevent this but is unlikely to be necessary. Note that zener diode voltages are usually specified at currents of 10 mA or sometimes 1 mA, so with very low current Vzener will be well below the rated voltage. If you do use a zener, check the spec sheet to determine the appropriate marked value.


text:
Q: Enum multiple cases with the same value in Swift In C you could make your enums have this:
typedef enum _Bar {
    A = 0,
    B = 0,
    C = 1
} Bar;

In Swift I want to make the equivalent. However, the compiler complains that it isn't unique. How do I tell it that I want two cases to have the same value?
enum Bar : Int {
    case A = 0
    case B = 0 // Does not work
    case C = 1
}

I've tried
case A | B = 0

and
case A, B = 0

But it doesn't seem to work as I want it to.

A: Swift doesn't allow elements of an enumto share values. From the documentation on enums under the "Raw Values" heading (emphasis mine):

Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration.

A: I'm not sure you can. The following is taken from Apple.

"Unlike C and Objective-C, Swift enumeration members are not assigned a default integer value when they are created. In the CompassPoints example above, North, South, East and West do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration members are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint."

Excerpt from: Apple Inc. "The Swift Programming Language." iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
Since the enumeration members do not implicitly equal 0, 1, etc., the compiler looks at each as a unique value.  When you try and duplicate it the compiler complains because it has already been created.

A: Swift doesn't support duplicated values (or "aliases" semantically). If you don't mind, you can mimic it by using something like this:
enum Foo: Int {
    case Bar = 0

    static var Baz:Foo {
        get {
            return    Bar
        }
    }
    static var Jar:Foo {
        get {
            return    Foo(rawValue: 0)!
        }
    }
}

With recent version of Swift, this can be shortened like this:
enum Foo: Int {
    case bar = 0

    static var baz:Foo { .bar }
    static var jar:Foo { Foo(rawValue: 0)! }
}

Note that Swift has changed their naming convention of enum variants from PascalCase to camelCase.

A: Here is another way of getting around it:
enum Animal {

  case dog
  case cat
  case mouse
  case zebra

  var description: String {
    switch self {
    case .dog:
      return "dog"

    case .cat:
      return "dog"

    case .mouse:
      return "dog"

    case .zebra:
      return "zebra"

    default:
      break
    }
  }
}

A: I encounter the same problem about multiple case with the same value. After googling this problem, I prefer the following solution with computed properties of enum, which come from this post.

A: You could easily override the == operator to return true every time, except that would be cheating. Let's do this the real way!

I disagree with the accepted answer: Swift does allow raw values to be equivalent, but it does not allow you to write interpretively identical literals. This may cause people to think that what you are asking is impossible. But, your question is answerable, and we will have to work around Swift's lexical grammar a little bit.

i.e. 1.0 and 1.000 are interpretively identical Double literals, since the extra zeroes collapse.

The simplest proof of this is to take advantage over floating point type underflow/overflow. The literals themselves are not identical, but the values themselves are the same.
enum ExhibitA: Double {
    case a = 0.0
    case b = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
}
print(ExhibitA.a == ExhibitA.b) // true
print(ExhibitA.a.rawValue) // 0.0
print(ExhibitA.b.rawValue) // 0.0

So I technically answered your question, but this has no practical value. Let's try and make it work for all numbers, as well as include more types.

If you let your enum cases be JSON decodable String raw values, and apply the ExpressibleByStringLiteral protocol to convert them into their specified type, you can do just that.
import Foundation

struct EnumWrapper<T: Codable & Equatable>: ExpressibleByStringLiteral, Equatable {
    var value: T
    init(_ t: T) { value = t }
    init(stringLiteral value: StringLiteralType) {
        try! self.init(JSONDecoder().decode(T.self, from: Data(value.utf8)))
    }
}

enum Foo: EnumWrapper<Int> {
    case a = "1"
    case b = "1 "
}
print(Foo.a == Foo.b) // true
print(Foo.a.rawValue.value) // 1
print(Foo.b.rawValue.value) // 1

Awesome! Now you can use as a raw value anything that conforms to Decodable.
i.e. a 4D Array of Booleans:
enum Example: EnumWrapper<[[[[Bool]]]]> {
    case woah = "[[[[true, false, true], [false], []], []]]"
}
print(Example.woah.rawValue.value) // [[[[true, false, true], [false], []], []]]

This pattern is dangerous when applied to Sets or Dictionaries. Half the time you run the code below, you will receive a run-time error saying the dictionary has duplicate keys.
let foo : [Foo : Bool] = [
    .a : true,
    .b : false
]

A: I found this by sheer coincidence and was surprised there's no Swift-y dark magic in any of the answers (which are still good, of course). Personally I don't like the static properties as much because they introduce overhead elsewhere, e.g. in the pattern matching.
I think the "cleanest" solution would be to rely on RawRepresentable and define that yourself. Then you can counter the main reason why Swift doesn't support this out of the box: the init?(rawValue:) method. By just specifying String as the adopted raw value (i.e. enum MyEnum: String { ... }) the compiler can't generate the logic for that on its own. It would need to know which case to skip, as there are not "enough" potential raw values defined (since one or more are doubled). Adopting the protocol yourself allows you to simply chose one case as the "default" for a given raw value string and basically prevent the other one from constructed with a raw value (regular construction still works, of course).
Unfortunately that is also a bit of overhead, as the former case myCase = "its_raw_value" then gets distributed over

*

*the regular case (without the raw value String): case myCase (the definition)

*a switch in the init?(rawValue:) method: ... case "its_raw_value": return .myCase ...

*a switch in the required rawValue property: ... case .myCase: return "its_raw_value" ...
I think I have a nice way to reduce that a little and keep the raw values from floating around too much. I wrote a playground to illustrate and will simply paste it here:

// define protocol and a default implementation
protocol SloppyRawRepresentable
where Self: RawRepresentable, Self.RawValue: Hashable, Self: CaseIterable {
}
extension SloppyRawRepresentable {
    init?(rawValue: RawValue) {
        var tempMapping = [RawValue: Self]()
        for oneCase in Self.allCases {
            // first come first served. any case after the first having the same
            // raw value is simply ignored, so the first is the "default"
            if tempMapping[oneCase.rawValue] == nil {
                tempMapping[oneCase.rawValue] = oneCase
            }
        }
        guard let candidate = tempMapping[rawValue] else { return nil }
        self = candidate
    }
}

// use it. Note we don't need the init
enum EventNames: SloppyRawRepresentable {
    typealias RawValue = String

    var rawValue: String {
        switch self {
        case .standardEvent: return "standard"
        case .joesConfig: return "iAmJoe"
        case .myConfig: return "iAmJoe"
        }
    }

    case standardEvent
    case joesConfig
    case myConfig
}

// some example output

print(EventNames.standardEvent)
print(EventNames.joesConfig)
print(EventNames.myConfig)

print(EventNames.standardEvent.rawValue)
print(EventNames.joesConfig.rawValue)
print(EventNames.myConfig.rawValue)

print(EventNames(rawValue: "standard")!)
print(EventNames(rawValue: "iAmJoe")!)
print(EventNames(rawValue: "iAmJoe")!)

print(EventNames(rawValue: "standard")!.rawValue)
print(EventNames(rawValue: "iAmJoe")!.rawValue)
print(EventNames(rawValue: "iAmJoe")!.rawValue)

It should be self-explanatory. The case definition and assigning it its raw value is still split, I don't think there's a way around that, but it can come in handy. Of course all this requires the RawValue be constraint and I rely on the enum be CaseIterable to easily construct that helper dictionary, but I think that should be okay, performance wise.

A: Disclaimer: I'm not recommending this. Most people would not consider best practice. There are downsides, depending on the application. Let's just say these ideas are theoretical, hypothetical, impure, just presented for contemplation
One possibility is to add some sort of meaningless differentiator sufficient to thwart Swift's check for identity that doesn't affect what you are doing with the raw values in your code.
He's an example with a Float, where, in music, A♯ (A sharp) is the same frequency as B♭ (B flat). They are both different annotations for the same thing, in other words.
Differences measured in microHz are meaningless to audio engines, yet sufficient to differentiate case values in a Swift enumeration.  In other words, practically speaking, there is no difference between 116.540 and 116.540001 in most music applications:
enum NoteFrequency : Float = {
   case A = 110.0, A_SHARP = 116.540, B_FLAT = 116.540001
}

Going from quasi-tolerable to uglier: For strings that only get assigned and printed you might add a non-printable character to differentiate.
Obviously this has downsides (potentially serious), if you do something like this and later you (or someone else) might be unaware of what you did, and writes code that doesn't account for it (such as using in rawValue of an enumeration in String comparisons) and their code fails. To make this work in String comparisons you'd have to probably do something to ignore the last character or lop it the unprintable character with myEnumString.rawValue.dropLast() before comparing...
 enum Animals : String = {
     case CAT = "Feline\u{01}", LION = "Feline\u{02}"
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selectable() Jquery mobile alternative I was looking for the solution for my API but I couldn't find.. All examples or advices didn't work. Could somebody help me out? Or give me any suggestion? I'm still studying JQuery, so any help would be more than welcome..
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New api</title>
    <link rel="stylesheet" href="./style.css">

Result

JQuery code:
function screenResolutionAlert(x) {
    if (x.matches) {
        $("#alert").html("This API doesn't work with touchpads
 (mobiles, tablets etc)
 please use computer or laptop with a mouse").show();
    } else {
        $("#alert").hide();
    }
}
var x = window.matchMedia("(max-width: 1200px)")
screenResolutionAlert(x)
x.addListener(screenResolutionAlert)

//API swap words code
$(function () {
    $("#wordblock").sortable();
    $("#wordblock").disableSelection();
    const array = ["pierogi", "gołąbki", "pies", "sześcian"];
    const word = array[Math.floor(Math.random() * array.length)];
    let d_word = word.split('');
    shuffle(d_word);

    const lis = [];
    for (let i = 0; i < d_word.length; i++) {
        lis.push('
' + d_word[i] + '
')
    }

    $('#wordblock').html(lis.join(''));

    $('#wordblock').mouseup(function () {
        setTimeout(() => {
            let r_word = '';
            $('#wordblock>li').each(function (e) {
                r_word += $(this).text();
            });
            if (r_word == word) {
                $("#result").html(`Correct! It was exactly "${r_word}"`);
            } else {
                $("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
            }
        }, 0);
    });

});

function shuffle(a, b, c, d) {
    c = a.length;
    while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}

Yes I was using mobile Jquery links, didn't work... And any versions of.. I tried everything what was written in the internet ;(

A: I tried your code and ...it seems to work! Snippet is here below, just press Run code snippet, and order letters to "PIES".
I suggest you to read about APIs, because at the moment you're not using any API at all!

function screenResolutionAlert(x) {
  if (x.matches) {
    $("#alert")
      .html(
        "This API doesn't work with touchpads
 (mobiles, tablets etc)
 please use computer or laptop with a mouse"
      )
      .show();
  } else {
    $("#alert").hide();
  }
}
var x = window.matchMedia("(max-width: 1200px)");
screenResolutionAlert(x);
x.addListener(screenResolutionAlert);

//API swap words code
$(function () {
  $("#wordblock").sortable();
  $("#wordblock").disableSelection();
  const array = ["pies"];
  const word = array[Math.floor(Math.random() * array.length)];
  let d_word = word.split("");
  shuffle(d_word);

  const lis = [];
  for (let i = 0; i < d_word.length; i++) {
    lis.push('
' + d_word[i] + "
");
  }

  $("#wordblock").html(lis.join(""));

  $("#wordblock").mouseup(function () {
    setTimeout(() => {
      let r_word = "";
      $("#wordblock>li").each(function (e) {
        r_word += $(this).text();
      });
      if (r_word == word) {
        $("#result").html(`Correct! It was exactly "${r_word}"`);
      } else {
        $("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
      }
    }, 0);
  });
});

function shuffle(a, b, c, d) {
  c = a.length;
  while (c)
    (b = (Math.random() * (--c + 1)) | 0),
      (d = a[c]),
      (a[c] = a[b]),
      (a[b] = d);
}
ul#wordblock {
  padding-left: 0;
}

ul#wordblock li {
  display: inline-block;
  font-size: 2em;
  padding: 0.2em 0.2em;
  cursor: pointer;
  background-color: aliceblue;
  border-radius: 50%;
  margin: 0.5em;
  width: 1em;
  height: 1em;
  text-align: center;
  line-height: 0.9em;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>New api</title>
  <link rel="stylesheet" href="./style.css">

Result


text:
Q: Automatically convert date text to correct date format using Google Sheets I'm trying to convert date from "text" to correct format. It is logged to Google Spreadsheets and I'm unable to use it to plot graphs.
This is the text format: February 3, 2018, at 11:21 AM
Time is not relevant, all I need is the date converted: DD/MM/YYYY.
I found a similar question where Gary's Student answered with a formula that looks like this for a different format:
=DATEVALUE(SUBSTITUTE(A1,MID(A1,FIND(" ",A1)-2,2),""))

(link to that question)
How can I use above formula (or something similar) so that text is converted to date?
Thanks in advance.

A: =DATEVALUE(JOIN("/", LEFT(D5,2), {MID(D5,4,2), RIGHT(D5,4)}))

where D5 contains for example: 25.06.2019
which script converts to datevalue: 43641
Dateformat is as dd.MM.YYYY converted to dd/MM/YYYY and then converted to datevalue.
Google sheet's documentation helps:
DATEVALUE, JOIN, LEFT, MID, RIGHT
Datevalue is useful for organizing rows of data by date correctly.

A: Another solution is to create custom function.

*

*Open tools → script editor in menu to open script editor in new tab

*Click Untitled project in top left corner and rename

*Open Resources → Libraries in top menu

*Paste library key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click Add to add the Moment library to your script

*Choose Moment version 9 and click Save

*Paste function

function parseDate(dateString, format){
  return Moment.moment(dateString, format).toDate()
}

to Code.gs and save project Ctrl+S
Now you use your function in any cell in your sheet:
=parseDate(B2,"MMM D, YYYY, at HH:mm A")

more details about format:
https://momentjs.com/docs/#/parsing/string-formats/
You can also create function to display date in custom format:
function formatDate(date, format){
  return Moment.moment(date).format(format)
}

Use it like this in cell
=formatDate(B5,"DD/MM/YYYY")

or
=formatDate(parseDate(B2,"MMM D, YYYY, at HH:mm A"),"DD/MM/YYYY")

A: The , at portion of the string is keeping Google Sheets from recognizing it as a datevalue. Just remove it with the substitute function and wrap in datevalue function like so: =DATEVALUE(SUBSTITUTE(A1,", at",""))
To format as DD/MM/YYYY just go to custom formatting and set it to look like the following:


text:
Q: C++ template parameter default function implementation I have a set of classes that are used as parameters to templates.
They all conform to some informal interface ( a.k.a. a concept )
template <typename T>
int func( T& t ) { return t.a() + t.b() + t.c(); }

In this example, le'ts say I instantiate templates with Foo or Bar as parameters, so they must implement methods a b and c.
struct Foo { int a(); int b(); int c(); };
struct Bar { int a(); int b(); int c(); };

Now, I have a lot of these classes, and I would like to have a default implementation of one of the functions in terms of the others.
For example, I want c to return the difference between a() and b() by default. So I wish that it would be enough that I define a() and b() and c() would automatically implemented as int c() { return a()- b();} without having to copy this code for all classes.
I used to achieve this result with polymorphism ( by defining a() and b() as pure virtual functions in a base class with a default (virtual) implementation of c() ), but I moved away from this mechanism for performance reasons.
I would like to know if there is a recommended solution to attain this kind of result (i.e. write the default implementation once) with my template parameter classes.

A: I would be tempted to steal a page from std::begin.
CRTP is great, but it requires every structure modify itself to handle your requirement of having a c.  And really, the code for c is your problem, not the problem of the data you are being fed.
Naturally you'll want zero-overhead, which both CRTP and this approach pulls off.
So instead, we conditionally call .c() or we call .a()+.b() depending on its existence.  Here are two approaches:
Create a free function c:
template<class T, class...Ignored>
decltype(auto) c(T& t, Ignored&&...)

It dispatches to two implementations:
{
  auto which = has_c_method<T>;
  return details::c(which{}, t);
}

Where has_c_method is a traits bool type that detects if the type passed has a .c() method.  (I write one below).
In namespace details:
namespace details{
  template<class T>
  auto c(std::false_type, T&){
    return t.a()-t.b();
  }
  template<class T>
  auto c(std::true_type, T&){
    return t.c();
  }
}

and we are good.  Also note that if there is a free non-variadic function c(t) in ts namespace, it will be preferred (that is what Ignored does).
You do have to write that traits class, but many SO answers cover that.
A better name than c is advised.   ;)
This design has the advantage of not forcing people writing your target types to get in on the action.  You simply access either t.c() or t.a()+t.b() depending on if t.c() is defined.

Now we could approach this from an even more generic direction.  We don't create a c function that dispatches for us, instead...
We write a compile-time branch:
namespace details {
  template<bool>
  struct branch {
    template<class T, class F_true, class F_false>
    std::result_of_t<F_true(T)> operator()( T&&t, F_true&&f, F_false&&){
      return decltype(f)(f)(decltype(t)(t));
    }
  };
  template<>
  struct branch<false> {
    template<class T, class F_true, class F_false>
    std::result_of_t<F_false(T)> branch( T&& t, F_true&&, F_false&&f){
      return decltype(f)(f)(decltype(t)(t));
    }
  };
}
template<template<class...>class Z, class T, class F_true, class F_false>
auto branch( T&& t, F_true&& f_true, F_false&& f_false )
-> decltype( details::branch<Z<T>{}>{}(std::declval<T>(), std::declval<F_true>(), std::declval<F_false>() )
{
  return details::branch<Z<T>{}>{}(decltype(t)(t), decltype(f_true)(f_true), decltype(f_false)(f_false) );
}

no false case:
template<template<class...>class Z, class T, class F_true>
void branch( T&& t, F_true&& f_true )
{
  branch( std::forward<T>(t), std::forward<F_true>(f_true), [](auto&&){} );
}

use:
int c = branch<has_c_method>(
  t,
  [&](auto& t){ return t.c(); },
  [&](auto& t){ return t.a()-t.b(); }
);

which lets you do this a bit more ad-hoc.
branch<template>( arg, if_true, if_false ) evaluates template on the type (including r/l value qualification of) arg.  If an instance of the type resulting returns true within a constexpr context, if_true is run.  If it returns false within a constexpr contest, if_false is run.
In both cases, the arg is passed to the selected lambda.
Together with auto lambda support from C++14, this lets you write code that is conditionally compiled with relative brevity.
The unrun lambda is just an uninstantiated template.  The run lambda is instantiated with an instance of arg.  So the unrun lambda need not contain valid code for the case where it isn't selected.
The type of the branch is actually statically selected between the two options; they can actually return different types.  No conversion is done.
The if_false-less overload of branch returns void, as I am lazy and I don't see much use.

Here is a sketch of has_c_method written with mostly generic code.
namespace details {
  template<template<class...>class Z, class, class...Ts>
  struct can_apply_helper:
    std::false_type
  {};
  template<template<class...>class Z, class...Ts>
  struct can_apply_helper<Z, std::void_t<Z<Ts...>>, Ts...>:
    std::true_type
  {};
}
// is true_type iff Z<Ts...> is valid:
template<template<class...>class Z, class...Ts>
using can_apply = typename details::can_apply_helper<Z, void, Ts...>::type;

// return type of t.c(args...).  Easy to write
// and with the above, makes has_c_method a one-liner:
template<class T, class...Args>
using c_method_result = decltype(std::declval<T>().c(std::declval<Args>()...));

template<class T, class...Args>
using has_c_method = can_apply<c_method_result, T, Args...>;

there is a proposal to add something very much like can_apply to std.

Note my non-idiomatic use of decltype(x)(x) above.  This is equivalent to std::forward<X>(x) in a context where X is a forwarding reference, and also works within auto&& parameter lambdas.  It means "cast x to the type it was declared with".  Note that if x is a value (non-reference) type, it will duplicate it (which is a reason to prefer forward, which never does that): this, however, is not the case in any of my above decltype(x)(x) uses.

A: What about using CRTP to provide the default implementation to classes that inherit from it:
template <typename Child>
class DefaultC
{
public:
    int c() { Child& this_obj = static_cast<Child&>(*this); return this_obj.a()- this_obj.b();}
};

Then:
struct Foo : public DefaultC<Foo> { int a(); int b(); };

(and as a note if your functions are non-mutating please mark them const)

A: I would first try CRTP:
template < typename Derived >
struct subtract
{
    int c() const
    {
        auto this_ = static_cast<Derived const*>(this);
        return this_->a() - this_->b();
    }
};

struct whatnot : subtract<whatnot>
{
    int a() const { return 42; }
    int b() const { return 666; }
};

A: A version, inspired by Kerrek's one on comments, but using std::true_type and std::false_type
#include <iostream>
#include <type_traits>

struct Foo {
    int a() { return 10; }
    int b() { return 20; }
    int c() { return 30; }
};

struct Bar {
    int a() { return 8; }
    int b() { return 3; }
};

template<typename T, typename = void>
struct has_c : std::false_type {
    static int call(T t) { return t.a() - t.b(); }
};

template<typename T>
struct has_c<T, decltype(std::declval<T>().c(), void())> : std::true_type {
    static int call(T t) { return t.c(); }
};

template <typename T>
int f(T&& t) {
    return has_c<T>::call(std::forward<T>(t));
}

int main()
{
    Foo foo;
    Bar bar;

    std::cout << f(foo) << "\n";
    std::cout << f(bar) << "\n";

    return 0;
}

Live on Coliru


text:
Q: How to encircle a character inside a Latex formula? I would like to encircle one character inside a LaTeX formula. An example is

$f_1 = ...$ or $f_k = ...$,

where I want to encircle the characters 1 and k. I've found some questions (question 1, question 2) about how to encircle one character or an entire (small) formula. But how should I encircle only one character of a LaTeX formula? Is there an easy solution such as

$f_\encircled{1} = ...$

(my preference), should I use symbols such as from the \ding library, or use TikZ?

A: I would use TikZ to achieve this. Here's some rough sample code that is similar to what is used in the answers to question 1 and question 2 that you mentioned:
\documentclass{article}
\usepackage{tikz}

\newif\ifstartedinmathmode
\newcommand\encircled[1]{%
  \relax\ifmmode\startedinmathmodetrue\else\startedinmathmodefalse\fi%
  \tikz[baseline,anchor=base]{%
  \node[draw,circle,outer sep=0pt,inner sep=.2ex]
    {\ifstartedinmathmode$#1$\else#1\fi};}%
}

\begin{document}

\encircled{Text} outside math. \encircled{$n=1$} formula.
Or $\encircled{n}$ like this.
\[ f_{\encircled{n}} = \encircled{f_n} \]

\end{document}

For convenience, I've added code to automatically switch to math mode if needed. This is based on question 3.

A: Slight improvement of ThV's answer, in order to preserve the proper math style.
\documentclass{article}

\usepackage{tikz}

\makeatletter
\newcommand*{\encircled}[1]{\relax\ifmmode\mathpalette\@encircled@math{#1}\else\@encircled{#1}\fi}
\newcommand*{\@encircled@math}[2]{\@encircled{$\m@th#1#2$}}
\newcommand*{\@encircled}[1]{%
  \tikz[baseline,anchor=base]{\node[draw,circle,outer sep=0pt,inner sep=.2ex] {#1};}}
\makeatother

\begin{document}

\encircled{Text} outside math. $\encircled{n=1}$ formula.
\[
f_{\encircled{n}} = \encircled{f_n}
\]

\end{document}


text:
Q: How to close parent window in an Apps Script Web App? I have a web app in Google Apps Script and I need that when I have click in a Button, the browser tab closes. I tried with different solutions but it does not work as I require it.
This is my HTML code.
<!DOCTYPE html>

    <base target="_top">

Demo Close tab

When you click the button, you must close this tab.

    <button>Close</button>

And this is my GS code
function doGet() {
  var template = HtmlService.createTemplateFromFile("Index");

  return template.evaluate()
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .addMetaTag("viewport", "width=device-width, initial-scale=1")
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
  .setTitle("Demo Google Analytics");
}

A: As stated in the docs HTML Service: Restrictions:

The setSandboxMode method now has no effect when called.

Your Google Apps Script runs in an iframe by default, regardless of any attempts to change the sandbox mode. I strongly suspect the sandbox settings will prevent you accessing the parent window, but you might try window.parent.window.

A: According to Javascript Documention: Window.close()

This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, an error similar to this one appears in the console: Scripts may not close windows that were not opened by script.

A: Web Apps are usually standalone script projects that, as per the documentation on restrictions applied in the IFRAME sandbox mode (which is, as of 2021, the only mode available), has the following sandbox flags (corresponding to the sandbox attribute) set on the HTMLIFrameElement Web Apps are served in:

Flag

allow-same-origin

allow-forms

allow-scripts

allow-popups

allow-downloads

allow-modals

allow-popups-to-escape-sandbox

allow-top-navigation-by-user-activation

Note the last flag - this is the reason for being able to initiate navigation when a user clicks on an element but not when calling methods like window.top.close(), window.location.reload(), or window.location.replace(<url>).

This seemed to not be strictly enforced for bound script projects up until September 2021, but it is now. As of now, there are several open issues on the Issue Tracker reporting that the auto-closing Web App windows stopped working - please follow them if you want to get updates on whether or not Google will reconsider enforcing the flag:

*

*https://issuetracker.google.com/issues/198071205

*https://issuetracker.google.com/issues/198323022

*https://issuetracker.google.com/issues/198073648 (status "Won't fix" but open for a feature-request)


text:
Q: Android Junit - "Class not found" For my Android project I'd like to test pure Java code. To achieve this, I want to use JUnit.
Due to known bug:
!!! JUnit version 3.8 or later expected:
java.lang.RuntimeException: Stub!
    at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
    at junit.textui.TestRunner.<init>(TestRunner.java:54)
    at junit.textui.TestRunner.<init>(TestRunner.java:48)
    at junit.textui.TestRunner.<init>(TestRunner.java:41)
    at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:190)
    at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:173)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

I installed proper plugin to Android Studio and added:
classpath 'com.github.jcandksolutions.gradle:android-unit-test:2.1.1'

and in app build.gradle
apply plugin: 'android-unit-test'

dependencies {
    testCompile('junit:junit:4.11')
}

As JUnit was added I wrote simple test class in src/androidTest/java/com.adamstyrc.mytrack.unit:
package com.adamstyrc.mytrack.unit;

import junit.framework.TestCase;

public class SimpleTest extends TestCase {

    public void testName() {
        assertEquals(7, 6);
    }
}

But what I get is:
Class not found: "com.adamstyrc.mytrack.unit.SimpleTest"

Why is it not visible ?

A: OK, as https://github.com/JCAndKSolutions/android-unit-test says the path has to be:

src/test/...

instead of src/androidTest/
and nothing like:
sourceSets {
    androidTest {
        setRoot('src/androidTest')
    }
}

can change it.


text:
Q: Hibernate Table Per Sub Class Mapping I want to know, that if we have two class :

1) Employee.java

2) PermanentEmployee.java

Now, I want to know:

1. if there exists a record with `id = 1` in Employee table.
2. id generator used in increment.
3. There is no record in PermanentEmployee table.
4. Is it possible to insert a record with id 1 in PermanentEmployee table

ie if we save record of `permanentEmployee`, than a new record should get insert in `permannentEmployee` table and it should refer to already existing record in Employee table ?

Any pointers will be of great help

More Description :

Employee.java
----------------------------
package com.kar.hibernate;

public class Employee {

    private int eid;
    private String ename;
    private String ecity;
    private String eemail;
    private Long ephone;
    public Employee() {
        super();
    }
    public Employee(String ename, String ecity, String eemail, Long ephone) {
        super();
        this.ename = ename;
        this.ecity = ecity;
        this.eemail = eemail;
        this.ephone = ephone;
    }
    public int getEid() {
        return eid;
    }
    public void setEid(int eid) {
        this.eid = eid;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getEcity() {
        return ecity;
    }
    public void setEcity(String ecity) {
        this.ecity = ecity;
    }
    public String getEemail() {
        return eemail;
    }
    public void setEemail(String eemail) {
        this.eemail = eemail;
    }
    public Long getEphone() {
        return ephone;
    }
    public void setEphone(Long ephone) {
        this.ephone = ephone;
    }
    @Override
    public String toString() {
        return "Employee [eid=" + eid + ", ename=" + ename + ", ecity=" + ecity
                + ", eemail=" + eemail + ", ephone=" + ephone + "]";
    }

}
-----------------------------------------------
OldEmployee.java
-----------------------------------------------
package com.kar.hibernate;

public class OldEmployee extends Employee{

    private String oeDateOfRelease;
    private int oeDurationInCompany;

    public OldEmployee() {
    }

    public OldEmployee(String ename, String ecity, String eemail, Long ephone
            ,String oeDateOfRelease, int oeDurationInCompany) {
        super(ename, ecity, eemail, ephone);
        this.oeDateOfRelease=oeDateOfRelease;
        this.oeDurationInCompany=oeDurationInCompany;
    }

    public String getOeDateOfRelease() {
        return oeDateOfRelease;
    }

    public void setOeDateOfRelease(String oeDateOfRelease) {
        this.oeDateOfRelease = oeDateOfRelease;
    }

    public int getOeDurationInCompany() {
        return oeDurationInCompany;
    }

    public void setOeDurationInCompany(int oeDurationInCompany) {
        this.oeDurationInCompany = oeDurationInCompany;
    }

    @Override
    public String toString() {
        return super.toString()+":::::"+ "OldEmployee [oeDateOfRelease=" + oeDateOfRelease
                + ", oeDurationInCompany=" + oeDurationInCompany + "]";
    }

}
=================================================
Client1.java
=================================================
package com.kar.hibernate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

public class Client1 {
    public static void main(String[] args) {
        Transaction tx=null;
        try
        {
            SessionFactory sessionFactory=CHibernateUtil.getSessionFactory();
            Session session=sessionFactory.openSession();
            tx=session.beginTransaction();

            String ename="anuj";
            String ecity="blore";
            String eemail="a@a";
            Long ephone=1111l;

            Employee e=new Employee(ename, ecity, eemail, ephone);
            session.save(e);

            tx.commit();
            session.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            if(tx!=null)
                tx.rollback();
        }
    }
}

===================================================================
Client2.java
==========================================
package com.kar.hibernate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.event.SaveOrUpdateEvent;

public class Client2{
    public static void main(String[] args) {
        Transaction tx=null;
        try
        {
            SessionFactory sessionFactory=CHibernateUtil.getSessionFactory();
            Session session=sessionFactory.openSession();
            tx=session.beginTransaction();

            Employee e=(Employee)session.load(Employee.class, 1);

            OldEmployee oe=new OldEmployee(e.getEname(),
                    e.getEcity(), e.getEemail(),
e.getEphone(), "1/1/2014", 2);

            session.saveOrUpdate(oe);

            tx.commit();
            session.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            if(tx!=null)
                tx.rollback();
        }
    }
}

-------------------------------------------------------------------
Employee.hbm.xml
---------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.kar.hibernate">

<class name="Employee" table="employee">
<id name="eid" column="eid" type="int">
<generator class="increment"/>
</id>
<property name="ename" column="ename" type="string"/>
<property name="ecity" column="ecity" type="string"/>
<property name="eemail" column="email"/>
<property name="ephone"/>

<joined-subclass name="OldEmployee" table="oldEmployee">
<key column="eid"></key>
<property name="oeDateOfRelease"></property>
<property name="oeDurationInCompany"></property>
</joined-subclass>

</class>
</hibernate-mapping>

====================================================================
Hibernate.cfg.xml
===================================================================
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/chm</property>
            <property name="hibernate.connection.username">root</property>
                <property name="hibernate.connection.password">root</property>

          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
     <property name="show_sql">true</property>
    <mapping resource="com/kar/hibernate/Employee.hbm.xml"/>

        </session-factory>
</hibernate-configuration>

=======================================================================================
============
    //Now my question is what to edit in Client2, So that when we try to save OldEmployee than
    a new record should not get insert in Employee table. but a new record of OldEmployee table should refer to already existing record of Employee Table ?
Any pointers will be of great help.

A: Inheritance table per subclass is your case, hibernate documentation.
Your problem, could not be solved like you imagine it. First that can't be done either java or hibernate on regular way. So your options are;

*

*delete original Employee and insert new OldEmployee object

*manually insert old employee object.
session.createSQLQuery("insert into oldEmployee values (employeeId, ....)")
As you can see both solutions are workaround, maybe it would be smarter to recheck your inheritance or even business model.


text:
Q: why changes to layout application.html.erb view does not show on new Rails 6 app Upon scaffolding a new Rails 6 app, I see the Yay! You're on Rails! page. When making changes to application.html.erb, I'm not seeing the changes being reflected. I was wondering how to fix this.

A: Because that is a static page.
What happens is that the yay you're in rails is a static page that is located on the rails gem, you can check that by looking through the logs of your server, mine for example is located here /Users/jean/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.2/lib/rails/templates/rails/welcome/index.html.erb

In order to override you need to create a default root page in your routes.rb with the respective controller and view. That will use your application.html.erb as the default template.
For example you can create a home controller
rails g controller Home index

That will generate a bunch of files including the view file and the controller file, now you have to go to your routes, remove the route generated and add this:
root 'home#index'

Now if you start the server again you will be able to see the correct layout (application.html.erb) that you changed plus the content of the newly generated index.html.erb located in app/views/home.


text:
Q: AzSK ARM Checker Task are not giving scanning results for Virtual Machine ARM Template Am working on ARM Templates,Azure DevOps CI & CD and Secure DevOps Kit for Azure(AzSK). In my organisation, I created a build pipeline for scanning Virtual Machine ARM Template with the help of AzSK ARM Template Checker. Here, am facing some issue like "after the build triggered, at the time of scanning "Its skipping the checking Virtual Machine ARM Template and giving No controls have been evaluated for file" output through Excel File,logs. Can you please suggest me to "How to overcome this issue?"
I followed the link

Update-1

I think according to the document, there is no ARM Checker scanning for the Virtual Machine and it is for only few resource templates only. Is it true and got this point from the Link-1

A: I have the same problem as you.
So if I'am correct and you click on the "ARM template for reference are available here" you can see the resources of arm templates that will be checked and there you can see virtual machine in the list.
But like my problem for the keyvault it still gives the same error. probably because the apiVersion is not updated.
I hope you find a solution for your problem and you are willingly to share it.


text:
Q: Restore Database in WAMP I had few databases related to different projects in the WAMP. I don't know what happened, Today, when I go to PhpMyAdmin, I was just able to see the default databases and rest of my databases are not showing and even the php code related to those databases are throwing database not found errors. But when I go to "D:\wamp\bin\mysql\mysql5.1.30\data" the folders with my DB names are there. But not sure how to restore those DBs and I don't have any backup of the DB, Can any one help me how to restore them?

A: You can copy these file to another location and reinstall the same WAMP version after installtation copy them back to original location.
Please note that your WAMP version should be same, because if the version will change then mysql version will also be change.

A: Another method is to utilise Window's "Restore previous versions" feature. Right click the wamp folder (usually in C:\, click Restore previous versions and select the most recent date you know it was working.
Note: This will also revert mysql data - so you'll lose any changes after the date you select, but I have used this in the past when I needed to get my whole wamp system back to a working state when something had broken it.

A: Have you checked my.ini file? Just find datadir it should refer to db folder (e.g datadir=D:/Wamp/bin/mysql/mysql5.1.30/data) - goodluck :)

A: Copy the complete data folder from old wamp mysql folder to new mysql folder and then inside data folder change the name of the file mysql-bin.index to mysql-bin.index-corrupt. Then restart WAMP. That's all.

A: reinstall Wamp Server that must be same version. After reinstall if wamp show red icon 1. go to wamp -> apache -> services ->test port 80.
if its available . then apache -> services -> install services.
2. mysql-> services -> install services.
after that restart wamp..
100% work

A: Copy data folder and reinstall same version of WAMP.
Once installation is completed, go to data folder: inside replace only ibdata1 file from existing folder.
After starting WAMP, check phpmyadmin: you'll get all database and tables with data.


text:
Q: Why do my WinForms controls flicker and resize slowly? I'm making a program where I have a lot of panels and panels in panels.
I have a few custom drawn controls in these panels.
The resize function of 1 panel contains code to adjust the size and position of all controls in that panel.
Now as soon as I resize the program, the resize of this panel gets actived. This results in a lot of flickering of the components in this panel.
All user drawn controls are double buffered.
Can some one help me solve this problem?

A: I successfully eliminate flicker when form resize using this code. Thanks.
VB.NET
Public Class Form1

Public Sub New()
    Me.SetStyle(ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint Or ControlStyles.SupportsTransparentBackColor, True)
End Sub

Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
    Me.Update()
End Sub

End Class

C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Resize += Form1_Resize;
        this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
    }

    private void Form1_Resize(object sender, System.EventArgs e)
    {
        this.Update();
    }

}

A: So I ran into this same problem - my control with a transparent background was repainting like 34 times, and what worked for me was:
On my form that contained the control
protected override void OnResize(EventArgs e)
    {
        myControl.Visible = false;
        base.OnResize(e);
        myControl.Visible = true;
    }

And the same in the control:
protected override void OnResize(EventArgs e)
    {
        this.Visible = false;
        base.OnResize(e);
        this.Visible = true;
    }

This reduced the amount of repainting to 4, which effectively eliminated any flicker when the control was being resized.

A: To get rid of the flicker while resizing the win form, suspend the layout while resizing. Override the forms resizebegin/resizeend methods as below.
protected override void OnResizeBegin(EventArgs e) {
    SuspendLayout();
    base.OnResizeBegin(e);
}
protected override void OnResizeEnd(EventArgs e) {
    ResumeLayout();
    base.OnResizeEnd(e);
}

This will leave the controls intact (as they where before resizing) and force a redraw when the resize operation is completed.

A: Looking at the project you posted, the flickering is really bad when you have the first tab selected, with the gradient-filled group boxes. With the second or third tab showing, there's hardly any flicker, if at all.

So clearly the problem has something to do with the controls you're showing on that tab page. A quick glance at the code for the custom gradient-filled group box class gives away the more specific cause. You're doing a lot of really expensive processing each time you draw one of the groupbox controls. Because each groupbox control has to repaint itself each time the form is resized, that code is getting executed an unbelievable number of times.
Plus, you have the controls' background set to "Transparent", which has to be faked in WinForms by asking the parent window to draw itself first inside the control window to produce the background pixels. The control then draws itself on top of that. This is also more work than filling the control's background with a solid color like SystemColors.Control, and it's causing you to see the form's pixels being drawn while you resize the form, before the groupboxes have a chance to paint themselves.
Here's the specific code I'm talking about from your custom gradient-filled groupbox control class:
protected override void OnPaint(PaintEventArgs e)
{
    if (Visible)
    {
        Graphics gr = e.Graphics;
        Rectangle clipRectangle = new Rectangle(new Point(0, 0), this.Size);
        Size tSize = TextRenderer.MeasureText(Text, this.Font);
        Rectangle r1 = new Rectangle(0, (tSize.Height / 2), Width - 2, Height - tSize.Height / 2 - 2);
        Rectangle r2 = new Rectangle(0, 0, Width, Height);
        Rectangle textRect = new Rectangle(6, 0, tSize.Width, tSize.Height);

        GraphicsPath gp = new GraphicsPath();
        gp.AddRectangle(r2);
        gp.AddRectangle(r1);
        gp.FillMode = FillMode.Alternate;

        gr.FillRectangle(new SolidBrush(Parent.BackColor), clipRectangle);

        LinearGradientBrush gradBrush;
        gradBrush = new LinearGradientBrush(clipRectangle, SystemColors.GradientInactiveCaption, SystemColors.InactiveCaptionText, LinearGradientMode.BackwardDiagonal);
        gr.FillPath(gradBrush, RoundedRectangle.Create(r1, 7));

        Pen borderPen = new Pen(BorderColor);
        gr.DrawPath(borderPen, RoundedRectangle.Create(r1, 7));
        gr.FillRectangle(gradBrush, textRect);
        gr.DrawRectangle(borderPen, textRect);
        gr.DrawString(Text, base.Font, new SolidBrush(ForeColor), 6, 0);
    }

}

protected override void OnPaintBackground(PaintEventArgs pevent)
{
    if (this.BackColor == Color.Transparent)
        base.OnPaintBackground(pevent);
}

And now that you've seen the code, red warning flags ought to go up. You're creating a bunch of GDI+ objects (brushes, pens, regions, etc.), but failing to Dispose any of them! Almost all of that code should be wrapped in using statements. That's just sloppy coding.
Doing all of that work costs something. When the computer is forced to devote so much time to rendering controls, other things lag behind. You see a flicker as it strains to keep up with the resize. It's no different than anything else that overloads a computer (like a computing the value of pi), it's just really easy to do so when you use as many custom drawn controls like you do here. Transparency is hard in Win32, and so is a lot of custom 3D painting. It makes the UI look and feel clunky to the user. Yet another reason that I don't understand the rush away from native controls.
You really only have three options:

*

*Deal with the flicker. (I agree, this is not a good option.)

*Use different controls, like the standard, built-in ones. Sure, they may not have a fancy gradient effect, but that's going to look broken half of the time anyway if the user has customized their Windows theme. It's also reasonably hard to read black text on a dark gray background.

*Change the painting code within your custom controls to do less work. You may be able to get by with some simple "optimizations" that don't cost you any of the visual effects, but I suspect this is unlikely. It's a tradeoff between speed and eye candy. Doing nothing is always faster.

A: Maybe a good solution for you will be to use Form.ResizeBegin and Form.ResizeEnd events.
On ResizeBegin set main panel visibility to false, on ResizeEnd set main panel visibility to true.
This way panels will not be redrawn while someone is resizing your form.

A: While hooking into ResizeBegin and ResizeEnd is the right idea, instead of hiding the main panel's visibility I'd instead delay any resize calculations until ResizeEnd. In this case, you don't even need to hook into ResizeBegin or Resize - all the logic goes into ResizeEnd.
I say this for two reasons. One, even though the panel is hidden, the resize operation will likely still be expensive and so the form won't feel as responsive as it should unless the resize calculations are delayed. Two, hiding the pane's contents while resizing can be jarring to the user.

A: I had the same problem.
It seams that this is happening because you are using rounded corners. When I set CornerRadius property to 0, the flickering was gone.
So far I have only found the following workaround. Not the nicest one, but it stops the flickering.
private void Form_ResizeBegin(object sender, EventArgs e)
{
  rectangleShape.CornerRadius = 0;
}

private void Form_ResizeEnd(object sender, EventArgs e)
{
  rectangleShape.CornerRadius = 15;
}

A: I Had A Similar Issue Like This. My Entire Form Was Resizing Slowly And The Controls Painted Them In An Ugly Manner. So This Helped Me:
//I Added This To The Designer File, You Can Still Change The WindowState In Designer View If You Want. This Helped Me Though.
this.WindowState = FormWindowState.Maximized;

And In The Resize Event, Add This Code To The Beginning
this.Refresh();


text:
Q: Reusing stages of a jenkins pipeline in multiple jobs My team is moving to Jenkins 2 and I am using the pipeline plugin so that our build can live in our repository.  Because getting repositories allocated has lots of overhead in our company we have a single respository with many sub-projects & sub-modules in it.
What I want is separate builds and reporting of Junit/checkstyle/etc reports for each sub-module as well as a final "build and deploy" step for each sub-project putting it all together.
My current plan is to create separate jobs for each sub-module so that they get their own junit/checkstyle/etc reports page.  Then have a multi-job project to orchestrate the sub-module builds for the sub-projects.  Since all of the sub-projects are simple jar builds, I want to put bulk of the logic in a common file, lets call it JenkinsfileForJars at the root of the sub-project.  So the repo structure is

*

*sub-project

*

*JenkinsfileForJars.groovy

*sub-moduleA

*

*Jenkinsfile

*sub-moduleB

*

*Jenkinsfile
My Jenkinsfile contains
def submoduleName = "submoduleA"
def pipeline
node {

    pipeline = load("${env.WORKSPACE}/subproject/JenkinsfileForJars.groovy")

}
pipeline.build()
pipeline.results()

And my JenkinsfileForJars contains
def build() {

    stage('Build') {
        // Run the maven build
        dir("subproject") {
            sh "./gradlew ${submoduleName}:build"
        }

    }
}
def results() {

    stage('Results') {
        dir("subproject/${submoduleName}") {
            junit 'build/test-results/TEST-*.xml'
            archive 'build/libs/*.jar'
            publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'build/reports/cobertura/', reportFiles: 'frame-summary.html', reportName: 'Cobertura Report'])
            publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'build/reports/findbugs/', reportFiles: 'main.html', reportName: 'Fidbugs Report'])
            publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'build/reports/pmd/', reportFiles: 'main.html', reportName: 'PMD Report'])
            step([$class: 'CheckStylePublisher', pattern: 'build/reports/checkstyle/main.xml', unstableTotalAll: '200', usePreviousBuildAsReference: true])
        }
    }

}

return this;

When I run the Jenkinsfile above I get the following error:
Running on master in /var/lib/jenkins/workspace/jobA
[Pipeline] {
[Pipeline] load
[Pipeline] { (/var/lib/jenkins/workspace/jobA/subproject/JenkinsfileForJars.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NullPointerException: Cannot invoke method build() on null object

As far as I can tell, I am following what is shown in the documents for loading manual scripts and the example given for a loaded script.  I do not understand why my script is null after the load command.
How do I get my Jenkinsfile to load JenkinsfileForJars.groovy?

A: The problem is related to the SCM checkout as mentioned by Blake Mitchell in the comment above.
Since you are loading your groovy functions from a submodule, you will need to checkout the submodule first, preferably on a build agent /slave, if you would like to keep only bare repos on the master.
def pipeline
node( 'myAgentLabel' ) {
    stage ( 'checkout SCM' ) {
        checkout([
            $class: 'GitSCM'
            ,branches: scm.branches
            ,extensions: scm.extensions
                + [[ $class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: false]]
            ,doGenerateSubmoduleConfigurations: false
            ,userRemoteConfigs: scm.userRemoteConfigs
        ])
        pipeline = load( "${env.WORKSPACE}/path/to/submodule/myGroovyFunctions.grooovy" )
    }
    pipeline.build()
}

Note that in the checkout example, access to scm.* attributes also needs to be whitelisted by an administrator in Jenkins (In-process script approval)

A: There might be two possible problems:

*

*Why do you put the load in a node structure. This import does not need computational resources, so you do not need it there.

*The call to build should be put inside a node structure. And probably the call to result should also be inside (the same) node structure to make sure, that the correct results are archived (if you use more than one (slave) nodes).

(This should probably be a comment below your question but I do not have enough points to add a comment there.)


text: Q: ¿Cómo puedo mantener mi toggle en la misma posición que lo coloque aunque pase a otro apartado? tengo mi pagina que tiene dos modos, uno claro y otro oscuro que se activan por medio de la posición de toggle, intentándolo logre que se guardara solo un thema y así se queda, en pocas palabras, antes de modificarlo el modo inicial era el modo claro, ahora el modo principal es el oscuro, alguien sabe porque?


text:
Q: Shortcut for subscript in PowerPoint Is there a keyboard shortcut to format as subscript in PowerPoint 2011?  Most sources point to command-= but this zooms out.  Is there a way to customize these shortcuts, or more importantly to discover them without spending a lot of time googling?

A: To see your system keyboard shortcuts go to:
System Preference >Keyboard >Shortcuts
To apply subscript formatting (automatic spacing) in PowerPoint 2011
⌘+SHIFT+MINUS SIGN
To see all PowerPoint shortcuts go here


text:
Q: How to tell if Kubuntu is hibernating or not? My Kubuntu 22.04 on a Macbook Air takes a lot to wake up from sleep, which makes me think it's maybe hibernating in fact.
This is happening even if the lid is closed for a few seconds.
It takes up to 10-15 seconds to wake up.
Only Escape key seems to work for this purpose.
In the Plasma settings the default is sleep/suspend when lid is closed, and there is no hibernation option:

I have read here (Does linux have a hybrid "deep sleep" mode like the Mac?) that Ubuntu above 18.04 has this feature, but here it says that the feature is not enabled by default but needs editing the file /etc/systemd/sleep.conf. On my system that file has all options commented out:
[Sleep]
#AllowSuspend=yes
#AllowHibernation=yes
#AllowSuspendThenHibernate=yes
#AllowHybridSleep=yes
#SuspendMode=
#SuspendState=mem standby freeze
#HibernateMode=platform shutdown
#HibernateState=disk
#HybridSleepMode=suspend platform shutdown
#HybridSleepState=disk
#HibernateDelaySec=180min

How can I tell what is happening and what are the settings on my system?
I want to know whether this behavior is due to hibernation being active by default (by some Kubuntu setting or by deeper Macbook boot settings) or to some odd problem with the OS taking a lot of time to wake up from suspend.

A: Based on the comment by @Esther -- running journalctl -b, I see lines like kernel: PM: hibernation: Registered nosave memory: [mem 0x00000000-0x00000fff]. So, it's hibernation, it seems.
On the other hand, after running sudo systemctl suspend-then-hibernate in order to just test if that worked, what happened was a sort of sleep from which the laptop woke quickly.
But afterwards all that I describe in the anser stopped happening. Now the laptop is just entering normal sleep (it wakes up almost instantly when I open the lid). Maybe some default file was now re-written, reset, or set to defaults.
Anyway, now the solutions in the links posted in my question can be used (activating "suspend then hibernate" and setting the delay before hibernation.)