text:
Q: Present the same `GameScene` again In some tutorial on a paid website I learned that you can replay the game by simply presenting the same scene again but I have no access to that tutorial anymore so I am not sure what I am doing wrong. If I remember correctly, the tutorial used something like this (in GameScene class):
func newGame() {
    let newScene = GameScene()
    let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
        view?.presentScene(newScene, transition: transition)
    view?.presentScene(newScene, transition: transition)
}

GameViewController.swift:
override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    if let skView = self.view as? SKView {
        if skView.scene == nil { //if the scene hasn't been created yet
            let aspectRatio = skView.bounds.size.height / skView.bounds.size.width
            let scene = GameScene(size: CGSize(width: 320, height: 320 * aspectRatio))

            //skView.showsFPS = true
            //skView.showsNodeCount = true
            //skView.showsPhysics = true
            skView.ignoresSiblingOrder = true

            scene.scaleMode = .AspectFill
            skView.presentScene(scene)
        }
    }
}

The problem is this gives me the following error:
libc++abi.dylib: terminating with uncaught exception of type NSException

If I add some breakpoints it seems that the problem is with my GameScene. That's first few lines of it:
class GameScene: SKScene, SKPhysicsContactDelegate {
    var player: Player!
    var world: SKNode!

The first and second line are causing an fatal error (I think) but am not sure why. Should I remove all the children from the scene before presenting that same scene again? With that tutorial we just presented the same scene in a few lines and it worked.
UPDATE:
class GameScene: SKScene, SKPhysicsContactDelegate {
    var player: Player!
    var world: SKNode!

    override func didMoveToView(view: SKView) {
        self.physicsWorld.contactDelegate = self
        player = Player(position: CGPointMake(size.width*0.5, size.height*0.4))
        world.addChild(player)
    }
}

Because the GameScene class is quite long, I added just the part which I think is problematic but don't know why or what I should change.

A: Change this:
func newGame() {
    let newScene = GameScene()
    let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
        view?.presentScene(newScene, transition: transition)
    view?.presentScene(newScene, transition: transition)
}

To this:
func newGame() {
    let newScene = GameScene(size: CGSize(width: 768, height: 1024))
    let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
        view?.presentScene(newScene, transition: transition)
    view?.presentScene(newScene, transition: transition)
}

Also with regards to your gameViewController, you don't need to make the size of the skView using the aspect ratio. Since you're using AspectFill as your scaleMode the scene automatically scales it. With this, you would then make the screen size 768x1024 (portrait) or 1024x768 (landscape). To make this compatible with all devices simply make the background 1024x1024 so it looks fine on iPad and you can adjust HUD elements for iPad only by doing something like this:
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
    yourButton.position.y += 100
    yourLabel.position.y += 100
    etc
 }


text:
Q: Rust Cargo CMake Integration with C++ Library Dependencies Let us say that I have Rust project that wants to use a CMake based C++
library. For that, I use a build.rs script something like below that uses the
cmake and cxx packages to build an external project (spikes):
let path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let external = path.join("external");
let spikes = external.join("spikes");
if spikes.exists()
{
    println!("cargo:rustc-cfg=spikes");
    let ccl_includes = spikes.join("src");
    let dst = cmake::Config::new(spikes).build();
    let lib = "spikes_common";
    println!("cargo:rustc-link-search=native={}/lib/spikes", dst.display());
    println!("cargo:rustc-link-lib=static={}", lib);

    // Attempt to build the C++-bridge.
    cxx_build::bridge("src/imageio_cxx.rs")
        .file("external/imageio-bridge.cpp")
        .include(spikes_includes)
        .flag_if_supported("-std=c++17")
        .compile("libimageio-bridge");
    println!("cargo:rerun-if-changed=external/imageio-bridge.h");
    println!("cargo:rerun-if-changed=external/imageio-bridge.cpp");
}

This works fine for the most part, but I can't seem to find any documentation on
how to handle link dependencies from the C++ project. E.g., in the above example
the C++ library uses OpenEXR, but naturally, the linker flags are not
propagated to the Rust project, making it fail during the compilation linking
step. What is the current best practice for propagating linker flags from a C++
project to Cargo?

A: So based on what I've read about this cargo crate I can forsee 3 options:

*

*You scrape the cmake files for the appropriate flags construct a string slice and pass it to the bridge

*You manually type them out

*Or this hackish solution: via pkg-config if applicable pkg-config just pastes out what you specify to paste out.

If you go with option 3 you have then two options on how to get it in

*

*I don't see under the hood of cxx.rs, but perhaps you could pass it to the flags_if_possible - I've done similar hacks before in qmake.

*You could just execute the command, grab the output and create a string slice that you input into the same method.

Hope it helps!
EDIT: If there is a cmake file then IIRC cmake has a feature to generate pkg-config files from its targets.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detecting Excel column data types in Python Pandas New to Python and Pandas here. I am trying to read an Excel file off of S3 (using boto3) and read the headers (first row of the spreadsheet) and determine what data type each header is, if this is possible to do. If it is, I need a map of key-value pairs where each key is the header name and value is its data type. So for example if the file I fetch from S3 has the following data in it:
Date,Name,Balance
02/01/2022,Jerry Jingleheimer,45.07
02/14/2022,Jane Jingleheimer,102.29

Then I would be looking for a map of KV pairs like so:

*

*Key 1: "Date", Value 1: "datetime" (or whatever is the appropriate date type)

*Key 2: "Name", Value 2: "string" (or whatever is the appropriate date type)

*Key 3: "Balance", Value 3: "numeric" (or whatever is the appropriate date type)

So far I have:
s3Client = Res.resource('s3')
obj = s3Client.get_object(Bucket="some-bucket", Key="some-key")
file_headers = pd.read_excel(io.BytesIO(obj['Body'].read()), engine="openpyxl").columns.tolist()

I'm just not sure about how to go about extracting the data types that Pandas has detected or how to generate the map.
Can anyone point me in the right direction please?

A: IIUC, you can use dtypes:
>>> df.dtypes.to_dict()
{'Date': dtype('<M8[ns]'), 'Name': dtype('O'), 'Balance': dtype('float64')}

>>> {k: v.name for k, v in df.dtypes.to_dict().items()}
{'Date': 'datetime64[ns]', 'Name': 'object', 'Balance': 'float64'}

A: I suggest you to check this pandas tutorial.
The pandas.read_excel('my_file.xlsx').dtypes should give you the types of the columns.


text:
Q: remove specifying the full path in sudoers I am trying to add a NOPASSWD entry for 'sudotest.sh' (or any script/binary that requires sudo) in my /etc/sudoers file (redhat) but in order to make it work, I must specify the full path. The following entry works just fine:
%jenkins ALL=(ALL)NOPASSWD:/home/vts_share/test/sudotest.sh The problem is that the script might move to a different directory. I tried as giving /home/*/sudotest.sh but didn't work for me when I tried to execute sudo ./sudotest.sh,it gave me you dont have root permission
Note:I can't have permission to /bin/sh directory too.

A: I don't think it's a good idea to do what you are trying to do. "The problem is that the script might move to a different directory." Ask you the question of who is going to move it. Suppose that a malicious user create a sudotest.sh somewhere in the path. Then it will be this malicious file which get executed with root access. So my answer is Don't do it !


text:
Q: Codesign and Ambiguos identity, matches "Mac Developer" and "iPhone Developer" I'm in the process of release testing a library. The process requires testing on a Jail Broken iOS device. For that, I use an old iPad 1 running iOS 5.1 jail broken with RedSn0w.
RedSn0w does not patch the Gatekeeper service (code signing), so I need to use my developer account and sign the binary I am testing (Absinthe does patch Gatekeeper, and its why you can use ldid to generate phony signatures).
Attempting to sign results in:
$ codesign -s "John Doe" cryptest.exe
John Doe: ambiguous (matches "Mac Developer: John Doe (3VT8SJ9C5)" and "iPhone Developer:
John Doe (3VT8SJ9C5)" in /Users/jdoe/Library/Keychains/login.keychain)

I made a pass through codesign(1), but I don't how to resolve it since they are the same KeyIDs. Using a KeyID produces the same message.
How do I remove the ambiguity when signing the executable?

A: If you have multiple (conflicted) certificate names, you can create a new keychain and import the desired certificate into it.  The "Keychains" list in "Keychain Access" is a sortable list. Therefore be sure your new keychain is at the top of the list.
Then add --keychain <path to new keychain file> to your codesign command line.
The path is typically /Users/<username>/Library/Keychains/<keychain name>.keychain-db

A: Ambiguous Certificates
This happens when two certificates of the same identity are present in the keychain:
The codesign tool requires there only be one.

NOTE: The mention of ldid in your question might need a bit more
  clarification as to how it relates to your Apple issued codesigning
  certificates, or what the concern there is exactly.

Duplicate certificates sometimes appear in the keychain as a result of one being expired which was never removed. Apple has some instructions for resolving such issues, although you might need to go a bit outside the normal procedure for resolving it if the following doesn't work:

*

*In Keychain Access, make sure your "View" menu > Show Expired Certificates option is turned ON

*Click the "Certificates" 'Category' and then click through every one of the keychains you have listed in your 'Keychain' sidebar in Keychain Access. If you see any duplicates, even expired certificates, delete those duplicates.

*Click the "Keys" 'Category' in Keychain Access.

*Navigate through every keychain looking for and deleting any "Orphaned Keys" that have the same Common Name as the affected certificate. Orphaned keys are ones that are not bound by a Disclosure Triangle to an iPhone Developer or iPhone Distribution certificate that currently exists in the keychain.

*If you found and removed any extra keys or certificates, please reattempt your build.

*If the issue persists after removing all active or expired duplicate certificates or keys by the same common name, you might try removing all existing signing certificates and keys and replace them with new ones using the steps in How do I delete/revoke my certificates and start over fresh?.

*Finally, if the error persists even after creating new certificates, please control-click on the affected certificate in Keychain Access, choose "New Identity Preference" and click the 'Certificate' field. If you see duplicate certificates listed in here, this is an known and uncommon issue with Keychain Access. To work around the problem, try the following:
Keychain Access > Edit > Keychain List, uncheck "Shared" for the login keychain.
If going back into the Keychain List you find the login keychain is still marked as Shared, create a backup of the following files and then remove them if they exist:
    /Library/Preferences/com.apple.security-common.plist
    ~/Library/Preferences/com.apple.security.plist

Then retry your build...

If you fail to resolve the issue by the steps above then try searching
  for one of the certificates listed in the error message. Once you find
  the certifcate in question delete either the expired one, or the one
  that is conflicting with the one you need.

Multiple Codesigning Certificates (not duplicates)
If you have multiple codesigning certificates you will want to specify which one to use (if codesigning from the command line) by using the -s option:
codesign -s <certificate name> -vvvv foo.app

-s, --sign identity
           Sign the code at the path(s) given using this identity. See SIGNING IDENTITIES in man codesign.

Optional:

-v, --verify Requests verification of code signatures.  If other actions (sign, display, etc.) are also requested, -v is interpreted to
  mean --verbose.

For example, in your case:
codesign -s "iPhone Developer: John Doe" cryptest.app

A: Another way (or hack, at least) to resolve the ambiguity is to create a keychain identity preference.
From the codesign man page (man 1 codesign):
     -s, --sign identity
             Sign the code at the path(s) given using this identity. See
             SIGNING IDENTITIES below.

[...]

SIGNING IDENTITIES

[...]

     The identity is first considered as the full name of a keychain identity
     preference.  If such a preference exists, it directly names the identity
     used.  Otherwise, the identity is located by searching all keychains for a
     certificate whose subject common name (only) contains the identity string
     given.

In the context menu for a certificate in Keychain Access, there is an item New Identity Preference..., where a URL or email address to associate the certificate with can be given.  This is meant to allow a client certificate to be used with websites or email accounts, but an arbitrary string works, e.g. codesign-dev-id-app.  The string is given directly to the --sign option:
codesign --verbose --sign codesign-dev-id-app --timestamp foo.dmg

This worked for me (on macOS 10.13), whereas putting the certificates and keys in different keychains didn't, even when specifying --keychain explicitly (codesign still looked in all the keychains).  The string should probably be chosen carefully to avoid accidental conflicts with its intended purpose.  A dummy URL under a domain owned by the developer might be a good candidate.


text:
Q: How to create standalone application for cross-compiled Qt for wince? I followed this link to cross compile Qt for wince.
http://qt-project.org/doc/qt-4.8/install-wince.html
Everything worked as link says. I am able to run the applications on Visual Studio emulator for wince.
Now how do I make a single executable that can run on wince based device?

A: You have 2 ways to go:
1- Compile everything in your program statically (static linking).
2- Use UPX to compress everything in one file, which will decompress and open automatically.
http://upx.sourceforge.net/
Just be aware of the licensing problems in Qt if you use static linking with Qt.


text:
Q: OLE Automation - Ghost Excel Instance in Task Manager I am using wxAutomationObject to export data to MS Excel. I have created a few helper classes ExcelApp, ExcelWorkbook etc... all of which inherits from wxAutomationObject.
Briefly, ExcelApp is as follows:
class ExcelApp :public wxAutomationObject
{

    public:

        ExcelApp(WXIDISPATCH* dispatchPtr = NULL);

        ~ExcelApp() = default;

        void Quit();

        std::unique_ptr<ExcelWorkbook> CreateWorkbook(bool Visible = true);

        std::vector<std::unique_ptr<ExcelWorkbook>> GetOpenedWorkbooks();

        long GetNumberofOpenedWorkbooks() const;

    private:
        wxAutomationObject m_App;
};

The constructor is implemented as follows:
ExcelApp::ExcelApp(WXIDISPATCH* dispatchPtr):wxAutomationObject(dispatchPtr)
{
        if (!m_App.GetInstance("Excel.Application"))
            throw std::exception("An instance of Excel object could not be created.");
}

And to create a workbook, I used to following code:
std::unique_ptr<ExcelWorkbook> ExcelApp::CreateWorkbook(bool Visible)
{
        auto wb = std::make_unique<ExcelWorkbook>();

        bool suc = m_App.GetObject(*wb, "Workbooks.Add");

        if (!suc)
            return nullptr;

        if (Visible)
            m_App.PutProperty("Visible", true);

        return std::move(wb);
}

This whole OLE implementation is part of a dynamic menu. Part of the code for the event handler for menu is:
void MyFrame::OnExportToExcelButtonHandler(wxCommandEvent& event)
{

        auto item = static_cast<wxMenu*>(event.GetEventObject());

        std::unique_ptr<ExcelWorkbook> xlsWB ((ExcelWorkbook*)event.GetEventUserData());

        bool CreateNewWB = false;

        try
        {

            //Export either the entire workbook or the active worksheet to a new Workbook
            if (xlsWB == nullptr)
            {
                auto xlsApp = ExcelApp();

                xlsWB = std::move(xlsApp.CreateWorkbook());

                CreateNewWB = true;
            }

In terms of exporting data and formatting, everything works fine. However, after closing the created Workbooks Excel.exe still remains in the taskbar list. I wonder what I could be missing?
By the way, I tried the very basic sample shipped with wxWidgets and there seems to remain no ghost instances of Excel after quitting. I
I am using wxWidgets 3.1.4 on Windows 10 using VS 2019.
EDIT 1:
The ribbon button that generates the dynamic menu:
void MyFrame::OnExportToExcelButtonClicked(wxRibbonButtonBarEvent& event)
{
    auto excel = sys::win32::ole::ExcelApp();

        auto PrepareMenu = [&](wxMenu* Menu)
        {

            try
            {

                wxMenuItem* item1 = Menu->Append(wxID_ANY, "New Excel Workbook");
                item1->SetBitmap(wxArtProvider::GetBitmap(wxART_NEW));

                Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId());

                auto wbs = excel.GetOpenedWorkbooks();

                if (wbs.size() > 0)
                {
                    for (int i = 0; i < wbs.size(); ++i)
                    {
                        auto ExcelWB = std::move(wbs[i]);

                        wxMenuItem* item1 = Menu->Append(wxID_ANY, ExcelWB->GetFullName());

                        Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId(), wxID_ANY, ExcelWB.release());

                    }
                }

            }
}

The problem seems to originate from the following line:
Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, item1->GetId(), wxID_ANY, ExcelWB.release());

The ExcelWB pointer is now owned by the wxWidgets system and therefore a reference remains and thus the ghost Excel.exe remains.
To solve it, in the following procedure I added:
void MyFrame::OnExportToExcelButtonHandler(wxCommandEvent& event)
{
    Unbind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExportToExcelButtonHandler, this, event.GetId(), wxID_ANY, xlsWB.get());

But the problem still remains. I am not sure how to properly get rid of the pointer that is now owned by the menu. I redesigned some parts with shared_ptr and it did not help.

A: You already may be doing that but just to be sure.
When debugging such things, make sure the application instance is always visible so you can see when it for example gets stuck waiting on a user input, e.g., asking to save a modified workbook, preventing it from quitting.
I have written wxWidgets-based MS Excel automation wrapper wxAutoExcel (it uses a shared instead of unique pointer for Excel objects) and I have never encountered application ghosts, except when I terminated my application when debugging, without disposing Excel objects.
BTW, I do not get why your ExcelApp both derives from wxAutomationObject and has wxAutomationObject as a member variable (m_App). What is the IDispatch used in the ExcelApp ctor for?

A: Finally, it seems like I solved the issue, using the following steps:

*

*Instead of a menu, now a dialog is used; therefore, the menu does not own the pointer anymore.

*All wxAutomationObject inheriting objects are passed around via std::unique_ptr.


text:
Q: Back out a commit to origin/master I'm relatively new to git, and I think I broke my master. Hopefully, someone can help me untangle it.
I have my master on GitHub, and local master and tracking branch on my dev system. I also have the master on my QA system.
On my dev system, I committed my local branch and merged it into (local) master, then pushed master to origin/master at GitHub. Then, I pulled master to the QA system. Then, I made some further changes to my local branch.
What I did was:
dev branch -- merge --> dev master
dev master -- push --> GitHub master -- pull --> QA master

I think I should have done:
dev **branch** -- push --> GitHub **branch** -- pull --> QA **branch**

Is that right?
Now: I want to revert the QA and GitHub master back before the commit ... in effect, back out that whole merge. Then, I want to push the branch (not the master) up to GitHub, and pull the branch to QA.

*

*How do I revert the masters on QA and on GitHub?

*Do I also need to revert the master on development?

*How do I preserve the branch changes I've made on development?

Help, please?

A: Should you have pushed a branch instead of merging to master?
That's a good question.  If the commit was highly experimental, then pushing a branch probably would have been better.  Otherwise, if you had a high confidence in the commit, then merging to master was correct.  No need to pollute your workspaces with remote branches if you don't have to.
Let's assume you want to switch this commit to a branch and push it remotely.  I'll draw a commit graph for this scenario:
A-C-D
 \   \
  B---E < master, your_branch

Let's say master was at B, and C & D where made on your_branch.  E is the merge commit for the two.  On to your questions.  You revert master on GitHub & QA by fixing your local repository, and then forcing GitHub in particular to match it.  So actually your questions are best answered in reverse order.
First we fix your_branch
git checkout your_branch
git reset --hard D

This will move branch to D, yielding:
A-C-D < your_branch
 \   \
  B---E < master

Now we fix your local development master
git checkout master
git reset --hard B

Which gives:
A-C-D < your_branch
 \
  B < master

Good-bye, unwanted merge commit E.
Fix GitHub (and QA)
git checkout master
git push -f

This will force master on GitHub back to B.  If you were collaborating with other devs, they would hate for this as you're re-writing history.  But since this presumably your personal repository without collaboration, go for it.  Now to make a remote branch:
git checkout your_branch
git push origin your_branch

Now that GitHub has been fixed to match development, updating QA should be a simple:
git checkout master
git pull
git reset --hard origin/master  # I'm assuming master will be on an orphaned commit after the pull

A: To me, the initial question seems like a matter of personal workflow preference of whether you want the development branch to already be merged into master by the time it hits the QA system. As for your current predicament, my (not-so-necessarily the best) suggestion:

*

*In your local master, git revert <merge-commit>, reverts the changes introduced by your development branch merge. Push the local master up. Pull that across to QA. After this, master across all repositories should be at the same history state.

*As per the above point, to maintain repository consistency I would do so, yes.

*Before doing your revert, stash your changes (cf. git stash). After completing the entire revert process, pop the changes (cf. git stash pop).

Hope you find that useful.


text:
Q: how will the hashset add to the following situation     public class Employee
    {
    int empId;
    String empName;
    }

Employee object has to be added to an hashset.
I am implementing the equals method where  only the empName is used to compare the 2 objects.
In one of the cases they happen to be same.
Is it possible to have a different hash code if i override hashcode method.
what is the possibility to add both objects to hashset?


text:
Q: HttpWebRequest - Как получить ответ сервера при ошибке 429? При посылке запроса с айпи тор в браузере - видно что ответ на запрос с кодом 429, но при этом в ответе код страницы с капчей, которую надо решить.
При посылке запроса через HttpWebRequest:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
//попытка прочитать ответ, из-за кода 429 сюда не заходит
}

из-за ошибки не могу прочитать страницу с капчей
Как можно получить тело ответа сервера при ошибке 429 ?

A: Есть миллион ответов на всех языках StackOverflow, поясняющих что HttpWebRequest устарел.
Но я еще раз поясню: HttpWebRequest не рекомендуется для новой разработки, об этом написано в его документации.

Мы не рекомендуем использовать HttpWebRequest для новой разработки. Вместо этого используйте System.Net.Http.HttpClient класс.

private static readonly HttpClient client = new HttpClient();

private async Task<string> GetPageAsync(string url)
{
    using var response = await client.GetAsync(url);
    if (!response.IsSuccessStatusCode) // диагностика
    {
        Console.WriteLine($"{url} - {(int)response.StatusCode} {response.ReasonPhrase}");
    }
    return await response.Content.ReadAsStringAsync();
}

Использовать
string html = await GetPageAsync("https://ru.stackoverflow.com");

Если не знаете, что такое async/await - вам сюда.


text:
Q: SR Flip-flop builded from 2 SR-Latch I just study about flip-flop in my class and this is the picture from the slide my teacher used that explain the construction of SR Flip-flop

However, I find something was wrong with this figure. If the input are S=1, R=0, Clk=1 at an instant then the out put of the master Latch is Q=1 and Q' = 0. Take that to the input of the Slave Latch. Q = 1 => S of slave latch = 1 but Q' is inverted that make R of the slave make also equal 1 which is forbidden condition.
I think my teacher make a mistake. The right figure should not have the inverter at the complement of output of master Latch but on the clk to en gate of slave Latch

A: For the positive half of the clock, first SR flip flop is enabled. So you will get output at Y and Y'. And for the negative half, second flip flop is enabled and you will get output at Q and Q'
That means, effectively you get respective output at starting of negative half (neg edge) of the clock signal.


text:
Q: SUID has no effect on directories with Linux Why does the SUID bit have no effect when applied to directories in Linux? I clearly see that I can set it with 'chmod u+s'. But why does it not have "any" effect. What is the reason for implementing a way to SET it but not implementing any effect?

A: The main reason to have a way to set it is simple: simplicity. It's simpler to treat the setuid bit on directories uniformly with other bits, than it would be to make an exception and reject attempts to set it.
Another reason is that you can mount a filesystem under Linux, set the setuid bit on a directory, and then mount this filesystem under another operating system that does treat the setuid bit in a meaningful way.
As for why the setuid bit has no effect on directories on Linux, that's because no one has found a compelling meaning for it. It can't work in the same way as the setgid bit because Linux doesn't allow a user to give away a file to another user.


text:
Q: Multiple lines macros in c++ I tried to write the macros for the code below but the Test word is underline with red and I do not know if the macros I declared are correct.
 The code is:
ABC Test{
int x,y,z;
AAA:
Test() : INIT(x),INIT(y),INIT(z) { }
CREATE(x);
CREATE(y);
CREATE(z);
};

I this the ABC word should be an equivalent for "class" and AAA is "public".
The macros I wrote are:
#define ABC class name\
int _DATE_
#define AAA public
#define INIT(number)\
{int number = _COUNTER_}
#define ZERO  0
#define CREATE(number) number = ZERO;

A: if m.cc is
#define ABC class name\
int _DATE_
#define AAA public
#define INIT(number)\
{int number = _COUNTER_}
#define ZERO  0
#define CREATE(number) number = ZERO;

ABC Test{
int x,y,z;
AAA:
Test() : INIT(x),INIT(y),INIT(z) { }
CREATE(x);
CREATE(y);
CREATE(z);
};

then (can use also gcc of course) :
pi@raspberrypi:/tmp $ g++ -E m.cc
# 1 "m.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "m.cc"
# 9 "m.cc"
class nameint _DATE_ Test{
int x,y,z;
public:
Test() : {int x = _COUNTER_},{int y = _COUNTER_},{int z = _COUNTER_} { }
x = 0;;
y = 0;;
z = 0;;
};

so indented :
class nameint _DATE_ Test{
    int x,y,z;
  public:
    Test() : {int x = _COUNTER_},{int y = _COUNTER_},{int z = _COUNTER_} { }
    x = 0;;
    y = 0;;
    z = 0;;
 };

probably not the expected result ;-)

Perhaps you wanted something like :
#define ABC(name) class name {int _DATE_;
#define AAA public
#define INIT(number)  number(_COUNTER_)
#define ZERO  0
#define CREATE(number) int number = ZERO;

ABC (Test)
CREATE(x)
CREATE(y)
CREATE(z)
AAA:
Test(int _COUNTER_) : INIT(x),INIT(y),INIT(z) { }
};

then :
pi@raspberrypi:/tmp $ g++ -E  m.cc
# 1 "m.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "m.cc"

class Test {int _DATE_;
int x = 0;
int y = 0;
int z = 0;
public:
Test(int _COUNTER_) : x(_COUNTER_),y(_COUNTER_),z(_COUNTER_) { }
};

so indented :
class Test {
    int _DATE_;
    int x = 0;
    int y = 0;
    int z = 0;
  public:
    Test(int _COUNTER_) : x(_COUNTER_),y(_COUNTER_),z(_COUNTER_) { }
};


text:
Q: Export data from table to excel, how to stop excel from auto converting the value? I am currently working on an export function on a project. (I am a fresh graduated student)
I had successfully done the function. the issue I facing now is the excel will auto convert(or format?) my initial value to another form. May I know is there any solution to stop from excel perform auto-converting to a value?

scenario: original number is 7778362019198430, after export, it shows
             7.77836E+15

here is the code of my export function
function fnExcelReport(tableID) {

            var downloadLink;
            var dataType = 'application/vnd.ms-excel';
            var tableSelect = document.getElementById(tableID);
            var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

            // Specify file name
            var d = new Date();
            var todaysDate = d.getFullYear() + '-' + d.getMonth() + '-' +
                d.getDate();
            filename = 'CashCard_' + todaysDate + '.xls';

            // Create download link element
            downloadLink = document.createElement("a");

            document.body.appendChild(downloadLink);

            if(navigator.msSaveOrOpenBlob){
                var blob = new Blob(['\ufeff', tableHTML], {
                    type: dataType
                });
                navigator.msSaveOrOpenBlob( blob, filename);
            }else{
                // Create a link to the file
                downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

                // Setting the file name
                downloadLink.download = filename;

                //triggering the function
                downloadLink.click();
            }

        }

The expected output should be as same as what the original value which is 7778362019198430,but excel perform auto converting, the output after export will auto convert to  7.77836E+15.
Is there any way to stop it? thank you very much.

A: The number in this format "7.77836E+15" is called scientific notation, it represents 7.77836 × 1015.
This StackExchange thread says that if you right-click the cells and click "Format cells" and choose "Number" you can stop Excel from using scientific notation.
It looks like there is a lot to your code that we cannot see, but I suspect you will be able to format cells when creating the document.
You might want to try this.

A: I don't know how to do this in javascript. If you move your export functionality to c# this can done with setting the Cell Style like
sheet.Cells[i].Attributes.Add("style", "textmode");


text:
Q: sort multidimensional array by gender and age Helo guys, i need your help.
I have an arrays data :
   $biodata = array(
            array(
                'nama' => 'Ayu',
                'gender' => 'P',
                'usia' => 12,
            ),
            array(
                'nama' => 'Doni',
                'gender' => 'L',
                'usia' => 30,
            ),
            array(
                'nama' => 'Yasina',
                'gender' => 'P',
                'usia' => 24,
            ),
            array(
                'nama' => 'Irul',
                'gender' => 'L',
                'usia' => 20,
            ),
            array(
                'nama' => 'Abdis',
                'gender' => 'L',
                'usia' => 21,
            ),
    );

I want to sort the data by 'gender' and 'usia', then I have to display it in the html table, what should I do?
here's my code :
usort($biodata, function($a, $b){
    return $a['gender'] > $b['gender'];
});

?>

        No
        NAMA
        GENDER
        Usia

<?php
;   $i = 1;
    foreach ($biodata as $d) {

     ?>

<?php echo $i; ?>
        <?php echo $d['nama']; ?>
        <?php echo $d['gender']; ?>
        <?php echo $d['usia']; ?>

    <?php

    $i = $i +1;

        } ?>

but it only sorts by gender, what I need is to sort by 'gender' and 'usia'. I really hope to find help here, I'm very curious.

A: You can do it in this way
$sortColumn = ['gender', 'usia'];
foreach($sortColumn as $column){
  usort($biodata, function($a, $b) use ($column){
    return $a[$column] > $b[$column];
  });
}

Demo : https://3v4l.org/bRIMQ


text:
Q: How do I find the particular solution to this ODE? I'm currently stuck on finding a solution for the following ODE:
$$ y'' +2y' +5y = e^{-x}(60\sin(x) + 57\cos(x))$$
The homogeneous part is fairly easy, just solving the auxiliary equation:
$ y_h = e^{-x}(C_1\cos(2x)) + C_2\sin(2x))$
But when it comes down to the particular part, I'm lost...
Symbolab is giving me:
$ y_h = e^{-x}(19\cos(x)) + 20\sin(x))$
But I have no clue how come.
The teacher will not provide any solutions and I have this test coming up in 2 days. Any help will be greatly appreciated!

A: use the undetermined coefficient method
so
$$y_p=e^{-x}(A\cos x+B\sin x)$$
$$y'_p=e^{-x}((B-A)\cos x-(A+B)\sin x)$$
$$y''_p=e^{-x}(2A\sin x-2B\cos x)$$
then plug it into the original D.E to get
$$3Ae^{-x} \cos x+3Be^{-x} \sin x=e^{-x}(60 \sin(x) + 57 \cos(x))$$now complete it

A: This particular solution can be obtained by using a function similar to the inhomogeneity (also known as the form of the right-hand side).
Use the ansatz
$$y_p=a e^{-x}\sin x + b e^{-x}\cos x$$
and plug it into the differential equation. Then compare the coefficients of similar terms to determine the coefficients $a$ and $b$.


text:
Q: I am confused with using pronouns Those dreaming of the perfect match are outnumbered by those who don't really want it at all, though perhaps they can't admit it.
In above sentence, it is confusing what those two pronouns refer to. (Bold character 'they' and 'it') Any help will be appreciated.

A: "They" is a plural pronoun, and here it must refer to one of the two groups of people.  In context it must be the second group "those who don't really want it at all".
When you say "Admit /something/" the something is the statement. Here it must be the thing that "They" can't say.  "It" refers to "not really wanting it it".
This kind of strict analysis is not really how language is understood by native speakers. In particular the meaning of "it" is not very important. But the verb "admit" needs to be followed by an object, so "it" will fill that need.


text:
Q: SVNServer moved to other server, cant relocate project I just moved my repositories to another server by copying the pasting the files in the appropriate folder. In the new server I can see the repositories loaded correctly. But when I go to my visual studio projects folders and right click TortoiseSVN -> relocate
From url: http://xx.xx.x.101:81/svn/Proj to Url: http://xx.xx.x.1:81/svn/Proj but it throws time out. Any suggestions how to fix it?
EDIT
I opened the 81 port in firewall with no luck...
  Proto  Local Address          Foreign Address        State

TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  RpcSs
 [svchost.exe]
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING
 [VisualSVNServer.exe]
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING

I changed my url to http://xx.xx.x.1:445/svn/Proj but now I got this error: error running context an existing connection was forcibly closed by the remote host

A: I assume you have a RHEL based distribution like CentOS. Let me know if you have something else.
Timeout usually means that there is a firewall or a routing problem. If ping works, then it is firewall. I will list below some generic things to check.
Make sure that you have apache configured with mod_dav.
apachectl -M

Make sure apache is listening on port 81 on the ethernet interface or on all interfaces.
sudo netstat -anp|grep :81

Make sure port 81 is open in firewall and that is labeled properly in SELinux.
sudo semanage port -l|grep 81
sudo semanage port -a -t http_port_t -p tcp 81  # To add it if it is missing

Make sure the port is open in local firewall or any firewall on the path. Check also the firewall on your desktop machine.
iptables -l   # To list the rules on the local firewall.


text:
Q: User model with static set of related models Say I have a User model in django and I want to add some achievements to users. So I've created an Achieve model:
class Achive:
    type = ....
    value = ....
    status = BooleanField(default=False)

I want all those achieves be a static set of models for every user (20 instances, for example) with ability to delete old and create new achieves. The problem is how to do it. Expected flow is:
1) user granted to use achievement system;
2) user got all those achieves (in admin panel shows like a table);
3) in admin panel per user I can change status of every achieve (affects only on edited user);
4) if new Achieve instance is created — add to all users who have achievements;
5) if existed Achieve instance has been deleted — remove from all users;
Solutions with I came up:
1) use Achieve model with jsonfield. store achieves in json like dictionary, use custom widget for admin panel to show checkboxes to change status). But where to store global set of achievements to create new/delete old ones? how to manage it?
2) use many to many field to Achieve and Achieve model without status. Why: if relation between User ← → Achieve exists, that means that user earn an achieve.
Both solutions I don't really like so hope for your advice.
P.S. sqlite is used as db and not allowed to use another (like mongo, etc.)
Thanks in advance!

A: What you want is a ManyToMany relationship between Achieve and User, but with the ability to store extra data on the relationship (the status for example).
With a normal ManyToManyField on a Model, Django actually creates an intermediate model to store the relationships in the database. By adding a through argument to your ManyToManyField, you can specify the intermediate model used for the relationship and store extra data with the relationship, as documented here:
class Goal(models.Model):
    type = ...
    value = ...
    achievers = models.ManyToManyField(to=User, through='Achievement', related_name='goals')

class Achievement(models.Model):
    status = models.BooleanField()
    date_reached = models.DateField(null=True)
    goal = models.ForeignKey(to=Goal, on_delete=models.CASCADE)
    achiever = models.ForeignKey(to=User, on_delete=models.CASCADE)

then you can create and query the relationships like this, assuming you have a user and a goal:
achievement = Achievement.objects.create(status=True, date_reached=date(2018, 10, 12), achiever=user, goal=goal)
user.goals.filter(achievement__status=True)  # gives the achieved goals of a user
goal.achievers.filter(achievement__status=True)  # gives the users that achieved a goal


text:
Q: For a React app, can it be made so that `npm run build` will bust the cache for CSS files? The current React has the tool to create an app:
create-react-app hello-world

and to build the app to be deployed:
npm run build

It busts the cache for the main JavaScript file, using a filename like main.742a4123.js, but when I tried the app, the CSS file might not get refreshed and I can disable the cache in the Chrome DevTools, but what about the general users?
They can be using the old version.  Maybe the server can be configured so that the etag or expiration date can make it refresh the file, but if the file can be style.css?t=1491264234 or style.742a4123.css then there is no need to do such checks and worry about what if the file expires in 1 day but you need to push out a new version as a fix after 2 hours.  Does npm run build have some mechanism to do this?

A: For your production builds, you may need to eject (npm run eject) to get the webpack file and edit it to use [chunkhash] in the output file name. For more details:
https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95

A: Here is the complete solution for you how to busted the cache in below given link
Strategies for cache busting CSS
So the question you want 'npm run build' will bust the cache?
But first thing is if you are using the create react app which wont give much option for bundling script (so can't say no but there is lot of configuration) but the issue that script lie in node_module so any update to it wont help
Second option is you eject the reacts-script by run this command 'npm run eject' then you'll find a config folder created in your project. You will find your webpack config files init.
Incase if you don't want to eject and you just want to look at the config you will find them in /node_modules/react-scripts/config
webpack.config.dev.js. //used by `npm start`
webpack.config.prod.js //used by `npm run build`

Once you have your own webpack config file you will able to name the css file unique and add that file to html for more please read webpack config
Here is webpack tutorial which will help you more

A: You can declare a React environment variable, assign a unique value to it and reference it in your index.html file.
In your build script (bash):
REACT_APP_CACHE_BUST={e.g. build number from a CI tool} npm run build

In your index.html:
<link rel="stylesheet" href="%PUBLIC_URL%/index.css?cachebust=%REACT_APP_CACHE_BUST%" />

The variable name has to start with REACT_APP_.
More about environment variables in React: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables.


text:
Q: how to implement a price range slider I am implementing a range slider within the bootstrap template:

<input type="range" name="range" step="50000" min="100000" max="1000000" value="" onchange="rangePrimary.value=value">
<input type="text" id="rangePrimary" />

The range value is displayed in the text-field with id rangeprimary.
I want to make this range slider work as a price range slider, where the lowest and highest ranges would be passed into two text-fields
Most of the price range sliders I have seen don't work well with the template am using.

A: Ion Range Slider is an excellent option, requiring only Jquery.
Very customizable and works excellently in Bootstrap. Also has excellent documentation.
http://ionden.com/a/plugins/ion.rangeSlider/en.html
An example of a single slider implementing exactly what you require using this plugin is shown on the Basic Demo Page.
<input type="text" id="rangePrimary" name="rangePrimary" value="" />

$("#rangePrimary").ionRangeSlider({
    type: "double",
    grid: true,
    min: 0,
    max: 1000,
    from: 200,
    to: 800,
    prefix: "£"
});

To then get the data from it you can do an Onchange Function example again from the web site.
$("#rangePrimary").on("change", function () {
    var $this = $(this),
        value = $this.prop("value").split(";");
        var minPrice = value[0];
        var maxPrice = value[1];
        $("#priceRangeSelected").text("Lower Price Range = £" + minPrice + " , Upper Price Range = £" + maxPrice);
});

This will update produce a message below the slider with the value selected on change of the sliders.

A: Here is a link to a price slider range.
1)Price Slider Shopping Carts(Visit this link)
HTML

             <input type="range" id="slider0to50" step="5" min="0" max="50">
             <input type="range" id="slider51to100" step="5" min="50" max="100">

             <input type="number" step="5" min="0" max="50" placeholder="Min" id="min" >
             <input type="number" step="5" min="51" max="100" placeholder="Max" id="max">

CSS
#rangeBox{ /* carry complete  range box*/
    width:300px;
    height:100px;

    }
    #sliderBox{
    position:relative;
    top:0%;
    width:300px;  /*2x width*/
    }
    #slider0to50{
    width:150px;/*1x width*/
    position:absolute;
    left:0%;
    }
    #slider51to100{
    width:150px;/*1x width*/
    position:absolute;
    left:50%;
    }
    #inputRange{
    position:relative;
    top:50%;
    }
    #inputRange::after{
    content:"";
    clear:both;
    display:block
    }
    #inputRange #min{
     width:40%;
    float:left;
     }
    #inputRange #max{
     width:40%;
    float:right;
    }

JS
var sliderLeft=document.getElementById("slider0to50");
 var sliderRight=document.getElementById("slider51to100");
 var inputMin=document.getElementById("min");
 var inputMax=document.getElementById("max");

///value updation from input to slider
//function input update to slider
function sliderLeftInput(){//input udate slider left
    sliderLeft.value=inputMin.value;
}
function sliderRightInput(){//input update slider right
    sliderRight.value=(inputMax.value);//chnage in input max updated in slider right
}

//calling function on change of inputs to update in slider
inputMin.addEventListener("change",sliderLeftInput);
inputMax.addEventListener("change",sliderRightInput);

///value updation from slider to input
//functions to update from slider to inputs
function inputMinSliderLeft(){//slider update inputs
    inputMin.value=sliderLeft.value;
}
function inputMaxSliderRight(){//slider update inputs
    inputMax.value=sliderRight.value;
}
sliderLeft.addEventListener("change",inputMinSliderLeft);
sliderRight.addEventListener("change",inputMaxSliderRight);

2)Multiple Thumb Slider Shopping Carts Advance

A: You can get the element from javascript and then give it the properties min and max getting them from the two textfields:
var x = document.getElementById('rangePrimary');
x.min = the value you get from the first textfield
x.max = the value you


text:
Q: df.Pivot with duplicate index values I have a df that looks like this:
    ts  VariableName    Location    Value   Notes
0   1   Population      01          99      NaN
1   1   Population      02          117     NaN
2   1   Mean_Age        03          28      NaN
3   1   Percent_Male    01          19      NaN
4   1   Population      03          137     NaN

I'd like to make the DF look like this:
ts Location Population Mean_Age Percent_Male Notes
1  01       99         45       51           NaN
1  02       117        39       72           NaN
1  03       137        28       43           NaN
...

I've tried a few different pivot operations, such as
df.reset_index().pivot(index='ts', columns='VariableName', values=['Value', 'Location', 'Notes])

but keep running into duplicate index values errors.
There are obviously duplicate values in most of the columns, but the combination of ts+VariableName+Location will be unique. I've looked into some stack/unstack options, but can't get anything to work.


text:
Q: Popup in BlackBerry 10 How do I show a popup in Blackberry 10? I want to show popup when any contact is added /deleted/updated.  I took one method like this---
void ContactEditor::showToast(QString text) {
bb::system::SystemToast toast;
toast.setBody(text);
toast.setPosition(bb::system::SystemUiPosition::MiddleCenter);
toast.exec();
}

and called like this---
showToast("contact added...");

included file for System Toast also.
but this is giving me error----
make[2]: *** [o-g/addressbook] Error 1
make[1]: *** [debug] Error 2
make: *** [Simulator-Debug] Error 2

can somebody tell me whats the problem ?

A: Add LIBS += -lbbsystem to your application pro file. and include
#include <bb/system/SystemToast>
         SystemToast *toast = new SystemToast(this);
                                toast->setBody("Your Toast");
                                toast->setPosition(SystemUiPosition::MiddleCenter);
                                toast->show();


text:
Q: Laravel 4 - Integrity constraint violation: 1062 Duplicate entry I am trying to create a user management system. Everything is going fine until the time I wanted to implement the "Edit User" part. I have successfully avoid the 'problem' with the unique username and e-mail fields, by ignoring the user's id in my rules.
The problem is, when I am trying to update a user to a non-existing username or email, everything is working. But when I am trying to do the same thing for something that already exists, I get an error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'existing_username_here' for key 'users_username_unique'

I already have the 'unique' field implemented in my rules, so I don't know what's wrong with that. Is there a way so I can catch this specific exception and show it to the user? Is there a way to outreach this problem? I have been searching for hours and hours and I can't seem to find anything useful.
Edit: It seems like it tries to insert a new raw instead of updating the existing one...! I don't know why that happens. Any thoughts?
 AdminController.php
public function update($id)
    {
        if ( ! $this->validator->isValidForAdminEdit()) {
        return Redirect::back()->withErrors($this->validator->errors())->withInput();
    }

    $user = $this->register->getUserById($id);
    $data = [
        'id' => $user->id,
        'first_name' => Input::get('first_name'),
        'email' => Input::get('email'),
        'username' => Input::get('username'),
        'password' => Input::get('password'),
        'activated' => Input::get('activated'),
        'assign_role' => Input::get('assign_role')
    ];

    $updatedUser = $this->adminRegister->update($data);

    return Redirect::to('admin/users')
    ->with(['flash_message' => "The user $updatedUser->username has been edited.",
            'flash_type' => 'success']);

}

 DbAdminRepository.php
public function update(array $data)
    {

    $user = Register::find($data['id']);
    $user->first_name = $data['first_name'];
    $user->username = $data['username'];
    $user->email = $data['email'];
    if (isset($data['password']) && ($data['password'] != "")) {
        $user->password = Hash::make($data['password']);
    }
    $user->activated = (! isset($data['activated']) ? (int)0 : (int)1);
    $role = $data['assign_role'];

    $user->save();   // THE PROBLEM SEEMS TO BE HERE
    $user->roles()->detach();
    $user->roles()->attach($role);

    return $user;
}

 Validator.php
public function isValidForAdminEdit(array $rules = array())
    {
    // if there are no rules return true.
    if(!isset(static::$rules)) return true;

    $rules = self::processRules($rules ? $rules : static::$admin_edit_rules);
    $validator = V::make($this->attributes, $rules);

    if ($validator->fails()) {
        $this->errors = $validator->messages();
        return false;
    }
    return true;
}

protected function processRules(array $rules)
{
    // get the model's ID.
    // If the ID is null, it's a new Model, so let's strip out the id completely.
    $id = $this->attributes['id'];
    $replacement = $id == null ? "" : "," . $this->attributes['id'];
    array_walk($rules, function(&$item) use ($replacement)
    {
    // Replace placeholders
        $item = stripos($item, ',:id:') !== false ? str_ireplace(',:id:', $replacement, $item) : $item;
    });
    return $rules;
}

public function errors()
{
    return $this->errors;
}

 UserValidator.php
static $admin_edit_rules = [
    'username' => 'Required|Min:3|Max:32|Unique:registers,username,:id:',

    'email'  => 'Required|Between:3,64|Email|Unique:registers,email,:id:',

    'first_name' => 'Required|Min:3|Max:80|Alpha',

    'password'  =>'AlphaNum|Between:4,20|Confirmed',

    'password_confirmation'=>'AlphaNum|Between:4,20',

];


text:
Q: Help with understanding a very basic main() disassembly in GDB Heyo,
I have written this very basic main function to experiment with disassembly and also to see and hopefully understand what is going on at the lower level:
int main() {
  return 6;
}

Using gdb to disas main produces this:
0x08048374 <main+0>:    lea    0x4(%esp),%ecx
0x08048378 <main+4>:    and    $0xfffffff0,%esp
0x0804837b <main+7>:    pushl  -0x4(%ecx)
0x0804837e <main+10>:   push   %ebp
0x0804837f <main+11>:   mov    %esp,%ebp
0x08048381 <main+13>:   push   %ecx
0x08048382 <main+14>:   mov    $0x6,%eax
0x08048387 <main+19>:   pop    %ecx
0x08048388 <main+20>:   pop    %ebp
0x08048389 <main+21>:   lea    -0x4(%ecx),%esp
0x0804838c <main+24>:   ret

Here is my best guess as to what I think is going on and what I need help with line-by-line:
lea    0x4(%esp),%ecx
Load the address of esp + 4 into ecx. Why do we add 4 to esp?
I read somewhere that this is the address of the command line arguments. But when I did x/d $ecx I get the value of argc. Where are the actual command line argument values stored?
and    $0xfffffff0,%esp
Align stack
pushl  -0x4(%ecx)
Push the address of where esp was originally onto the stack. What is the purpose of this?
push   %ebp
Push the base pointer onto the stack
mov    %esp,%ebp
Move the current stack pointer into the base pointer
push   %ecx
Push the address of original esp + 4 on to stack. Why?
mov    $0x6,%eax
I wanted to return 6 here so i'm guessing the return value is stored in eax?
pop    %ecx
Restore ecx to value that is on the stack. Why would we want ecx to be esp + 4 when we return?
pop    %ebp
Restore ebp to value that is on the stack
lea    -0x4(%ecx),%esp
Restore esp to it's original value
ret
I am a n00b when it comes to assembly so any help would be great! Also if you see any false statements about what I think is going on please correct me.
Thanks a bunch! :]

A: You did pretty good with your interpretation. When a function is called, the return address is automatically pushed to the stack, which is why argc, the first argument, has been pushed back to 4(%esp). argv would start at 8(%esp), with a pointer for each argument, followed by a null pointer. This function pushes the old value of %esp to the stack so that it can contain the original, unaligned value upon returned. The value of %ecx at return doesn't matter, which is why it is used as temporary storage for the %esp reference. Other than that, you are correct with everything.

A: Regarding your first question (where are stored the command line arguments), arguments to functions are right before ebp. I must say, your "real" main begins at < main + 10 >, where it pushes ebp and moves esp to ebp. I think that gcc messes everything up with all that leas just to replace the usual operations (addictions and subtractions) on esp before and after functions call. Usually a routine looks like this (simple function I did as an example):
   0x080483b4 <+0>:     push   %ebp
   0x080483b5 <+1>:     mov    %esp,%ebp
   0x080483b7 <+3>:     sub    $0x10,%esp            # room for local variables
   0x080483ba <+6>:     mov    0xc(%ebp),%eax        # get arg2
   0x080483bd <+9>:     mov    0x8(%ebp),%edx        # and arg1
   0x080483c0 <+12>:    lea    (%edx,%eax,1),%eax    # just add them
   0x080483c3 <+15>:    mov    %eax,-0x4(%ebp)       # store in local var
   0x080483c6 <+18>:    mov    -0x4(%ebp),%eax       # and return the sum
   0x080483c9 <+21>:    leave
   0x080483ca <+22>:    ret

Perhaps you've enabled some optimizations, which could make the code trickier.
Finally yes, the return value is stored in eax. Your interpretation is quite correct anyway.

A: Stack frames
The code at the beginning of the function body:
push  %ebp
mov   %esp, %ebp

is to create the so-called stack frame, which is a "solid ground" for referencing parameters and objects local to the procedure. The %ebp register is used (as its name indicates) as a base pointer, which points to the base (or bottom) of the local stack inside the procedure.
After entering the procedure, the stack pointer register (%esp) points to the return address stored on the stack by the call instruction (it is the address of the instruction just after the call). If you'd just invoke ret now, this address would be popped from the stack into the %eip (instruction pointer) and the code would execute further from that address (of the next instruction after the call). But we don't return yet, do we? ;-)
You then push %ebp register to save its previous value somewhere and not lose it, because you'll use it for something shortly. (BTW, it usually contains the base pointer of the caller function, and when you peek that value, you'll find a previously stored %ebp, which would be again a base pointer of the function one level higher, so you can trace the call stack that way.) When you save the %ebp, you can then store the current %esp (stack pointer) there, so that %ebp will point to the same address: the base of the current local stack. The %esp will move back and forth inside the procedure when you'll be pushing and popping values on the stack or reserving & freeing local variables. But %ebp will stay fixed, still pointing to the base of the local stack frame.
Accessing parameters
Parameters passed to the procedure by the caller are "burried just uner the ground" (that is, they have positive offsets relative to the base, because stack grows down). You have in %ebp the address of the base of the local stack, where lies the previous value of the %ebp. Below it (that is, at 4(%ebp) lies the return address. So the first parameter will be at 8(%ebp), the second at 12(%ebp) and so on.
Local variables
And local variables could be allocated on the stack above the base (that is, they'd have negative offsets relative to the base). Just subtract N to the %esp and you've just allocated N bytes on the stack for local variables, by moving the top of the stack above (or, precisely, below) this region :-) You can refer to this area by negative offsets relative to %ebp, i.e. -4(%ebp) is the first word, -8(%ebp) is second etc. Remember that (%ebp) points to the base of the local stack, where the previous %ebp value has been saved. So remember to restore the stack to the previous position before you try to restore the %ebp through pop %ebp at the end of the procedure. You can do it two ways:
1. You can free only the local variables by adding back the N to the %esp (stack pointer), that is, moving the top of the stack as if these local variables had never been there. (Well, their values will stay on the stack, but they'll be considered "freed" and could be overwritten by subsequent pushes, so it's no longer safe to refer them. They're dead bodies ;-J )
2. You can flush the stack down to the ground and free all local space by simply restoring the %esp from the %ebp which has been fixed earlier to the base of the stack. It'll restore the stack pointer to the state it has just after entering the procedure and saving the %esp into %ebp. It's like loading the previously saved game when you've messed something ;-)
Turning off frame pointers
It's possible to have a less messy assembly from gcc -S by adding a switch -fomit-frame-pointer. It tells GCC to not assemble any code for setting/resetting the stack frame until it's really needed for something. Just remember that it can confuse debuggers, because they usually depend on the stack frame being there to be able to track up the call stack. But it won't break anything if you don't need to debug this binary. It's perfectly fine for release targets and it saves some spacetime.
Call Frame Information
Sometimes you can meet some strange assembler directives starting from .cfi interleaved with the function header. This is a so-called Call Frame Information. It's used by debuggers to track the function calls. But it's also used for exception handling in high-level languages, which needs stack unwinding and other call-stack-based manipulations. You can turn it off too in your assembly, by adding a switch -fno-dwarf2-cfi-asm. This tells the GCC to use plain old labels instead of those strange .cfi directives, and it adds a special data structures at the end of your assembly, refering to those labels. This doesn't turn off the CFI, just changes the format to more "transparent" one: the CFI tables are then visible to the programmer.

A: The only thing I think that's outstanding from your original questions is why the following statements exist in your code:
0x08048381 <main+13>:   push   %ecx
0x08048382 <main+14>:   mov    $0x6,%eax
0x08048387 <main+19>:   pop    %ecx

The push and pop of %ecx at <main+13> and <main+19> don't seem to make much sense - and they don't really do anything in this example, but consider the case where your code invokes function calls.
There's no way for the system to guarantee that the calls to other functions - which will set up their own stack activation frames - won't reset register values. In fact they probably will. The code therefore sets up a saved register section on the stack where any registers used by the code (other than %esp and %ebp which are already saved though the regular stack setup) are stored in the stack before possibly handing control over to function calls in the "meat" of the current code block.
When these potential calls return, the system then pops the values off the stack to restore the pre-call register values. If you were writing assembler directly rather than compiling, you'd be responsible for storing and retrieving these register values, yourself.
In the case of your example code, however, there are no function calls - only a single instruction at <main+14> where you're setting the return value, but the compiler can't know that, and preserves its registers as usual.

It would be interesting to see what would happen here if you added C statements which pushed other values onto the stack after <main+14>. If I'm right about this being a saved register section of the stack, you'd expect the compiler to insert automatic pop statements prior to <main+19> in order to clear these values.


text:
Q: 'Cannot read property navigate of undefined' for full screen Modal in React Native navigation I'm trying to render a full screen modal in React Native when an 'Account' button is clicked in the top left of the header but receive the error

Cannot read property navigate of undefined

Where am I going wrong with this?
AppNavigator.js file:
import React, {useState} from 'react';
import {
  Button,
  Image,
  Modal,
  Pressable,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {HomeScreen} from '../../features/reports/screens/HomeScreen';
import {RiskAssessmentListScreen} from '../../features/reports/screens/RiskAssessmentListScreen';
import {ModalScreen} from '../../features/reports/screens/ModalScreen'

const Stack = createStackNavigator();

const AppNavigator = ({navigation}) => {

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="GoPAD"
          component={HomeScreen}
          options={{
            headerLeft: () => (
              <Button
        onPress={() => navigation.navigate('MyModal')}
        title="Account"
      />
            ),
            headerRight: () => (
              <Image
                style={{tintColor: 'blue'}}
                source={require('../../../assets/img/refreshIcon.png')}
              />
            ),
          }}
        />
        <Stack.Screen name="MyModal" component={ModalScreen} />
        <Stack.Screen
          name="Fire Risk Assessment - Flats"
          component={RiskAssessmentListScreen}
          options={{headerBackTitle: 'Back'}}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default AppNavigator;

And my ModalScreen.js file:
import React from 'react'
import {View, Text, Button} from 'react-native'

export const ModalScreen = ({navigation}) => {
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text style={{fontSize: 30}}>This is a modal!</Text>
      <Button onPress={() => navigation.goBack()} title="Dismiss" />
    </View>
  );
}

A: The navigation prop is only available in the children of NavigationContainer.
What you are doing right now is you are accessing the navigation at the parent of NavigationContainer, so navigation is undefined.
There are a few ways to solve this:

*

*Move NavigationContainer up to your App.js or index.js, depending on your app structure.

*Pass a ref to NavigationContainer, and reference the ref for its methods, as shown in documentation.


text:
Q: Screen for Small Conference Room - Size and Resolution Questions I'll try to keep my questions generic so that it might help others in the future.
How should we go about choosing a screen for our conference room? What factors should we consider and what information or sites might help us choose the correct screen? Is it generally better or more affordable to use an overhead projector instead of a screen in a conference room?
Details Specific to Our Application:
We'd like to use this screen for basic video-conferencing. There will only be one person joining the conference room via video at a time. We also want to use the screen to view applications such as Excel Spreadsheets or MS Access application forms so that we can discuss application functionality and behavior.
I'm concerned that buying a standard computer screen could result in complaints about not being able to see, or more specifically, not being able to read the text or distinguish between controls in the application we might be looking at together. There will usually be about three to six viewers and they will be sitting anywhere from 6 to 15 feet away from the screen, some of them at a slight angle.

A: The general corporate staple screen is usually a 42" monitor with a minimum resolution of 1280x720 either mounted on a wall (sometimes multiple screens are used) or on a trolley.
It also depends on the size of the room - for bigger meetings the general preference is a ceiling mounted projector and a motorised retractable screen.
The prices of both options nowadays will be competitive so I suppose it's a question of preference. You can expect the monitor to be more durable as projector bulbs are fragile - and also projectors can be noisy too.


text:
Q: Calculate $P(A_n)$, where $P$ uniform distribution on $[0,1]$ $P$ uniform distribution on $[0,1]$.
$$A_n=\bigcup_{i=1}^{2^n-1} \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ], n \in \mathbb{N}$$
To calculate $P(A_n)$ do we have to do the following??
$$P(A_n)=P \left ( \bigcup_{i=1}^{2^n-1} \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ] \right )=\sum_{i=1}^{2^n-1}P\left ( \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ] \right )=\sum_{i=1}^{2^n-1} \left ( \frac{2i}{2^n}-\frac{2i-1}{2^n} \right )=\sum_{i=1}^{2^n-1}  \frac{1}{2^n} =\frac{1}{2^n} \sum_{i=1}^{2^n-1} 1=\frac{2^n-1}{2^n}$$
Is this correct?? Or is it as followed??
$$P(A_n)=P \left ( \bigcup_{i=1}^{2^n-1} \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ] \right )=\sum_{i=1}^{2^n-1}P\left ( \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ] \right )=\sum_{i=1}^{2^n-1} \frac{1}{\frac{2i}{2^n}-\frac{2i-1}{2^n}}=\sum_{i=1}^{2^n-1} 2^n=2^n(2^n-1)$$

A: Your first calculation is correct. Note that
$$\sum_{i=1}^{2^n-1}P\left ( \left [ \frac{2i-1}{2^n}, \frac{2i}{2^n} \right ] \right )=\sum_{i=1}^{2^n-1} \frac{1}{\frac{2i}{2^n}-\frac{2i-1}{2^n}}$$
does not hold; that's where your second calculation fails.
Remark: You can simplifiy the calculation by noting that
$$A_n = \left[ \frac{1}{2^n}, 1 \right].$$


text:
Q: Call angular service in another js file I have some javascript and html files: User.js, index.html, Door.js
I want use any function in User.js file.

*

*My user.js file

*My door.js file
I call getUserInfo in user.Js from Door.js file in function
doorApplicationLoginPage.service

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});

var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {

    UserService.getUserInfo();

});

Thank you.

A: You are injecting a service which is not referenced to your module.
See:
The UserService service is referenced in PerioLoginPage module
The PerioMainController controller is referenced in PerioDoorApplication module.
You've got either to:

*

*reference the service in the same module as your controller.

*inject the module where service is referenced to the module where controller is referenced.

A: In this case I can see you have two modules Periodicloginpage and periodicdoorapplication. So two services are defined in two modules. So you have to put the Periodicloginpage as dependency of periodicdoorapplication.
var doorApplication = angular.module("PerioDoorApplication", ["PerioLoginPage"]);

A: As I said in my comments you have two things to do at least:
You need to return the functions you want to use from the service (UserService):
return{
    getUserInfo: getUserInfo,
    reLoginUser: reLoginUser
};

Your module needs to reference the one the service is defined on:
angular.module('PerioDoorApplication', ['PerioLoginPage']);

And in your 'PerioMainController', a better way to write it would be:
doorApplication.controller('PerioMainController', ['$scope', '$http', '$sce', 'UserService',
    function($scope, $http, $sce, UserService){
        [...]
    }
]);


text:
Q: Typescript dual purpose array for type info and param? We have an API that can return a lot of data and therefore has a fields param to control which props are returned. Assuming this API definition:
interface Foo {
    A?: string;
    B?: number;
    C?: boolean;
    D?: string[];
    E?: number[];
}

We get code all over that does stuff like this:
// stripped-down definition local to a project
interface MyFoo {
    A?: string;
    C?: boolean;
}

const fields = ['A', 'C'];
...
const myFoo = await axios.get(... some url passing "fields" ...) as MyFoo;

I'd like to simplify all of that (and reduce risk of errors) by just basing all of that off the main API definition. That means using the same array of keys of Foo to construct a new type as well as using that array in the API call itself.
What I have so far:
declare function getFoo<T extends Foo, K extends keyof T>(fields: K[]): Pick<T, K>;

This gets me MOST of the way there:
const myFoo = getFoo(['A', 'C']);
type MyFoo = typeof myFoo; // type MyFoo = { A?: string; C?: boolean }

But is there any way to avoid the awkward two-step process here?
I tried something like ReturnType<typeof getFoo> but that gets the whole original definition since there's no way that I can see to pass the fields array into that.

A: Ok, I think I get what the issue here is. You are trying to use the type of myFields to create another type with Pick. The problem here is the type FooFieldsArray. By giving myFields the type FooFieldsArray any information about specific elements in the array is already lost.
You could instead use a generic function to initialise FooFieldsArray.
function createFields<T extends (keyof Foo)[]>(fields: [...T]){
    return fields
}

const myFields = createFields(["A", "C"]);
//    ^? const myFields: ["A", "C"]

Now this next line works too:
type foo = GetMyFoo<typeof myFields>
//   ^? type foo2a = { A?: string | undefined; C?: boolean | undefined; }

Playground

If you want to specify a seperate generic type for createFields, there is a problem. You will still need to infer the type of the passed tuple but since TypeScript does not have partial type inference, currying is the only option without code repetition here.
function createFields<T>() {
    return <F extends (keyof T)[]>(fields: [...F]) => fields
}
type GetObj<T, K extends (keyof T)[]> = Pick<T, K[number]>;

const fields = createFields<Foo>()(['A']);
type obj = GetObj<Foo, typeof fields>;

Playground


text:
Q: Explicit specialization of function templates causes linker error Functions.h:
#pragma once
#include <iostream>

template<class T> void TemplatedFunction(T* p) {}

template<> void TemplatedFunction<float>(float* p) {}

template<> void TemplatedFunction<char>(char* p) {}

Functions.cpp:
#include "Functions.h"

void Test()
{
    TemplatedFunction<float>(NULL);
    TemplatedFunction<char>(NULL);
}

main.cpp:
#include "Functions.h"
void Test();

int main()
{
    Test();
    return 0;
}

Build errors:
main.obj : error LNK2005: "void __cdecl TemplatedFunction<float>(float *)" (??$TemplatedFunction@M@@YAXPAM@Z) already defined in Functions.obj
main.obj : error LNK2005: "void __cdecl TemplatedFunction<char>(char *)" (??$TemplatedFunction@D@@YAXPAD@Z) already defined in Functions.obj

I know two ways to fix this:

*

*Don't include Functions.h to several .cpp files - cannot be applied in complicated project, if h-file contains some additional definitions needed in many .cpp files.

*Declare all templated functions as static. But this means that specialized functions appear in all .cpp files where Functions.h is included, even if they are not used, which possibly causes code duplication.
So, I see that specialized templated function behaves like non-templated function. Is there any other solution to prevent linker error without static declaration? If functions are declared static, does modern C++ compiler remove them from optimized build, if they are not used?
Edit.
After reading first two answers: I don't ask here how to prevent such linker error. Assuming that I cannot move specialization to .cpp file and leave it in .h file with static or inline, does this cause code duplication and bloating in optimized build, when these functions are added to every .cpp file where .h file is included, even if they are not used?

A: Such explicit specialisations should be moved to a .cpp file or made inline. The linker will find them there. If you define them in the header you will be getting "already defined" error messages just like you would get them for ordinary non-inline and non-static functions defined in a header included by multiple compilation units.

A:
So, I see that specialized templated function behaves like non-templated function.

Correct.

Is there any other solution to prevent linker error without static declaration?

Yes, like any normal non-template function:
Either Define the function specializations as inline
or Declare (but do not define) the specializations in the header:
template<> void TemplatedFunction<float>(float* p);

template<> void TemplatedFunction<char>(char* p);

and define them in Functions.cpp
template<> void TemplatedFunction<float>(float* p) {}

template<> void TemplatedFunction<char>(char* p) {}

These are better options than using static, because making the functions static has other side effects, such as giving the functions different addresses in each translation unit, and making local static variables different in every translation unit. That's a semantic change, not just a solution to the linker error.

If functions are declared static, does modern C++ compiler remove them from optimized build, if they are not used?

Yes. But in any files where they are used, you will get duplicate code, making the executable larger than if there was a single definition of the function.

Assuming that I cannot move specialization to .cpp file and leave it in .h file with static ...

I can't see any good reason why that would be necessary, but anyway ...

... or inline, does this cause code duplication and bloating in optimized build, when these functions are added to every .cpp file where .h file is included, even if they are not used?

No, if they are not used in a given file they will not affect the size of the object compiled from that file.
Your question is misleading because it appears to be about templates (the title is very clearly about templates!) but whether unused inline/static functions cause code bloat is independent of whether the functions are templates or not.
If your question is simply "do unused inline and static functions affect object size?" the answer is no, for both normal functions and function templates.


text:
Q: C++/CLI Wrapping a Function that Returns a std::shared_ptr I'm currently wrapping a C++ class with C++/CLI for .NET interoperability following the standard process of holding a native pointer in a managed class. In one instance, I have a native class that has a function like:
std::shared_ptr<BaseChannel> channelData(const int RunNumber);

I have already begun creating a wrapper class for BaseChannel. However, if I pass the raw pointer to the constructor of the managed class, there are no guarantees on the lifetime of the object being pointed to by the managed class. I.e. the shared_ptr could go out of scope and the object will get deleted and the managed class will be left holding a dangling pointer.
What is the common solution for this situation?
UPDATE
@Ben: So I wrap the class that holds the method in the above question like so (let's say it is in a native class called Node and it is being wrapped in a managed class called NodeRef:
ChannelUser^ NodeRef::ChannelData(int runNumber)
{
    // mpNode is native class pointer of type Node held in managed class
    // wrapper called NodeRef
    std::shared_ptr<BaseChannel> spBaseChannel = mpNode->channelData(runNumber);

    // ChannelUser is using clr_scoped_ptr to hold the shared_ptr
    ChannelUser^ channelUser = gcnew ChannelUser(spBaseChannel);
    return channelUser;
}

Because the shared_ptr does not have its reference count increased as it is passed to the managed class by reference, does that mean

that as long as this shared_ptr is in
  scope, the object it points to will
  still exist, because its reference
  count will be at least 1

? (ref C++ - passing references to std::shared_ptr or boost::shared_ptr)

A: shared_ptr is a native type, and managed objects can't have integral native subobjects.
However, as you note, managed objects can have pointers to native objects.  What you need is a pointer to a shared_ptr, which will count as a reference to the BaseChannel object and keep it from being freed prematurely.
Of course, there are lots of reasons to use a smart pointer instead of a raw shared_ptr<BaseChannel>*.  I've written a smart pointer which should be suitable, you can find it on codereview.stackexchange.com: "scoped_ptr for C++/CLI (ensure managed object properly frees owned native object)"

Example (not compile tested):
ref class ChannelUser
{
    clr_scoped_ptr<shared_ptr<BaseChannel>> chan_ptr;

public:
    ChannelUser( shared_ptr<BaseChannel>& chan ) : chan_ptr(new shared_ptr<BaseChannel>(chan)) {}
};

This automatically implements IDisposable and deletes the shared_ptr when Dispose or the finalizer runs, which in turn reduces the reference count on the BaseChannel.

A: Here's a managed shared_ptr<T>. You can assign to it directly from a shared_ptr and it'll take a copy that it will delete when the managed object is GC'd or disposed.
Examples:
m_shared_ptr<CupCake> cupCake0(new CupCake());
m_shared_ptr<CupCake> cupCake1 = new CupCake();
m_shared_ptr<CupCake> cupCake2 = shared_ptr<CupCake>(new CupCake());
m_shared_ptr<CupCake> cupCake3 = make_shared<CupCake>();
shared_ptr<CupCake> cupCake4 = (shared_ptr<CupCake>)cupCake3;

Code:
#pragma once

#include <memory>

template <class T>
public ref class m_shared_ptr sealed
{
    std::shared_ptr<T>* pPtr;

public:
    m_shared_ptr()
        : pPtr(new std::shared_ptr<T>())
    {}

    m_shared_ptr(T* t) {
        pPtr = new std::shared_ptr<T>(t);
    }

    m_shared_ptr(std::shared_ptr<T> t) {
        pPtr = new std::shared_ptr<T>(t);
    }

    m_shared_ptr(const m_shared_ptr<T>% t) {
        pPtr = new std::shared_ptr<T>(*t.pPtr);
    }

    !m_shared_ptr() {
        delete pPtr;
    }

    ~m_shared_ptr() {
        delete pPtr;
    }

    operator std::shared_ptr<T>() {
        return *pPtr;
    }

    m_shared_ptr<T>% operator=(T* ptr) {
        delete pPtr;
        pPtr = new std::shared_ptr<T>(ptr);
        return *this;
    }

    T* operator->() {
        return (*pPtr).get();
    }

    void reset() {
        pPtr->reset();
    }
};


text:
Q: How to make subsections not appear in the text? I have the following preamble and I want the subsection not to be visible in the
text.  Instead of Chapter 1 "Blah Blah" I only want "Blah Blah to be visible. With this code I did it bu the subsections are still visible in the text. e.g. 2.5 "blah blah".  How can I also remove 2.5 ??
\documentclass[a4paper,12pt]{book}
\usepackage{titlesec}

\titleformat{\chapter}[display]{\normalfont\huge\bfseries}{}{20pt}{\Huge}

\let\cleardoublepage\clearpage
\usepackage[english,greek]{babel}
\usepackage[utf8x]{inputenc}
\usepackage{blindtext}
\usepackage[pdftex]{graphicx}
\usepackage[skip=2pt, font=small, labelformat = empty]{caption}

\newcommand{\gr}{\selectlanguage{greek}}
\newcommand{\en}{\selectlanguage{english}}
\usepackage{wrapfig}
\usepackage[paperwidth=17cm, paperheight=24cm]{geometry}

\usepackage[onehalfspacing]{setspace}
\usepackage{textcomp}
\useshorthands{;}
\defineshorthand{;}{?}
\usepackage{fancyhdr}
\fancyhf{}
\fancyhead[LE]{\nouppercase{\leftmark}}
\fancyhead[RO]{\nouppercase{\rightmark}}
\fancyfoot[LE,RO]{\thepage}
\pagestyle{fancy}

\renewcommand{\chaptermark}[1]{ \markboth{#1}{} }
\renewcommand{\sectionmark}[1]{ \markright{#1}{} }

A: No need to use titlesec for this. The easiest way to get all sectional units unnumbered is to set secnumdepth to -2 (or to -1 if parts should be numbered):
\documentclass{book}

\setcounter{secnumdepth}{-2}

\begin{document}

\chapter{Test chapter}
\section{Test section}
\subsection{Test subsection}
\subsubsection{Test subsubsection}

\end{document}


text: Q: Trifilar pendulum Time period The conical frustum for which moment of inertia was calculated using a Trifilar Pendulum is made of wood (density = 0.7 g/cc). If iron is used instead and dimensions of the frustum are kept same, will the time period of oscillation of the pendulum increase?


text:
Q: Is bootstrap.js specifically a library or a plugin or something else? Is bootstrap.js specifically a library or a plugin or can be classified as something else?

A: It's a CSS or Front-end framework ;-)
"Bootstrap is a free and open-source collection of tools for creating websites and web applications. It contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions. As of March 2015, it was the most-starred project on GitHub, with over 78,000 stars and more than 30,000 forks.[2]"
http://en.wikipedia.org/wiki/Bootstrap_(front-end_framework)
Difference between API's, Plug-In and Framework :
http://collap.com/challengesOpen.php?challenge_id=715


text:
Q: Fallback routing in OpenVPN In an effort to be a little environmental friendly I want to setup two connections between my home network and my VPN server.
My VPN server is running Ubuntu 16.04.
The default is my Raspberry Pi box is routing all traffic from my home network to to the VPN server.
However: I want that my desktop computer takes over routing for my network, whenever it is powered on, due to the fact that it can transmit data 10 times faster over VPN than my Raspberry Pi.
It has to fallback to the Rasberry again, when the desktop computer is powered off.
Im sitting on a 300 Mbps connection at home and my VPN server is connected to the Internet via a 10 Gbps connection. ;-)

My question is: Can all routing be done from OpenVPN or do I need to make a client connect/disconnect script that fiddle with policy based routing?

A: Bit of an off-topic answer but... I think you're doing it all wrong.
Don't use a Raspberry Pi for networking.
As you're realising the networking potential of the Raspi is terminally stunted. The ethernet port on a the Raspi3 is only 100mbps. In perfect conditions you can get ~250mbps over USB Ethernet adaptors and the wifi is pretty pap too. Add in all the CPU time for handling encryption and I'd be surprised if you were getting anything near even 30mbps.
OpenVPN is slow and bloated, use WireGuard.
For a point-to-point VPN where you don't have to corral all the hosts into being compatible, use WireGuard. There's a official PPA. It's just a lot faster, and a lot less resource intensive than OpenVPN.
There's only so far I can walk you with this, test it between your desktop and VPN server.
Get a better router that can do all this for you.
Get rid of the Raspi and get a router that supports OpenWRT. We use VDSL2 here so I got a "BT Home Hub 5" with OpenWRT pre-installed for ~£20. They give these things out to new customers so they're artificially cheap and available.

*

*It uses comparable amounts of power to a Raspi3 (probably less)

*You need a router anyway, you're just replacing your current one (saving more power)

*It's built for gigabit networking throughput.

*You can install Wireguard directly into OpenWRT. It can handle your VPN connection, firewall rules, etc. Forever without any switcheroo.

The hardware you need may vary to mine but don't get pulled into the £300 super-routers that ASUS (et al) make. You can usually spot these a mile off because they look like porcupines with their antennae.
If you need good wifi, buy PoE access points and put them where you actually need them. It's cheaper both initially and when you decide you need 802.11z in two years time.


text:
Q: $T_n$ an unbiased estimator of $\psi_1(\lambda)$? Prove your answer. (Exponential distribution) Q) Let $(x_1, x_2, \cdots, x_n)$ be an observed sample from an exponential($\lambda$) distribution. Note: Exponential($\lambda$) distribution has probability density function $f(x) = \lambda e^{-\lambda x}$ for $x \geq 0$ and zero otherwise. It can be shown that $T_n = \bar{X}$ is an maximum likelihood of $\psi(\lambda) = \frac{1}{\lambda}$
(a) Is $T_n$ an unbiased estimator of $\psi_1(\lambda)$? Prove your answer.
$$E(T_n) = E(\bar{X}) = E(X_1) = \frac{1}{\lambda} = \psi_1(\lambda)$$
(b) Is $U_n = \bar{X}^2$ an unbiased estimator of $\psi_2(\lambda)$? Prove your answer.
$$E(U_n) = E(\bar{X}^2) = V(X) + E(X)^2 = \frac{1}{n}V(X_1) + E(X_1)^2 = \frac{1}{n\lambda^2} + \frac{1}{\lambda^2} \neq \frac{1}{\lambda^2}$$ so no
(c) Is $U_n = \bar{X}^2$ an asymptotically unbiased estimator of $\psi(\lambda) = \frac{1}{\lambda^2}$. Prove your answer.
$$\lim_{n\to\infty} E(U_n) = \lim_{n\to\infty} \left(\frac{1}{n\lambda^2} + \frac{1}{\lambda^2} \right) = \frac{1}{\lambda^2} = \psi_2(\lambda)$$
(d) An observed sample of ten observations from this distribution had mean $\bar{x} = 0.6$. Use this information to calculate the standard error of $T_n = \bar{X}$.
$Var(T_n) = V(\bar{X}) = \frac{1}{n}V(X_1) = \frac{1}{n\lambda^2}$
MLE of $\lambda = \frac{1}{\bar{x}} = \frac{1}{0.52}$ so
$var(T_n) = \frac{1}{n\lambda^2} = \frac{1}{4  (0.52)^2} = 0.0676$
$SE(X) = \sqrt{V(T_n)} = 0.26$
Is this correct?

A: Your reasoning, while largely correct, lacks rigor.
In (a), you state without proof $$\operatorname{E}[\bar X] = \operatorname{E}[X_1].$$  While true, you do not explain why it is true.  The reason is due to linearity of expectation and the fact that the $X_i$ are identically distributed:  $$\operatorname{E}[\bar X] = \operatorname{E}\left[\frac{1}{n} \sum_{i=1}^n X_i\right] = \frac{1}{n} \sum_{i=1}^n \operatorname{E}[X_i] = \frac{1}{n} \sum_{i=1}^n \operatorname{E}[X_1] = \frac{1}{n} \cdot n \operatorname{E}[X_1] = \operatorname{E}[X_1].$$  We used linearity in the second equality from the left, and we used the identically distributed property of the $X_i$ in the third equality from the left.  Technically, one does not need that that $X_i$ are identically distributed, since all that is required is that $\operatorname{E}[X_i] = 1/\lambda$ for each $i = 1, 2, \ldots, n$ for the claim $\operatorname{E}[\bar X] = 1/\lambda$ to be true.
In (b), you make the assertion $$\operatorname{E}[\bar X^2] = \operatorname{Var}[X] + \operatorname{E}[X]^2$$ without proof.  This is not correct, unless you meant to write $$\operatorname{E}[\bar X^2] = \operatorname{Var}[\bar X] + \operatorname{E}[\bar X]^2.$$  If you meant the latter, then the following step requires substantiation along the same lines as in (a); namely $$\operatorname{Var}\left[\frac{1}{n} \sum_{i=1}^n X_i\right] = \frac{1}{n^2} \sum_{i=1}^n \operatorname{Var}[X_i] = \frac{1}{n^2} \sum_{i=1}^n \operatorname{Var}[X_1] = \frac{1}{n} \operatorname{Var}[X_1],$$ where the first equality holds due to independence of the $X_i$, and the second due to the $X_i$ being identically distributed.
(c) is correct.
(d) seems to have some inconsistencies.  Is $\bar x = 0.6$, or is $\bar x = 0.52$?  Which one?  Also, is $n = 10$, or is $n = 4$?
In any case, the estimate of the standard error of the sample mean is given by $$\operatorname{SE}[\bar X] = \sqrt{\widehat{\operatorname{Var}}[\bar X]}.$$  From part (b) above, we know that $$\operatorname{Var}[T_n] = \frac{1}{n}\operatorname{Var}[X_1] = \frac{1}{n \lambda^2} = \frac{1}{n} \cdot \operatorname{E}[\bar X]^2.$$
This suggests that an appropriate choice would be
$$\widehat{\operatorname{Var}}[\bar X] = \frac{\bar X^2}{n} = \frac{U_n}{n}.$$ This is by no means the only possible choice for the estimated variance of $\bar X$, since $U_n$ is biased.  To compensate, you could note $$\operatorname{E}\left[\frac{n}{n+1} U_n\right] = \frac{n}{n+1} \left( \frac{1}{n\lambda^2} + \frac{1}{\lambda^2} \right) = \frac{n}{n+1} \left( \frac{1}{n} + 1 \right) \frac{1}{\lambda^2} = \frac{1}{\lambda^2}$$ is unbiased, so an unbiased estimator for the variance of the sample mean would be $U_n/(n+1)$.


text:
Q: how to use linked animated css? I am trying to use animate.css
<link rel="stylesheet" href="animate.css" type='text/css'>

which is this:
.animated {
    -webkit-animation-duration: 2s;
    -moz-animation-duration: 2s;
    -o-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-fill-mode: both;
    -moz-animation-fill-mode: both;
    -o-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes wobble {
    0% {
        -webkit-transform: translateX(0%);
    }
    15% {
        -webkit-transform: translateX(-25%) rotate(-5deg);
    }
    30% {
        -webkit-transform: translateX(20%) rotate(3deg);
    }
    45% {
        -webkit-transform: translateX(-15%) rotate(-3deg);
    }
    60% {
        -webkit-transform: translateX(10%) rotate(2deg);
    }
    75% {
        -webkit-transform: translateX(-5%) rotate(-1deg);
    }
    100% {
        -webkit-transform: translateX(0%);
    }
}
@-moz-keyframes wobble {
    0% {
        -moz-transform: translateX(0%);
    }
    15% {
        -moz-transform: translateX(-25%) rotate(-5deg);
    }
    30% {
        -moz-transform: translateX(20%) rotate(3deg);
    }
    45% {
        -moz-transform: translateX(-15%) rotate(-3deg);
    }
    60% {
        -moz-transform: translateX(10%) rotate(2deg);
    }
    75% {
        -moz-transform: translateX(-5%) rotate(-1deg);
    }
    100% {
        -moz-transform: translateX(0%);
    }
}
@-o-keyframes wobble {
    0% {
        -o-transform: translateX(0%);
    }
    15% {
        -o-transform: translateX(-25%) rotate(-5deg);
    }
    30% {
        -o-transform: translateX(20%) rotate(3deg);
    }
    45% {
        -o-transform: translateX(-15%) rotate(-3deg);
    }
    60% {
        -o-transform: translateX(10%) rotate(2deg);
    }
    75% {
        -o-transform: translateX(-5%) rotate(-1deg);
    }
    100% {
        -o-transform: translateX(0%);
    }
}
@keyframes wobble {
    0% {
        transform: translateX(0%);
    }
    15% {
        transform: translateX(-25%) rotate(-5deg);
    }
    30% {
        transform: translateX(20%) rotate(3deg);
    }
    45% {
        transform: translateX(-15%) rotate(-3deg);
    }
    60% {
        transform: translateX(10%) rotate(2deg);
    }
    75% {
        transform: translateX(-5%) rotate(-1deg);
    }
    100% {
        transform: translateX(0%);
    }
}
.animated.wobble {
    -webkit-animation-name: wobble;
    -moz-animation-name: wobble;
    -o-animation-name: wobble;
    animation-name: wobble;
}

And HTML:
yo

And then Jquery:

$(document).ready(function(){
$(".yo").click(function() {
         $(this).addClass('animated wobble');
});
});

But when I click on yo it changes the classes (so I know the jquery is working) but nothing happens. I have also added a class to the css and changed the font colour and it works (so I know that the link is working properly) But still no wobble animation when I click?

A: I believe you need specify which animation gets called. Try adding this to your animated class:
.animated {
   -webkit-animation-name: wobble;
   -moz-animation-name: wobble;
   -o-animation-name: wobble;
   animation-name: wobble;
}

Wobble isn't a classname, it's just the name of your animation, so you can remove the wobble addClass in your jQuery.
EDIT: Looks like I didn't read all your CSS. Try moving your
.animated.wobble{} section right up underneath the .animated{} section.


text:
Q: switch load depending on battery voltage I have the following set up;

simulate this circuit – Schematic created using CircuitLab
MPPT charge controller: https://www.sparkfun.com/products/12885
Load: Raspberry Pi Zero
Battery is: http://ie.farnell.com/webapp/wcs/stores/servlet/ProductDisplay?catalogId=15001&urlLangId=353&langId=353&partNumber=2484233&storeId=10163#techDocsHook
Battery Datasheet: http://www.farnell.com/datasheets/2017383.pdf?_ga=2.166173694.1332281990.1495362248-227627644.1495362211
The battery datasheet states:
Over discharge detection voltage: 2.5V
Over discharge release voltage: 2.85V
Release condition: cut load, release after charging up
What happens is that the load at night drains the battery to 2.5V thus triggering the protection circuitry, upon daylight the battery does not charge nor does the load power up from the MPPT charge controller.
The only way to overcome this is to physically disconnect the battery from the MPPT controller and all works fine again. I assume then that the battery is getting stuck via it's charge protection circuitry.
I want to avoid the above battery low voltage triggering & manual intervention.
Can someone suggest a circuit/solution that will provide power to the battery & load when there is voltage from the MPPT and disconnect the load when the battery voltage drops to say 2.8v and reconnect the load when the battery voltages charges to say 4V?
How can I implement the following switch in circuitry?

simulate this circuit

A: The function that you describe is commonly performed by a comparator circuit which typically a specialized version of an op-amp. The circuit works by comparing the monitored voltage to a reference voltage (typically from a zener). When the voltage falls below the set point that is programmed with a simple resistive divider network, the output of the comparator changes state.
The ability of a comparator to change state at one voltage but not revert back until a higher (or lower as the case may be) voltage is measured is called hysteresis. You have asked for 1.2 volts (4.0 - 2.8 volts) of hysteresis although you could probably get by with much less hysteresis.
In your case the comparator circuit must at all times be powered by the battery it is trying to protect so you need a very low power comparator. The output of the comparator could drive a MOSFET switch that disconnects the load from the battery when the comparator trips.
There are many low power comparators on the market, some of which are integrated into brown out protection devices and other special functions. Take a look at the spec sheet for the LTC1540 (here). This is an ultra low current device that includes the zener voltage reference source and it can operate down to a 2 volt supply. This IC with two divider resistors and a MOSFET should suit your application.


text:
Q: Focus lost in IE when element is set to hidden and then visible in the same function We have a piece of code that sets a container element's visibility to hidden, do something to its children, then set the visibility back to visible. It works well in Modern browsers, but in IE the input elements inside the container lose focus after execution.
To demo this situation, say we have:
<div id="container">
  <input id="input"/>
</div>

if you do:
var containerEl = document.getElementById('container');
var inputEl = document.getElementById('input');
inputEl.focus();
containerEl.style.visibility = 'hidden';
containerEl.style.visibility = 'visible';

The input element is in focus in Chrome. It loses focus in IE.
See This Demo
I am using latest Chrome66 and IE11 when testing.
So, why
containerEl.style.visibility = 'hidden';
containerEl.style.visibility = 'visible';

makes the focused input lose its focus in IE?