text:
Q: How to develop complex applications I want to know the approach in developing big complex application regardless of which programming language to use. I want to know how developers make such big applications such as internet banking, API's and big database management application. How should one approach to make  such applications. I have only 1 year programming experience so far and I work as a freelancer so when I saw such applications lots of questions came in my mind. How to understand the basic need of information technology. What actually it is? How it can be useful for common people of small towns. I want everyone to make use of technology no matter they are educated or not, rich or not. Please post some suggestions.

A: In one word: Modularity.
You build large software systems by composing them from smaller building blocks.  You do that by using techniques such as Object Orientation.  Each object is a complete, testable software unit in its own right.  When combined, each of these objects communicates messages between itself and other objects, creating a complete, coherent system.
Getting good at this takes awhile, because you have to figure out what each object is responsible for, and how it fits in with the rest of the system.
Think about how a car is built.  A car is a system, composed of smaller subsystems like the engine, the electrical and fuel systems.  The engine, in turn, is built up from components like the pistons, crankshaft and valves, and it is supported by an ignition system, a cooling system and a lubrication system.  The ignition system has spark plugs, wires, a coil, etc.  While the entire system is enormously complex, nothing is particularly difficult to understand if you look at its components, and how they work together.
Software works the same way.  You have methods, variables and keywords inside classes.  You instantiate objects from these classes.  You have objects that are factories that can create other objects, objects that manipulate collections of other objects, object that act as proxies, and so forth.
You learn how to build these larger systems by learning how to write smaller programs (or smaller parts of larger systems) first, and then combining those smaller parts into larger systems.

A: What you're talking about are the concepts of Software Engineering. It's difficult to really condense all you need to know into a single SO comment, when there are series of books written on the subject and it is indeed a field of its own. Here's some books you can look into to get you started, and coupled with your education should set you on the right path:

*

*Code Complete: A Practical Handbook of Software Construction

*The Pragmatic Programmer: From Journeyman to Master

*Design Patterns: Elements of Reusable Object-Oriented Software

*Refactoring: Improving the Design of Existing Code

A: First of all you should Ignore Coding until you fully understand the Requirements.
The phases of software development

*

*Requirement Analysis : is the very first phase of project development and the most important one. You need to write down what is the requirement of the client, the users and the project itself. Take as much time as you want before proceeding to the later stages. Because if this phase is misunderstood, you might need to run back and from between phases

*Design & Architecture : This is the phase where you put your requirements at work. Draw sketches of application flow, pen down the algorithms for carrying out functions. Make a nice wireframe or outlining as to how the application will look. In short consider how every requirement will be met and foreseen. Also, a good designer or architect will take into account the future expansion so you should consider that too

*Coding : The part where the results can be seen. Choose any language you are comfortable with and start coding. Coding is not the hardest part and need not take as much time as Analysis or designing but this is the part you, your users and clients are concerned with. Write code as neat as possible applying different coding practices and make sure your leave less spots for the testing phase to clean up

*Testing : Last but not the least important phase. Testing mostly takes more time than coding because you test your code against all circumstance ranging from user input to load performance. A thorough testing will always lead to a better product

A: This is a very wide question, with no one ready-made answer. I'll try to answer nonetheless, but my answer will be as vague as the question. I'll assume nonetheless that you are asking about how to build a large app on your own or with a colleague. Large teams are something totally different.

*

*Careful Planning: List everything the app needs to do, trim the unneeded. Then trim gain. Keep trimming. Also, list all the tasks you have to do and break them in sub-tasks

*Plan everything in different sections. I do it in this order:

*

*I list all the main "objects" of my app. For example, books, pages, authors, users, with their properties, relations, and actions

*I do the database design

*I design the roles of the users, implement this in my "objects" sheet and my "database design" sheet

*I describe all the main classes I will need, in quick pseudo-code

*I wireframe the design (quick sketches)

*I create a quick mockup with as little code as possible, as functional as possible

*If you are on your own, you will want to keep the whole process loose and sketchy. Allow for changes, specially early on. You will NOT think of everything, so leave room for all the things unplanned that you will stumble on on the way.

*To that effect, create you app in a modular way, with components as decoupled as possible. This makes it easier to maintain, debug, and test. I learned this the hard way as I was creating a monolithic framework, stopped working on it for a few weeks, then was totally lost in my own code. So think "plugins"

*Begin with the bare essential, test, let your friends use it, see what's needed, analyze, dig out the few essential features, implement. Rinse and repeat.

*Read getting real by 32 signals.

*Have some sort of version control. I personally like mercurial, but whatever is fine. Just have one.

*Test different languages, don't get stuck on one. Pick one functional, one object-oriented language, you will learn from each.

*Stick to a language until you master it completely (contradictory yeah I know). When you will want to create mockups, begin with this language, at least you will be able to work fast.

Above all, read, read, read, and apply, apply, apply, create your own stuff and push forward for more optimized code, better standards, and whatever the language you choose, try to push it to the max. And don't listen to the "don't reinvent the wheel" thing. DO reinvent the wheel, just not when you are working for a client. If you are on a professional project, use whatever you can to make it work. But on your personal projects, build everything from the ground up. Then look up the source of similar projects and see how they did it.
Then throw everything away because what you did is most likely going to be crap the first 100 times. Rinse and repeat.
Practice makes somewhat better, after a few years (2 to 4), you should be able to manage even a very large project by yourself. But you have to be wanting to do it from day one. If you only try to build little stuff for 4 years, you won't get there.
Try to manage to have a life beside all that, because fresh air, friends and going out make it all better.

A: There are different kind of complexity, usually two types, a complexity caused by the addition of stuff that doesn't strictly belongs to our purpose or the nature of what are you doing ( like when you add some lines of code later on just to add some functionality that you didn't have planned to give to your app ), and what is usually called "the complexity of engineering" that means that the system that you have to design probably requires a lots of elements and many connections between those just to run.
The thing is that you can't really face this kind of problems without a solid base that only a college degree can give to you. We are talking about an intensive use of the math, basic and high level notions about both the hardware and the software.
What you can easily understand is the use of some good companion like the UML language that is really useful and powerfull especially during the design process, without talking about any specific languages you just can have a big picture in front of you. Other good things are the versioning systems like Mercurial and Git that are especially used when you are working in team with other people, you can also browse every IDE is made for your language and decide what is the most appropriate for your needs.
But this are only tips, you have to build your know-how reading some books and applying something in the real world, a good book for a start can be one about algorithms and data structure.
A good language to start from is Java, a good Java project with a good design can be Android with its own system classes; try to learn Java and analyze the design of this big project in UML to begin to understand what it's like to design a very big project and what you have to care about. The design it's all about how different languages can have the same business logic and what the user is allowed to know and do, and with some languages you also have to care about some performance issues but this is something that you can learn in a college not on the internet.

A: I would have a look to an existing similar project and see if it works well. You do't need the full code but java executable jar file could also be reversed. Be aware you are not allowed to reverse jar file in US, but you can do it in Europe and other countries so..
If the architecture is ok, then copy the static architecture (e.g. package, classes etc....) and then just code the business rules. A good start is to reverse engineer the existing project into an UML model and then generate again the code in java. There is no more code copyright if you do that.
Once you have a static architecture you check if the requirements are possible and add new classes at class diagram level. You show your class diagram to the project manager and talk about the architecture. Once this is validated then you start codding.
After the first stage codding you show the class diagrams and a small demo and ask the project manager if it is ok. You take into consideration his demands. You always use a graphical representation of your code in order to get all the team involved in decisions and possible changes.
One more iteratiion, class diagrams updated with a code merge and manager demo. Change again and again. After few week it will almost be perfect and everybody will be happy :-)

A: Your question is a big question include many aspect.
But I think the first you should be understand good and bad which each language and what`s situation best of this language using.
And then according to business requirement to decide which language you could use.
And next you should be understand this language about detail.


text:
Q: Slack Private Messages: Export or Forward DM's I would like to automatically forward or export all private messages I receive from a NEWS BOT in Slack.
It can be forwarded to email, webhook, telegram or just exported in JSON, doesn't matter.
I tried creating a bot using Slack' events, but it can't listen to my private messages.
What's the best way to achieve this?
PS: using channels won't work, as the NEWS BOT only sends me the updates via DM.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to track the permissions given by multiple TFS Admins? We are using TFS 2015 U3, and we are totally of 2 Admins.
We have given permissions to many users and would like to track who is given accesses to whom? and what time we have provided access?
Is there any way to find out the log?
Thanks,
Sat

A: No, we can only get the information on who managed the permissions from Activity Log, but can not track giving the accesses to whom. (The related records can not be found even in the database)
To check the Activity Log.

*

*Go to http://server:8080/tfs/_oi

*Select the specific Collection, enter the specific Account (Admin
user account) in Identity Name area to filter the Activity log.

*Find the command ApiSecurity.ManagePermissions -> Show Details


text:
Q: python .txt file is identifying one letter at a time instead of a word in a .txt first i wold like to say im a very basic programmer so if you can please try not to be complicated however anything is helpful.
I have a .txt file to define a keyword list eg:
pig,dog,cat

My real list is much bigger but has the same format.
I want the user to input something and if the program detects one of the words which the user imputed and what the .txt file has it common it will give a response. If it doesn't find one of the words if gives a different response.
start_question = str(input("keywords are pig , cat , dog "))

with open('D:\Program Files (x86)\Python Programming\python.txt'):
   if any(word in start_question for word in ('D:\Program Files (x86)\PythonProgramming\python.txt')):
   print ("yes")

else:
    print ("no")

Now the file successfully opens but instead of finding words in comomon it finds letters in common. So if i input 'p' it will still say 'yes' however i want it to say no.
Thankyou.

A: You're looking through the string of the file path, not the contents.
To loop through the file, you'd want to do something like this:
with open('D:\Program Files (x86)\Python Programming\python.txt') as fl:
  if any(word in start_question for word in fl):
      print("yes")
  else:
      print("no")

But there is another problem, too. If your file is:
cat,dog,pig

And your input is cat, then you'll always get no.
Why?
Because you're looking for contents of lines in a file. This means you're seeing
if any('cat,dog,pig' in 'cat')

That doesn't work.
You'll need to format your file:
cat
dog
pig


text:
Q: Can I get a faunaDB document's json data in one shot with Go API? With Go API of faunaDB, I can define a struct to post the founaDB as follows:
type LabelData struct {
    RedirectURL   string `fauna:"redirectURL"`
    Owner         string `fauna:"owner"`
    RedirectCount int    `fauna:"redirectCount"`
}

Then I can call Create for the Label Data struct in one shot with the labelData as follows:
    labelData := LabelData{
        RedirectURL:   "",
        Owner:         "",
        RedirectCount: 0,
    }
    newlabel, _ := client.Query(
        f.Create(
            f.Collection("label"),
            f.Obj{"data": labelData},
        ),
    )

My question is, can I get the data of document which created above in one shot to the LabelData type valuable? Currently, I'm getting it to each element of LabelData type as follows:
func faunaLabelInfo(id string) (owner string, redirectCount int, redirectURL string, err error) {
    var data f.Value
    ret, err := client.Query(f.Get(f.RefCollection(f.Collection("label"), documentID)))
    err = ret.At(f.ObjKey("data")).Get(&data)
    err = data.At(f.ObjKey("owner")).Get(&owner)
    err = data.At(f.ObjKey("redirectCount")).Get(&redirectCount)
    err = data.At(f.ObjKey("redirectURL")).Get(&redirectURL)

I've expected as follows, but it's wrong.
var labelData LabelData
ret.At(f.ObjKey("LabelData")).Get(&labelData)

Thank you for your suggestion!

A: i made full working example based on docker (docker run --rm --name faunadb -p 8443:8443 fauna/faunadb):
package main

import (
    "fmt"

    f "github.com/fauna/faunadb-go/faunadb"
)

type LabelData struct {
    RedirectURL   string `fauna:"redirectURL"`
    Owner         string `fauna:"owner"`
    RedirectCount int    `fauna:"redirectCount"`
}

var (
    data = f.ObjKey("data")
    ref  = f.ObjKey("ref")
)

func main() {
    var labelId f.RefV
    config := f.Endpoint("http://localhost:8443")
    client := f.NewFaunaClient("secret", config)
    labelData := LabelData{
        RedirectURL:   "",
        Owner:         "",
        RedirectCount: 0,
    }
    // Create a collection to store labels
    _, _ = client.Query(f.CreateCollection(f.Obj{"name": "label"}))

    newlabel, err := client.Query(
        f.Create(
            f.Collection("label"),
            f.Obj{"data": labelData},
        ),
    )
    if err != nil {
        return
    }

    // Get generated label ID
    _ = newlabel.At(ref).Get(&labelId)
    fmt.Println(labelId)

    // Retrieve label by its ID
    value, _ := client.Query(f.Get(labelId))

    var newLabelData LabelData
    _ = value.At(data).Get(&newLabelData)
    fmt.Println(newLabelData.RedirectURL)
    fmt.Println(newLabelData.Owner)
    fmt.Println(newLabelData.RedirectCount)
}


text:
Q: Xcode 10.0: Failed with exit code 1
CopySwiftLibs /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app (in target: codeChecker)
    cd /Users/90301207/Desktop/IOS\ Development/IOS\ Projects/codeChecker
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
    export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk
    builtin-swiftStdLibTool --copy --verbose --sign AC89DB35766AAF3EAFB57F70F3F3167E4AC07C96 --scan-executable /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/codeChecker --scan-folder /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks --scan-folder /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/PlugIns --platform iphoneos --toolchain /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain --destination /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks --strip-bitcode --resource-destination /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app --resource-library libswiftRemoteMirror.dylib --strip-bitcode-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/bitcode_strip --emit-dependency-info /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Intermediates.noindex/codeChecker.build/Debug-iphoneos/codeChecker.build/SwiftStdLibToolInputDependencies.dep

Requested Swift ABI version based on scanned binaries: 6
libswiftObjectiveC.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib
libswiftCoreImage.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftCoreImage.dylib
libswiftUIKit.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftUIKit.dylib
libswiftMetal.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftMetal.dylib
libswiftCore.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftCore.dylib
libswiftFoundation.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftFoundation.dylib
libswiftos.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftos.dylib
libswiftCoreGraphics.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftCoreGraphics.dylib
libswiftDarwin.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftDarwin.dylib
libswiftDispatch.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftDispatch.dylib
libswiftCoreFoundation.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftCoreFoundation.dylib
libswiftQuartzCore.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftQuartzCore.dylib
libswiftRemoteMirror.dylib is up to date at /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/libswiftRemoteMirror.dylib
Probing signature of /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib
/usr/bin/codesign -r- --display /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib
/Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib: code object is not signed at all

Codesigning /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib
/usr/bin/codesign --force --sign AC89DB35766AAF3EAFB57F70F3F3167E4AC07C96 --verbose /Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib
/Users/90301207/Library/Developer/Xcode/DerivedData/codeChecker-hcddnntogbbtbqecesokhznmpcsq/Build/Products/Debug-iphoneos/codeChecker.app/Frameworks/libswiftObjectiveC.dylib: errSecInternalComponent

error: Failed with exit code 1

This error keeps throwing for any of my apps when I try to run them on my iPhone 7 or iPad 6

A: It seems like you having an Code Signing issue. Try check "Automatically manage signing", clean and build the project and try again.
Screenshot


text:
Q: Suprema and infima on a partially ordered set This is Exercise 6 from page 28 of Analysis I by Amann and Escher. I have searched for "supremum union" on this site and there are a number of similar questions but they all seem to assume some extra structure that I can't justify.
Exercise:

Comments:
I have made almost no progress. Some of the similar questions on StackExchange involve the real numbers, or proofs that for example $\sup(A \cup B) = \max \{ \sup(A), \sup(B) \}$, neither of which are applicable here. Some other questions involve proving that certain sets are bounded, which doesn't seem relevant when all the suprema and infima are assumed to exist.
One thing that I feel is paralyzing me is that because this is a partially ordered set, I can't necessarily compare any two elements. Since $A$ is bounded above I can presumably use the relation $\leq$ on an upper bound $s$ of $A$ and every $a \in A$. But I can't, for example, necessarily compare $s$ with an upper bound $t$ of $B$.
I'm starting to think that, for part (a) at least, I should pursue a strategy along the lines of showing that $\sup(A \cup B) \leq \sup \{ \sup(A), \sup(B) \}$ and then $\sup(A \cup B) \geq \sup \{ \sup(A), \sup(B) \}$. Is that reasonable?
I appreciate any help.

A: Your final paragraph outlines a perfectly reasonable strategy for (a). So let's do that. And remember the defining property of $\sup$ (and analogously for $\inf$): It is the least upper bound, meaning all other upper bounds are larger. So any inequality of the form $\sup(X) \leq t$ is best proven by showing that $t$ is an upper bound for $X$.

*

*$\sup(A\cup B)\leq \sup\{\sup(A), \sup(B)\}$: Let $x = \sup\{\sup(A), \sup(B)\}$, and take an element $a\in A\cup B$. Either $a\in A$, which means $a\leq \sup(A)\leq x$, or $a\in B$, which means $a\leq \sup(B)\leq x$. Either way we get $a\leq x$. This means $x$ is an upper bound for $A\cup B$.

*$\sup(A\cup B)\geq \sup\{\sup(A), \sup(B)\}$: Clearly, by using (b) ("larger set means larger $\sup$"), we have $\sup(A\cup B)\geq \sup(A)$, and just as clearly $\sup(A\cup B) \geq \sup(B)$. Thus $\sup(A\cup B)$ is an upper bound for $\{\sup(A), \sup(B)\}$.

The $\inf$ proof is entirely analogous, except we flip all the inequality signs, and change "upper" into "lower" (same goes for (b) and (c) as well).
Now for (b). This time there is only one inequality. It's rather simple to prove, though, using the defining property: We have that $\sup(B)$ is an upper bound for $B$, so it must be an upper bound for $A$.
The proof for (c) is very similar to half the proof for (a): again by using (b), clearly $\sup(A\cap B)\leq \sup(A)$, and just as clearly, $\sup(A\cap B)\leq \sup(B)$. Thus $\sup(A\cap B)$ is a lower bound for $\{\sup(A), \sup(B)\}$. (One could go the other way too, showing that $\inf\{\sup(A), \sup(B)\}$ is an upper bound for $A\cap B$. That would be more akin to the other half of the proof of (a). This time there isn't equality, because the two halves show the same inequality, rather than opposite inequalities the way they did in (a).)
Finally, we have (d). They give one hint as to what you could look at, but I like to do it simpler. Let us say our partially ordered set has three elements, two are incomparable, and the third is larger than both (the power set on a set of two elements yields a similar example). Then let $A$ and $B$ each consist of one of the two incomparable elements. Then the set $\{\sup(A), \sup(B)\}$ has no maximum as its elements are incomparable, by design.


text:
Q: 0xC0000005: Access violation writing location 0x0000000000000008 I have this simple project that uses imagemagick on windows:
#include <Magick++.h>
#include <iostream>

using namespace std;
using namespace Magick;

int main() {
    cout << "Hello, World!" << endl;
    string inputFileName =
        "D:\\magick\\pic2.jpg";
    string outputFileName = "D:\\magick\\pic_resized.png";
    int width = 800;
    int height = 600;

    try{
        Image image;
        image.read(inputFileName);
        Geometry geometry(width, height);
        geometry.aspect(false);
        image.resize(geometry);
        image.write(outputFileName);
        Blob b;
        image.write(&b);
        cout << "data size is " << b.length() << endl;
    }
    catch (...) {
        cout << "error occurred";
    }
    return 0;
}

When I run it, I get an exception at the line image.read(inputFileName);:
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.

I read online that this exception is due to missing dlls, but I don't understand what is this missing dll?
I am using cmake and already the project builds normally.
my CMakeLists.txt:
cmake_minimum_required(VERSION 3.23)

project(demo-app)

set(CMAKE_CXX_STANDARD 23)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

file(GLOB SOURCE_FILES src/*.cpp)

add_executable(demo ${SOURCE_FILES})

include_directories(src)

#ImageMagick
add_definitions( -DMAGICKCORE_QUANTUM_DEPTH=16 )
add_definitions( -DMAGICKCORE_HDRI_ENABLE=0 )
include_directories(deps/ImageMagick/include)
target_link_directories(demo PRIVATE deps/ImageMagick/lib)
target_link_libraries(demo
    "CORE_RL_Magick++_"
    "CORE_RL_MagickCore_"
    "CORE_RL_MagickWand_"
)

and the project structure is very simple:

And this is the log when I run the app and get the error ( I forced it to quit as it breaks on the exception):
-------------------------------------------------------------------
You may only use the C/C++ Extension for Visual Studio Code
with Visual Studio Code, Visual Studio or Visual Studio for Mac
software to help you develop and test your applications.
-------------------------------------------------------------------
Loaded 'D:\dev_haidar\c++\demo_old\build\demo.exe'. Module was built without symbols.
Loaded 'C:\Windows\System32\ntdll.dll'.
Loaded 'C:\Windows\System32\kernel32.dll'.
Loaded 'C:\Program Files\Avast Software\Avast\aswhook.dll'.
Loaded 'C:\Windows\System32\KernelBase.dll'.
Loaded 'C:\Windows\System32\ucrtbase.dll'.
Loaded 'C:\Windows\System32\msvcp140.dll'.
Loaded 'C:\Windows\System32\vcruntime140.dll'.
Loaded 'C:\Windows\System32\vcruntime140_1.dll'.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_Magick++_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_MagickCore_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_MagickWand_.dll'. Module was built without symbols.
Loaded 'C:\Windows\System32\user32.dll'.
Loaded 'C:\Windows\System32\vcomp140.dll'.
Loaded 'C:\Windows\System32\win32u.dll'.
Loaded 'C:\Windows\System32\gdi32.dll'.
Loaded 'C:\Windows\System32\gdi32full.dll'.
Loaded 'C:\Windows\System32\msvcp_win.dll'.
Loaded 'C:\Windows\System32\advapi32.dll'.
Loaded 'C:\Windows\System32\msvcrt.dll'.
Loaded 'C:\Windows\System32\sechost.dll'.
Loaded 'C:\Windows\System32\rpcrt4.dll'.
Loaded 'C:\Windows\System32\ws2_32.dll'.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_freetype_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_bzlib_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_lcms_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_lqr_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_xml_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_zlib_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_harfbuzz_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_fribidi_.dll'. Module was built without symbols.
Loaded 'C:\Program Files\ImageMagick-7.1.0-Q16\CORE_RL_glib_.dll'. Module was built without symbols.
Loaded 'C:\Windows\System32\shell32.dll'.
Loaded 'C:\Windows\System32\ole32.dll'.
Loaded 'C:\Windows\System32\combase.dll'.
Loaded 'C:\Windows\System32\dnsapi.dll'.
Loaded 'C:\Windows\System32\IPHLPAPI.DLL'.
Loaded 'C:\Windows\System32\imm32.dll'.
Loaded 'C:\Windows\System32\nsi.dll'.
Hello, World!
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
Exception thrown at 0x00007FFC98B7A59D (ntdll.dll) in demo.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
The program '[8620] demo.exe' has exited with code 0 (0x0).

Can someone tell me how to solve this?
Note: the include and lib folders under deps/ImageMagick were copy/pasted from the installation of imagemagick  ImageMagick-7.1.0-49-Q16-x64-dll.exe from the official site.

A: According to the Documentation over on the site you linked to, the suggested usage is:

Note, under Windows (and possibly the Mac) it may be necessary to initialize the ImageMagick library prior to using the Magick++ library. This initialization is performed by passing the path to the ImageMagick DLLs (assumed to be in the same directory as your program) to the InitializeMagick() function call. This is commonly performed by providing the path to your program.

So you'll have to properly initialize the library before using it, to get your program to run correctly. This initialization can be accomplished like so:
int main(int argc, char* argv[]) {
    InitializeMagick(*argv);

    //Your code with Magick++ operations here.

    return 0;
}


text:
Q: How Fourier transform be able to deal with transients? Below is what Matt L.said in the thread here.
Could anyone clarify how Fourier transform be able to deal with transitents? Reading that thread many times but I couldn't figure it out.

Note that it is not true that the Fourier transform cannot deal with
  transients. This is just a misunderstanding which probably comes from
  the fact that we often use the Fourier transform to analyze the
  steady-state behavior of systems by applying sinusoidal input signals
  that are defined for −∞ < t < ∞.

A: It's important to use the right sort of tool for the job. A hammer is defined to put in nails. If you want to turn screws, use a screwdriver.
The Discrete Fourier Transform (DFT), of which the Fast Fourier Transform (FFT) calculates exactly the same result, but far faster, is defined only over repetitive signals. That is, the result it produces is exactly the same (with appropriate re-labelling) as if you had taken the signal input to the FFT, and concatenated it with itself.
This cyclic feature means that the FFT is a natural fit for repetitive waveforms. If the input sample contains an exact integer number of cycles, then it can be extended indefinitely by repetition, and look exactly the same as the original.
The technique of windowing a signal before FFT is used to reduce the problems that occur when it's used to transform a non-cyclic waveform. For example, take a one-second sample of a continuous 10.5Hz signal. If this sample is concatenated with itself, you get a half-cycle step, which messes with what you would hope to see doing a spectrum analysis. Note that it doesn't make the transform wrong, it just means that what you got is not what you naively hoped to get. If you hit the nail sideways, you get a bent rather than a driven nail, the hammer is still working just fine, doing exactly what it's defined to do.
The window reduces the signal amplitude at the beginning and end of the sample to zero, which means it can be cyclically extended. The window changes the signal, so the spectrum will change. However, it changes in a known and easily calculable way, which the FFT doesn't further change.
When used to transform a transient signal, we need to ensure that the signal sample starts and ends at zero. Then the sample meets the cyclic requirement, and the FFT will give you exactly what you would expect if you had a train of transient signals, repeating every sample length.
That's what the FFT does. If you don't want the transform of a train of signals, then the FFT is not the hammer to use. You still have a lot of freedom to adjust this train of signals to your taste, just as you can choose what window to use when transforming a continuous signal. You can make the impulses repeat less often by increasing the time length of the sample for instance.

A: I'm not trying to get to the bottom of the linked question, I'm just trying to justify why Fourier analysis of a transient is perfectly feasible.
Given that a transient is temporal limited, i.e. it is a transient and it doesn't last very long, it's feasible to limit the time range for the analysis. On this basis, it seems reasonable to analyse it if it were a continual and repeating waveform. So the transient begins at (say) time zero and is all-done at (say) 1 second. Is there anything unreasonable to assume that it starts again at t=1 second?
Therefore it can be analysed by normal Fourier analysis.

A: Here is Signal Wave Explorer, using FFT, to model 3 pulses thru a LPF. On right side of the plots is a dotted vertical line, the Nyquist frequency. In the Mag/Phase that is the mirroring frequency, indeed shown here.
[ We are interested in very accurate modeling of the SETTLING of opamp responses, to the 16 and 20 and 24 bit levels. Thus far, in SWE, with 512,000 samples, we easily reach the 20 bit level. With larger memory allocation, we expect to reach 24+ bits. The built-in example "JB stage", shown at end of this answer, illustrates typical problems of settling. ]
Shown below these 8 plots is screenshot with just InputWaveform, Magnitude plots, and OutputWaveform. Examine the OutputWaveform carefully, particularly the 3rd output pulse, and you'll see that final decay to zero amplitude. The first 2 pulses are not allowed enough time to decay to zero amplitude.
Thus we have used the FFT to fully capture the transient behavior.

And now without the Phase plots. In the InputSpectrum, you see the sin(x)/x components of the squarewave, with amplitudes decaying as 1/Harmonic#. The tool --SWE--- simply multiplies this InputSpectrum with the SystemSpectrum, producing the OutputSpectrum; magnitudes are multiplied; phases are added. Then OutputSpectrum undergoes InverseFFT, to produce the OutputWave.

Here is the JB_stage example.

Here is output waveform of JB_stage, with NO input filtering (C1 is not active); notice the initial pulse is NONINVERTING. The input edge blasts right through the feedback capacitor.


text:
Q: Connect an directory index to another directory index I'm trying to call my index.php on my cPanel, however since my hosting service only allows up to 1 sublevel of directory, I have to bring up my index.php.
I'm using Yii framework, and since it's my first application. I dont know how to link it. I also just continued the application from another developer, it's making me confused on how to change or place my index.php
Is it possible to create an index.php to call another index.php, since the current index.php, still has to run the yii framework? I dont want to change the directory paths since there's just too many paths to change.
UPDATE:
Found out I was inputting the wrong path, I've got it to show the page, but now it does not load any of the images/css. What's seems to be the problem now?

A: I might be asking a dumb question, but have you tried a PHP Include? This won't affect paths or anything, but the code from the included index.php will be used in the first page...
<?PHP
   include_once('directory/index2.php');
?>


text:
Q: $R$ UFD and integral domain $\Rightarrow$ every $a\neq 0 \in R\setminus R^\times$ is a product of prime elements Let $a$ be as in title. Then by definition of UFD we have unique factorisation
$$a=\epsilon p_1\dots p_n \quad : \epsilon\in R^\times \text{ and } p_i \in R \text{ irreducible}.$$
It is known that in an UFD irreducible elements are prime. To finish the proof we have to argue $\epsilon = 1$, but why is that?


text:
Q: Scoping issues with nested scriptblocks and try ... finally I'm trying to implement RAII-style resource managing in PowerShell. What struck me as a good idea was to acquire the resource in a try-block and release it again in a finally-block (as it is guaranteed that the finally-block is executed). Sometimes, my resources depend on each other, so I use a nested approach. The outline is as follows:
My resource 1 is acquired like so (sorry for the lenghty code, could not find a way to shorten it):
function withResource1 {
    param( [Parameter(Mandatory=$true)][scriptblock]$action )

    try {
        write-host "acquire resource1"

        <# ... compute resource 1... #>
        $resource1 = "<this is the resource>"

        invoke-command -scriptBlock $action -args $resource1
    } finally {
        write-host "release resource1"
        <# ... #>
    }
}

Resource 2 depends upon 1, so I acquire it like this:
function withResource2 {
    param( [Parameter(Mandatory=$true)][scriptblock]$action )

    withResource1 { param( $res1 )
        try {
            write-host "acquire resource2"

            <# ... compute resource2, using resource1 ... #>
            $resource2 = "<and this is the other resource>"

            invoke-command -scriptBlock $action -args $resource2
        } finally {
            write-host "release resource2"
            <# ...  #>
        }
    }
}

Now (at least I was thinking), I could use resource 2 like this:
withResource2 { param( $res2 )
    write-host "I'm happy to have '$res2', which depends on resource 1"
}

I expected the output to be
acquire resource1
acquire resource2
I'm happy to have '<and this is the other resource>', which depends on resource 1
release resource2
release resource1

But what actually happened was some kind of infinite loop. The problem seems to be some kind of scoping issue, because if I rename action to, say ac in withResource2, then everything works as expected.
How can I achieve what I want? And is there a better way to simulate RAII in PowerShell?

A: Okay, I found out myself.
Inside the try-block within withResource2, there is no $action variable in scope 0, i.e.
get-variable -name action -scope 0

cannot find a variable named action. So it relents to scope 1, which is the parent scope (the scope of withResource1) and the $action there is precisely the scriptblock I'm supplying to withResource1. Calling it leads to an infinite loop.
What I actually wanted to call in the try-block in withResource2 is the $action in withResource2, which is 2 scopes above. So changing the invoke-command-line in withResource2 to
invoke-command -scriptBlock ( get-variable -name action -scope 2 ).Value -args $resource2

does the trick.


text:
Q: Firestore: Convert time object to timestamp I am using vue.js for my e-commerce project.
I want to set the sale time limit in the firestore collection.
ex)If user want to stop to sell his or her product at 15:00, user can input 15:00.
Now I could set the time object in my collection.
But I want to convert it to timestamp.
How can I achieve it?
I set this.limit like this way in the template tag.
<b-form-input type="time" v-model="limit"></b-form-input>

This is the script tag.
<script>
import fireApp from '@/plugins/firebase'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();
let id = String(id);
import ErrorBar from '@/components/ErrorBar'
import { SpringSpinner } from 'epic-spinners'

  export default {
    name: "Products",
    data() {
      return {
        show: false,
        quantity: "",
        initial: "",
        sale: "",
        limit: ""
      }
    },
    components: {
        SpringSpinner
    },
    created() {

    },
    methods: {
        submitProduct() {

                var docRefLimit = db.collection('Profile').doc(user.uid).collection('Product').doc('limit')
                const timestamp = firebase.firestore.FieldValue.serverTimestamp()

                docRefLimit.get().then((doc) => {
                    this.show =true;
                    if (doc.exists) {
                        docRefLimit.update({
                            limit: this.limit.timestamp,
                        }).then(() => {
                            this.show =false
                        })
                    } else {
                        docRefLimit.set({
                            limit: this.limit.timestamp,
                        })
                        .then(() => {
                            this.show =false
                        })
                    }
                }).catch((error) => {
                    console.log("Error getting document:", error);
                });
            },
    }
  }
</script>

A: You don't indicate if the timestamp should take the date of the day.
So let's imagine you want to add a Timestamp for today at 15:00 to a Firestore document. Do as follows:
  const limitHour = this.limit.substring(0, 2);
  const limitMinutes = this.limit.substring(3, 5);

  let today = new Date();
  today.setHours(limitHour, limitMinutes, 0, 0);

  var docRefLimit = db.collection('Profile').doc(user.uid).collection('Product').doc('limit');
  docRefLimit.update({ limit: today })
   .then(() => ...)

Note that firebase.firestore.FieldValue.serverTimestamp() "returns a sentinel used with set() or update() to include a server-generated timestamp in the written data" which will be calculated by the Firestore backend, not in the frontend.


text:
Q: side by side plots on multiple pages I'm trying to create a list of plots for each categorical value in my data frame. For each category, 2 plots side by side will be plotted on one page and on each page will contain the plots for each category.
Each one of the tasks is doable but I'm having problems with combining both.
1- The task of creating plots by categories (one on each page of the PDF) can be easily done using this dplyr code:
AllPlots <- dataf %>%
  group_by(category) %>%
  do(plots=ggplot(data=., aes(x = x, y = val)) +  geom_bar(stat="identity")+ ggtitle(unique(.$category)))

pdf("plots.pdf")
invisible(lapply(AllPlots$plot, print))
dev.off()

2- The task of plotting side by side is also easy with grid and gridExtra:
p1 = qplot(1:10, rnorm(10))
p2 = qplot(1:10, rnorm(10))
grid.arrange(p1, p2, ncol = 2, main = "Main title")

One can make a for loop based on the category and make the arrangement of the plots side by side and then combine them all in one page. however, I guess this slow since my dataframes are quite big.
The question is, how to do both things at the same time in a fast way?

A: Sorry, I wanted only to comment, but because I'm new, the site doesn't let me to comment yet.
If you can plot by categories, try using this before starting to plot-
par(mfrow = c(1,2))

which will change your environment definitions, and will put 2 plots in each page one next to the other.
to find more about par(mfrow), you can look here-
http://www.statmethods.net/advgraphs/layout.html


text:
Q: Create column with values from multiple columns in SQL I want to add a column to a table that includes value from one of two columns, depending on which row contains the value.
For instance,
SELECT
  concat("Selecting Col1 or 2", cast("Col1" OR "Col2" as string)) AS relevantinfo,
FROM table

I do not know much SQL and I know this query does not work. Is this even possible to do?
Col1    Col2
1
         4
3
4
         5

FINAL RESULT
Col1    Col2    relevantinfo
1                1
        4        4
3                3
4                4
        5        5

A: You can use the COALESCE function, which will return the first non-null value in the list.
SELECT col1, col2, COALESCE(col1, col2) AS col3
FROM t1;

Working example: http://sqlfiddle.com/#!9/05a83/1

A: I wouldn't alter the table structure to add a redundant information that can be retrieved with a simple query.
I would rather use that kind of query with IFNULL/ISNULL(ColumnName, 'Value to use if the col is null'):
--This will work only if there can't be a value in both column at the same time
--Mysql
SELECT CONCAT(IFNULL(Col1,''),IFNULL(Col2,'')) as relevantinfo FROM Table

--Sql Server
SELECT CONCAT(ISNULL(Col1,''),ISNULL(Col2,'')) as relevantinfo FROM Table


text:
Q: Waveguides question A rectangular waveguide with dimensions \$a=10~\mathrm{cm}, b=6~\mathrm{cm}\$ is filled with dielectric material with an unknown relative coefficient \$\epsilon_r\$. The guide is terminated by an unknown load. It is excited by \$TE_{3,0}\$ modes at a frequency of \$2.5~\mathrm{GHz}\$. How can I determine \$\epsilon_r\$?
I know the cutoff frequency is given by:
$$f=c\frac{\sqrt{(n/a)^2+(m/b)^2}}{2\sqrt{\epsilon_r}}$$
I am also told that the first minima are at \$s_a=5~\mathrm{mm}, s_b=30~\mathrm{mm}\$ away from the load.
I know that the distance between the minima is \$\lambda/2\$, hence \$\lambda=50~\mathrm{mm}\$. Does that mean that \$c/(f\sqrt{\epsilon_r})=50\$? Because if it is, then I can easily find \$\epsilon_r\$ to be approx. 1.55. Is that correct?

A: of course standing wave minima was given thus $$\lambda /2 $$so you are almost correct ... calc error...
$$\epsilon_r = (\dfrac{c}{\lambda f })^2~~ \text{  so }~~\epsilon_r=5.76$$


text:
Q: Using the google sheets api after completing quickstart tutorial I'm pretty new to Android app development so please forgive my naivety.
I'm currently trying to develop an app that can pull data from a google spreadsheet and write data to it.
I've completed the quickstart tutorial so my code is the same as that right now. It all works correctly.
My issue is I need to be able to read from my own spreadsheet and I don't really understand the code used so I'm struggling to know where to start.
I've looked at this to try and implement the authorisation in fewer steps which I thought might make the code easier to understand - but again my lack of knowledge means I don't know how this fits into all the methods I currently have.
I've looked at the developer documentation and tried to replace the code from the quickstart which retrieves data from the app with this:
ValueRange result = service.spreadsheets().values().get(spreadsheetId, range).execute();
int numRows = result.getValues() != null ? result.getValues().size() : 0;
System.out.printf("%d rows retrieved.", numRows);

But again this is different to the code I already have so doesn't fit in as the getDataFromApi() method requires a return statement. I've tried just changing the spreadsheetId to that of my own spreadsheet and changing the range value to the cells I need,
/**
         * Fetch a list of names and majors of students in a sample spreadsheet:
         * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
         * @return List of names and majors
         * @throws IOException
         */
        private List<String> getDataFromApi() throws IOException {
            String spreadsheetId = "1-hL78Jm9-HijPx9UHthFxcXatkIhA2FR-AQ1lrCUbEg";
            String range = "Go Mix 12 0506!B6:D";
            List<String> results = new ArrayList<String>();
            ValueRange response = this.mService.spreadsheets().values()
                    .get(spreadsheetId, range)
                    .execute();
            List<List<Object>> values = response.getValues();
            if (values != null) {
                results.add("Name, Major");
                for (List row : values) {
                    results.add(row.get(1) + ", " + row.get(3));
                }
            }
            return results;
        }

but I'm clearly going about it wrong because I get this error:
Invalid index 3, size is 3
I've also followed up to video 15 on this tutorial but it bypasses the need for any authorisation so didn't help.
Basically I've hit a brick wall and need someone to explain to me in simple terms how I can either work with the code from the quickstart tutorial to work with my own spreadsheet and fix that error! OR (more preferable to myself) explain how to do it myself from scratch. NB the spreadsheet cannot be public so I will need authorisation.
I hope that all makes sense!

A: You are asking to retrieve three columns of data (B through D), but then attempting to read a fourth column (rows.get(3)).  In Java (and in most programming languages), lists and arrays are 0-based. So if you want the first item, you call list.get(0), and if you want the third you call list.get(2).  This is evident based on the fact that the error message tells you your index of 3 is invalid since the list is size 3 -- you're attempting to read something beyond the end of the list.


text:
Q: create a multidimensional array from mysql tables i would like to create a array of 3 dimensions from 3 mysql tables(sections/rubriques/category):
[0]  section_title_1
      [0] rubrique_title_1
           [0] category_title_1
           [1] category_title_2
           [2] category_title_3
      [1] rubrique_title_2
            ...................

[1]  section_title_2
      .........

here is my code:
$output = array();

$i = 0;
$sections=$this->_model->get_table_sections();

foreach($sections as $section){
output[$i] = $section->section_title;

  $ii = 0;
  $rubriques =  $this->_model->get_rubriques_for_a_section($section-   >section_id);

    foreach($rubriques as $rubrique){
    $output[$i]['rubr'][$ii] = $rubrique->rubrique_title;

    $iii = 0;
    $categories =  $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
         foreach($categories as $categorie){
         $output[$i]['rubr'][$ii]['categories'][$iii] = $categorie->categorie_title;
         $iii++;
                                           }
  $ii++;
                               }
  $i++;
                          }

            var_dump($output);

at the statement  : $output[$i]['rubr'][$ii] = $rubrique->rubrique_title;
i get an error of Illegal string offset 'rubr'

Can you give me the answer of this coding ?
Many thanks..

A: you getting error because $output[$i] is undefined and has no prototype of Array. So, you can solve it by initializing it as empty array like this:
$output[$i] = array();
But, you till have error, this code solve your problem:
$output = array();

$i = 0;
$sections=$this->_model->get_table_sections();

foreach($sections as $section){
    $output[$i]['title'] = $section->section_title;

  $ii = 0;
  $rubriques =  $this->_model->get_rubriques_for_a_section($section-   >section_id);

    foreach($rubriques as $rubrique){
    $output[$i]['rubr'][$ii] = $rubrique->rubrique_title;

    $iii = 0;
    $categories =  $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
         foreach($categories as $categorie){
         $output[$i] = isset( $output[$i] ) ? $output[$i] : array();
         $output[$i]['rubr'] = isset( $output[$i]['rubr'] ) ? $output[$i]['rubr'] : array();
         $output[$i]['rubr'][$ii] = isset( $output[$i]['rubr'][$ii] ) ? $output[$i]['rubr'][$ii] : array();
         $output[$i]['rubr'][$ii]['categories'] = isset( $output[$i]['rubr'][$ii]['categories'] ) ? $output[$i]['rubr'][$ii]['categories'] : array();
         $output[$i]['rubr'][$ii]['categories'][$iii] = isset( $output[$i]['rubr'][$ii]['categories'][$iii] ) ? $output[$i]['rubr'][$ii]['categories'][$iii] : array();
         $output[$i]['rubr'][$ii]['categories'][$iii] = $categorie->categorie_title;
         $iii++;
                                           }
  $ii++;
                               }
  $i++;
                          }

            var_dump($output);

A: This could be the way:
$output = array();
$sections = $this->_model->get_table_sections();

foreach($sections as $section){
    $output[$section->section_title] = array();

    $rubriques = $this->_model->get_rubriques_for_a_section($section->section_id);

    foreach($rubriques as $rubrique){
        $output[$section->section_title][$rubrique->rubrique_title] = array();

        $categories =  $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
        foreach($categories as $categorie){
            $output[$section->section_title][$rubrique->rubrique_title][] = $categorie->categorie_title;
        }
    }
}

var_dump($output);

Use titles as indexes. Of course only if you don't need numeric indexes, but from your code I suppose you don't.


text:
Q: Site-to-Site Tunnel between Cisco Router and Windows Server 2003/2008 Has anybody successfully created an IPSec site-to-site tunnel between a Windows Server 2003 or 2008 and a Cisco router?
We tried the steps outlined at:
http://www.cisco.com/en/US/tech/tk583/tk372/technologies_configuration_example09186a00800b12b5.shtml
But no luck.
Thanks,
Dejan

A: No.
I spent two whole days last week trying to accomplish the exact same thing and failed.  I found this to be a poorly documented topic, and after two days I just gave up.
I did get it to sort of work, but with various configurations on the Windows side, I could only get one side or the other to be able to create the tunnel, but never both.  Once the tunnel was created both sides could communicate with each other through the tunnel, but only if for example, the Cisco router initiated the tunnel.
You can find my Cisco config from this post and maybe some other information that might help from this serverfault post I made, even though I said XP, I tried with 2003 as well. Here is a article on how to get some error logs for the Windows side.  For the Cisco side, you can enable various crypto debugging with debug crypto ? where the question mark will show you the options.
From the windows side, if you see a failure with Main Mode, that would be the initial ike negotiation in the General -- Advanced portion of your policy.  For quick mode, that would be the Negotiate security part of your filter action.  For the cisco side, quick mode is the transform set, and Main mode is the crypto isakmp policy.
In that Cisco document you linked to, if you look at the filters, it shows there filters as being mirrored.  According to Microsoft, mirrored filters and protocol specific filters are not supported with tunnel mode.
I also wrote the following for myself to help me get the windows settings:

There are 'IP Security Policies'.
  Each policy has a IKE settings (Phase
  1, or Main Mode).  Each policy also
  can have rules applied to it. A rule
  can have a single filter, a single
  filter action, a optional tunnel
  endpoint, and a authentication method.
  A filter chooses what traffic will be
  matched and have the rule applied to
  it. A filter can be described in terms
  of Source address, Destination
  Address, and/or protocols and ports.

The filters is where my test broke down I think, For the Microsoft to Cisco, if I used the Windows IP and the Cisco IP as the destination, it would not work, I had to put ANY IP for the destination and set the protocol for the filter to ICMP for my test (Even though those are not supposed to work).
So on the whole, I found it to be a spotty technology, poorly documented, and if you can't tell, frustrating.  I have set up site-site VPN with Cisco to Cisco before without any problems.  If you get to work reliably, please post what you did. Sorry if this post is a bit rambling, hopefully something in here might help you.


text:
Q: Prototype bean scope implementation in Spring Framework Hello guys I am trying to understand how exactly prototype Scope works in Spring IoC.
For prototype beans I tried to understand by:
1. Reading this again and again but could not understand fully(https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes-other-injection)
2. Tried to debug via source code,only understood one thing if we do not specify proxyMode, it will not create proxy for prototype bean.
3. default ScopedProxyMode for prototype scope is DEFAULT which typically equals NO.. unless configured in component scan.
So I have 3 examples here:
Case A: Prototype bean used independently(not having any dependency or is not dependency for any bean) without proxymode defined
@Bean
@Scope("prototype")
public Employee employee(){
  return new Employee();
}

Case B: Prototype bean inside a singleton bean as dependency without proxymode defined
@Bean
@Scope("prototype")
public Employee employee(){
  return new Employee();
}

@Bean
@Scope("singleton")
public Department department(){
  return new Department();
}

Case C: Prototype bean inside a singleton bean as dependancy with proxymode defined
@Bean
@Scope("prototype",proxyMode= ScopedProxyMode.TARGET_CLASS)
public Employee employee(){
  return new Employee();
}

@Bean
@Scope("singleton")
public Department department(){
  return new Department();
}

Guys questions here are:

*

*How will case A, case B and case C work?

*I am trying to understand what exactly will be correct way.

*Also not specifying proxymode is correct or not?

*What happens when proxyMode is not set? how does prototype work then?

What I typically saw in implementation examples on internet is people often do not configure proxyMode either mistakenly or are not aware about this option or maybe they are right.
Thank you for your valuable time.

A: *

*A, B, and C will all return new instance of Employee when requested.

*A and B are usual ways to use prototype scopes.

*Not specifying is the usual way. Though in some instances where scope is RequestScope or Session scope, etc, it might make sense to specify proxyMode. Regarding specifying proxyMode, see the last paragraph.

*If not set, you get the expected behavior. That is, you get new instance every time a bean instance is requested.

The prototype scope instructs Spring to instantiate a new instance of the bean everytime a bean instance is requested by the application.
You should consider using prototype scope in the following scenarios:

*

*If you have a bean that has a lot of writable state, you may find that the cost of synchronization is greater than the cost of creating a new instance to handle each request from a dependent object.

*Some dependent objects need a bean that has private state so that they can conduct their processing separately from other objects that depend on the bean. In this case, singletons are clearly not suitable. Consider prototypes.

It is a good practice that your beans should implement some interface. In that case, Spring uses JDK proxy mechanism to create proxy of your class. But implementing interface is not a requirement. If no interface is implemented by your bean, then Spring uses CGLIB library to create proxy of your bean (unless a class is annotated with @Configuration in which case a different proxy mechanism is used).
By specifying proxyMode=ScopedProxyMode.TARGET_CLASS, you are forcing Spring to use CGLIB proxy mechanism. In the end, just providing @Scope("prototype")  is sufficient.
On a side note, know that if you have any methods that hook into lifecycle of a bean (like @PreDestroy, implementing DisposableBean interface, or destroyMethod as a flag in @Bean), then those methods will never be called in prototype scoped beans.


text:
Q: RecyclerView ItemTouchHelper on swipe I'm trying to implement swipe to delete in a recycler view. I have this code.
public abstract class SwipeToDeleteCallback extends ItemTouchHelper.Callback {
    private Context context;
    private Paint clearPaint;
    private ColorDrawable background;
    private int backgroundColor;
    private Drawable deleteDrawable;
    private int intrinsicWidth;
    private int intrinsicHeight;

    public SwipeToDeleteCallback(Context context) {
        this.context = context;
        background = new ColorDrawable();
        backgroundColor = Color.parseColor("#DB3236");
        clearPaint = new Paint();
        clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        deleteDrawable = ContextCompat.getDrawable(this.context, R.drawable.ic_delete_white_24dp);
        intrinsicWidth = deleteDrawable.getIntrinsicWidth();
        intrinsicHeight = deleteDrawable.getIntrinsicHeight();
    }

    @Override
    public int getMovementFlags(@NonNull RecyclerView recyclerView,
                                @NonNull RecyclerView.ViewHolder viewHolder) {
        return makeMovementFlags(0, ItemTouchHelper.LEFT);
    }

    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView,
                          @NonNull RecyclerView.ViewHolder viewHolder,
                          @NonNull RecyclerView.ViewHolder viewHolder1) {
        return false;
    }

    @Override
    public void onChildDraw(@NonNull Canvas canvas, @NonNull RecyclerView recyclerView,
                            @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
                            int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

        View itemView = viewHolder.itemView;
        int itemHeight = itemView.getHeight();

        boolean isCancelled = dX == 0 && !isCurrentlyActive;

        if (isCancelled) {
            clearCanvas(canvas, itemView.getRight() + dX, (float) itemView.getTop(),
                    (float) itemView.getRight(), (float) itemView.getBottom());
            super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState,
                    isCurrentlyActive);
            return;
        }

        background.setColor(backgroundColor);
        background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(),
                itemView.getRight(), itemView.getBottom());
        background.draw(canvas);

        int deleteIconTop = itemView.getTop() + (itemHeight - intrinsicHeight) / 2;
        int deleteIconMargin = (itemHeight - intrinsicHeight) / 2;
        int deleteIconLeft = itemView.getRight() - deleteIconMargin - intrinsicWidth;
        int deleteIconRight = itemView.getRight() - deleteIconMargin;
        int deleteIconBottom = deleteIconTop + intrinsicHeight;

        deleteDrawable.setBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom);
        deleteDrawable.draw(canvas);

        super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    private void clearCanvas(Canvas canvas, Float left, Float top, Float right, Float bottom) {
        canvas.drawRect(left, top, right, bottom, clearPaint);
    }

    @Override
    public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
        return 0.7f;
    }
}

However, the problem is that the row is deleted as it is swiped. I would like to maintain it there i.e. when the row is swiped, show the delete button and then the user can click on it, instead of swiping fully deletes it, instead show the delete button after the swipe. Also, am trying to add the edit button as well but on the left, with the delete, any ideas how?

A: Create ItemTouchHelper and attach it to recyclerview.
Code to attach helper to RecyclerView
itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);

Code of ItemTouchHelper class
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

        private void drawText(String text, Canvas c, RectF button, Paint p) {
            float textSize = 30;
            p.setColor(Color.WHITE);
            p.setAntiAlias(true);
            p.setTextSize(textSize);

            float textWidth = p.measureText(text);
            c.drawText(text, button.centerX() - (textWidth / 2), button.centerY() + (textSize / 2), p);
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {

                View itemView = viewHolder.itemView;
                Paint p = new Paint();

                if (dX > 0) {
                    c.drawRect((float) itemView.getLeft(), (float) itemView.getTop(), dX,
                            (float) itemView.getBottom(), p);
                } else {
                    RectF rightButton = new RectF(itemView.getRight() - 200, (itemView.getTop() + dpToPx(4)),
                            (itemView.getRight() - dpToPx(4)), (itemView.getBottom() - dpToPx(8)));
                    p.setColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
                    c.drawRoundRect(rightButton, 10, 10, p);
                    drawText("Del", c, rightButton, p);
                }

                // Fade out the view when it is swiped out of the parent
                final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                viewHolder.itemView.setAlpha(alpha);
                viewHolder.itemView.setTranslationX(dX);
            } else {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
            final int position = viewHolder.getAdapterPosition();
            if (direction == ItemTouchHelper.LEFT) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Are you sure to delete?");
                builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.notifyItemRemoved(position);
                        mProductViewModel.delete(adapter.getItem(position));
                        return;
                    }
                }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {  //not removing items if cancel is done
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.notifyItemRemoved(position + 1);
                        adapter.notifyItemRangeChanged(position, adapter.getItemCount());
                        return;
                    }
                }).show();  //show alert dialog
            }
        }
    };

A: I find this new way of implementing swipe to delete quite friendly,that is implementing new ItemTouchHelper() in oncreate method.All you have to do is pass in the position of the item you want to delete in the recyclervew. See the the example code below.Here i implemented the new ItemTouchHelper() for it to delete any note i swipe right or left of my screen.
here is the code:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            noteViewModel.delete(noteAdapter.getNoteAt(viewHolder.getAdapterPosition()));
            Toast.makeText(MainActivity.this, "Note Deleted", Toast.LENGTH_SHORT).show();
        }
    }).attachToRecyclerView(rv_notes);

rv_notes is the instance of my recyclerview
To understand how you can implement it clearly ,follow the code in my github.Here is the link.
https://github.com/sammymutahigicheru/NoteApp


text:
Q: How to add brackets around WHERE conditions with Laravel query builder I'm using the Laravel query builder to dynamically filter data based on a user's filter selections:
 $query = DB::table('readings');
 foreach ($selections as $selection) {
   $query->orWhere('id', $selection);
 }
 $query->whereBetween('date', array($from, $to));
 $query->groupBy('id');

When I examine the SQL, I get something like this:
select count(*) as `count` from `readings` where `id` = 1 or id` = 2 and `date` between "2013-09-01" and "2013-09-31" group by `id`;

But what I need is something like this (with brackets around the or statements):
select count(*) as `count` from `readings` where (`id` = 1 or id` = 2) and `date` between "2013-09-01" and "2013-09-31" group by `id`;

How do I add brackets around WHERE conditions with Laravel query builder?

A: Solved this myself by using a closure, as described in Parameter Grouping in the query builder documentation.
 $query = DB::table('readings');
 $this->builder->orWhere(function($query) use ($selections)
 {
    foreach ($selections as $selection) {
       $query->orWhere('id', $selection);
    }
 });
 $query->whereBetween('date', array($from, $to));
 $query->groupBy('id');

A: Sometimes you may need to group several "where" clauses within parentheses in order to achieve your query's desired logical grouping. In fact, you should generally always group calls to the orWhere method in parentheses in order to avoid unexpected query behavior. To accomplish this, you may pass a closure to the where method:
$users = DB::table('users')
           ->where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();

As you can see, passing a closure into the where method instructs the query builder to begin a constraint group. The closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')

A: Very useful, I use this:
->where(function ($query) use ($texto){
    $query->where('UPPER(V_CODIGO)', 'LIKE', '%'.Str::upper($texto).'%')
          ->orWhere('UPPER(V_NOMBRE)', 'LIKE', '%'.Str::upper($texto).'%');
});

A: You can use WHERE IN here for the same effect:
$query = DB::table('readings');
$query->whereIn('id', $selection)
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');

A: I couldn't find this in documentation, whereNested was what I was looking for. Hope it helps anybody.
$q->whereNested(function($q) use ($nameSearch) {
    $q->where('name', 'LIKE', "%{$nameSearch}%");
    $q->orWhere('surname', 'LIKE', "%{$nameSearch}%");
});

Note: This is on Laravel 4.2


text:
Q: Does Clojure have short-circuit logic? In many languages, if you write something along the lines of
if (foo() || bar() || foobar()) { /* do stuff */ }

and foo() returns true, then bar() and foobar() will not be evaluated.
Suppose I had the following Clojure code:
(let [a (simple-function args)
      b (complex-function args)
      c (too-lazy-to-optimize-this-function args)]
  (or a b c))

If a evaluates to true, will b and c also be evaluated, or will they be ignored?
Thanks!

A: When in doubt, consult the documentation:

or
  macro
  Usage:
   (or)
   (or x)
   (or x & next)

Evaluates exprs one at a time, from left to right. If a form
  returns a logical true value, or returns that value and doesn't
  evaluate any of the other expressions, otherwise it returns the
  value of the last expression. (or) returns nil.

(Emphasis mine.)
The documentation for and shows it behaves in the equivalent way too.

A: Since you answered your own question, note that though in your example b and c may not evaluated in the (or a b c) call, the let binding is evaluated before that so the too-lazy-to-optimize-this-function call is evaluated anyway. Clojure isn't as lazy as that.
To be clear: to conditionally evaluate the function calls, you need to put the expression evaluating them in the or call, basically:
(or (simple-function args)
    (complex-function args)
    (too-lazy-to-optimize-this-function args))

A: The other answers all good, but when in doubt, you can always just test it out on the REPL:
user=> (or true (do (println "hello") true))
true
user=> (or false (do (println "hello") true))
hello
true

A: As soon as I finished typing this question, I realized I could just look at the documentation for 'or'.
From the docs:
 "Evaluates exprs one at a time, from left to right. If a form
  returns a logical true value, or returns that value and doesn't
  evaluate any of the other expressions, otherwise it returns the
  value of the last expression. (or) returns nil."

A: Yes, Clojure does indeed have short circuit evaluation.
One interesting feature in Clojure / other Lisps is that it is also possible to extend the language with new constructs that also provide short-circuit evaluation. This can't be done using functions in most other languages since all the parameters to a function must be evaluated before the function is called.
Here's an example of a macro to implement a short-circuiting NAND function in Clojure:
(defmacro nand
  ([x]
    `(not ~x))              ; NAND is equivalent to NOT for one argument
  ([x & xs]
    `(let [nand# (not ~x)]
       (if nand#
         true               ; short circuit if we can prove the nand is true
         (nand ~@xs)))))    ; continue with the other expressions otherwise

(nand true true)
=> false

(nand false (println "Expression with a side effect!"))
=> true

A: if (foo() || bar() || foobar()) { /* do stuff */ }

to
(if (or (foo) (bar) (boobar)) (comment do stuff))

or
(when (or (foo) (bar) (boobar)) (comment do stuff))


text:
Q: localization resource not found. partialViews and controllers I am getting resource not found = true in this line
ViewData["MenuItem_AboutUs"] = localizer["MenuItem_AboutUs"];

also I am not sure how to use localization on partialviews, I couldn't find any sample.
PartialView
Microsoft.AspNetCore.Mvc.Localization

@inject IViewLocalizer Localizer

@Localizer["MenuItem_AboutUs"]

STARTUP
services.AddMvc(options =>

            {
    options.Filters.Add(typeof(MyAuthorizeAttribute));

})
                    // Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml
                    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                    // Add support for localizing strings in data annotations (e.g. validation messages) via the
                    // IStringLocalizer abstractions.
                    .AddDataAnnotationsLocalization(); services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("en"),
                new CultureInfo("fr")
            };

// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");

// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;

 // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
            options.SupportedUICultures = supportedCultures;
        });
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{
    loggerFactory.AddFile("Logs/GWP-{Date}.log");

    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();

    app.UseRequestLocalization(locOptions.Value);`

CONTROLLER
namespace Web.Controllers
{
    public class IndexController : BaseController
    {
        private readonly IAppSettings appSettings;
        private readonly IStringLocalizer<IndexController> localizer;
        public IndexController(IAppSettings appSettings, IStringLocalizer<IndexController> localizer) : base(appSettings)
        {
            this.localizer = localizer;
        }

        [AllowAnonymous]
        public IActionResult Index()
        {
            ViewData["MenuItem_AboutUs"] = localizer["MenuItem_AboutUs"];
            return View();
        }
    }
}`

A: You're almost there. Just keep consistent directory structure.
By the way, you've configured a supportedCultures in your startup class :
var supportedCultures = new[]
{
    new CultureInfo("en"),
    new CultureInfo("fr")
};

But your resx files are :

*

*_Header.en.resx

*_Header.resx

*_Header.tr.resx

There seems a typo. You should rename the last resource file as _Header.fr.resx.
How to in details
The default partial view resides in Views/Shared folder. You can also create your own partial folder:
Views/
    Home/
    Index/
        Index.cshtml
    Shared/
        _HeaderPartial.cshtml
    PartialViews/
        _Header2Partial.cshtml

Your directory structure of resource should be
Resources/
    Controllers/
        IndexController.fr.resx
    Views/
    Shared/
        _HeaderPartial.fr.resx
    PartialViews/
        _Header2Partial.fr.resx

When you want to use the localizer, simply using the namespace and inject a service :
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

you can use @Localizer[] now

Test Case :
partial view of Views/Shared/_HeaderPartial.cshtml:
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

This is header from partial : @Localizer["hello world"]

The Shared/_HeaderPartial.fr.resx:
|    Name          |     value                                      |
|------------------+------------------------------------------------+
| hello world      |    Bonjour le monde (from `/Shared/` folder)   |

The PartialViews/_Header2Partial.cshtml :
|    Name          |     value                                       |
|------------------+-------------------------------------------------+
| hello world      | Bonjour le monde (from `/PartialViews/` folder) |

resource files :

the rendered page :


text:
Q: Is every 1-Lipschitz homeomorphism $f:X\to X$ from a compact metric space to itself an isometry? I found a statement involving a homeomorphism $f:X\to X$ of a compact metric space $X$, with Lipshitz coefficient 1, i.e., a non-expansive map, and cannot think of an example where $f$ is not an isometry. Must it be?

A: It follows from 1.6.15(1) in "A Course in Metric Geometry" by Burago, Burago, and Ivanov and 1.6.15(2) is a more general statement:

Any distance-noncontracting map from a compact metric space to itself is an isometry.

This statement is needed in the proof that Gromov--Hausdorff metric is a metric.
Also check the solution of 1.12 in my "Pure metric geometry" it is based on a different idea.


text:
Q: Materialize Parallax not showing images in Angular2 application I'm building a webpage with Angular 2 and Materialize CSS; however, when I try to use the Materialize's parallax feature, the images do not show
Here's my Angular2 Component Class:
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `

Parallax Template

A modern responsive front-end framework based on Material Design

            Get Started

flash_on

Speeds up development

We did most of the heavy lifting for you to provide a default stylings that incorporate our custom components. Additionally, we refined animations and transitions to provide a smoother experience for developers.

group

User Experience Focused

By utilizing elements and principles of Material Design, we were able to create a framework that incorporates components and animations that provide more feedback to users. Additionally, a single underlying responsive system across all platforms allow for a more unified user experience.

settings

Easy to work with

We have provided detailed documentation as well as specific code examples to help new users get started. We are also always open to feedback and can answer any questions a user may have about Materialize.

A modern responsive front-end framework based on Material Design

Contact Us

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam scelerisque id nunc nec volutpat. Etiam pellentesque tristique arcu, non consequat magna fermentum ac. Cras ut ultricies eros. Maecenas eros justo, ullamcorper a sapien id, viverra ultrices eros. Morbi sem neque, posuere et pretium eget, bibendum sollicitudin lacus. Aliquam eleifend sollicitudin diam, eu mattis nisl maximus sed. Nulla imperdiet semper molestie. Morbi massa odio, condimentum sed ipsum ac, gravida ultrices erat. Nullam eget dignissim mauris, non tristique erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

A modern responsive front-end framework based on Material Design

  `
})

export class AppComponent {}

As you may have noticed, The first line in my template is an image tag. This image tag works correctly.
However, the other image tags within the parallax container do not work correctly, and whether or not they are locally stored or an external resource doesn't matter.
In my index.html file I have the following code:
<!DOCTYPE html>

    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">

My App

Navbar Link

Navbar Link

        menu

    <my-app>Loading AppComponent content here ...</my-app>

          Made by Materialize

In here, besides including Materialize, Jquery, and Angular2's stuff, I have included two files: styles.css and main.js.
styles.css includes the parallax template's CSS. And the following code belongs to main.js
(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

I can't see any reason for my code not to work, but it isn't. Where have I gone wrong?
While inspecting my app in Chrome, I found that the images had been found with NO 404 errors. The app just doesn't seem to be displaying them.

A: For paralax use this  code:

Parallax

Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling.

For Sidnav use this code

        Logo

Navbar Link

Navbar Link

        menu


text:
Q: Initialization PostgreSQL with Node Js I'm trying to delete some entries based on the creation/expiry date in a PostrgreSQL DB only at the beginning, when the node server starts.
At present I put the line
 DELETE FROM ....db WHERE date <= CURRENT_DATE
in the main route and it works, but that also mean that each time I refresh the page Node gets to execute that line, over and over again.
Is there a way to add a functionality for which the database knows and executes that line only once at the very beginning?
Should I create a different javascript function that fires at the beginning of the server.js file?
I'm using PostgreSQL, NodeJs and Express (no sequelize or similar).
Thanks.

A:
Should I create a different javascript function that fires at the beginning of the server.js file?

Yes.

A: JavaScript is a scripting language, which means that the code gets executed in the outer block (global scope). There is no main() function as in C/C++. So you should just put this line after the database initialization code in the outer program scope.


text:
Q: How to insert integer values to rocksdb like uint64_t? I've tested following code for inserting integer values like uint64_t to the rocksdb database using casting . Is that a correct approach ?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>

#include<unistd.h>
#include<stdint.h>

const char DBPath[] = "/tmp/test_sample";

#include "rocksdb/c.h"

int main(int argc, char **argv){

   // Intialize basic parameters
   rocksdb_t *db;
   rocksdb_options_t *options = rocksdb_options_create();

   // Create the database if it's not already present
   rocksdb_options_set_create_if_missing(options,1);

   // Open database
   char *err = NULL;
   db = rocksdb_open(options,DBPath,&err);
   assert(!err);

   //Put key value
   //Insert insert value to the database
   rocksdb_writeoptions_t *writeoptions = rocksdb_writeoptions_create();
   int intKey = 256;
   int intValue = 256*256;

   const char* key;
   const char* value;

   //Convert integer value to char array
   key = (char*)&intKey;
   value = (char*)&intValue ;

   rocksdb_put(db,writeoptions,key,strlen(key),value,strlen(value) + 1,&err);

   assert(!err);

   //Cleanup
   rocksdb_writeoptions_destroy(writeoptions);
   rocksdb_options_destroy(options);
   rocksdb_close(db);

   return 0;
}

I have referred the following reference Can integer keys / values be stored in LevelDB?

A: Your approach is not portable. What you do is to just dump the integer representation into the binary field. If the code de-serializing your int has a different understanding of int, this won't work. You should use a serialization library to get a stable binary representation of the int, e.g. protobuf/flatbuffers.
How likely is this to blow up in your face? I don't know, depends on your system. Note that rocksdb internally uses serialized representations for all integer types: util/coding.h

A: There is one major difference between the linked post and your own code: they use sizeof while you use strlen. strlen searches the memory for a null byte. It only makes sense when you really have a null terminated character string.
Here you want to store an integer data, no matter whether it contains null bytes of not. So you must declare the size of that data to be sizeof(int):
rocksdb_put(db,writeoptions,key,sizeof(int),value,sizeof(int),&err);


text:
Q: Why throw local variable invokes moves constructor? Recently, I've "played" with rvalues to understand their behavior. Most result didn't surprize me, but then I saw that if I throw a local variable, the move constructor is invoked.
Until then, I thought that the purpose of move semantics rules is to guarantee that object will move (and become invalid) only if the compiler can detect that it will not be used any more (as in temporary objects), or the user promise not to use it (as in std::move).
However, in the following code, none of this condition held, and my variable is still being moved (at least on g++ 4.7.3).
Why is that?
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s="blabla";
    try {
        throw s;
    }
    catch(...) {
        cout<<"Exception!\n";
    }
    cout<<s; //prints nothing
}

A: C++ standard says (15.1.3):
Throwing an exception copy-initializes (8.5, 12.8) a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable named in the matching handler (15.3).
This paragraph may be also relevant here (12.8.31):

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object
occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

(...)

— in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object
Checked in Visual Studio 2012, effect:
Exception!
blabla

It looks like a bug in GCC indeed.

A: In the given case, it is probably a compiler bug, because the variable thrown (and moved from) is referenced afterwards.
In general case invoking move on throw is conceptually same as moving on return. It is good to invoke move automatically when it is known that the variable could not be referenced after the given point (throw or return).


text:
Q: Am I using Student's t-test correctly for feature selection? I have a $198$-sample dataset containing miRNA types (numerical features) and one categorical feature "Type" with values "Tumor" or "Healthy".
  Index     miRNA1          miRNA2          miRNA3            Type
   1       48421.52        24242.14        23842.1518        Tumor
   2       2757.96         28965.2         7339.57           Healthy
   3       4300.34         52565.07        6981.41           Healthy
           ...             ...             ...
   198     23854.73        24722.28        7611.53           Tumor

Since there are 1584 of these features in total, I need to select the ones that are most influential towards developing a Tumor.
My approach is described below. Is it correct?
The distributions of features are mostly log-normal. I've transformed each feature with a Box-Cox transformation to get approximately normal distributions. I scaled the values with Min-Max scaler to put them in range $[0,1]$.
miRNA1 has $100$ Healthy samples and $98$ Tumor samples. I should make a null hypothesis that Tumor samples have the same values as Healthy samples. I calculate mean and standard deviation for Tumor samples and Healthy samples, calculate the t-score and calculate the p-value, using significance level of $0.05$ and DF in this case is $97$. This is a two-tails test so it is $p$-value $\times 2$. If it's lower than $0.05$ I reject the null hypothesis and consider miRNA1 as a feature that impacts Tumor development, right?

A: First, what you have is high-dimensional data. This alone poses some problems and you should use a method which was designed for this, which is better suited.
Second, a regular t-test is a bad idea in this case, it is a univariate test - meaning it does not consider multiple variables together and their possible interactions. Also, p-values are not meant to be used for feature selection.
Nonetheless, if you are fixed on a t-test, it would be better to use a permutation test to test for significance, as you have many variables which will lead to some serious corrections, when you adjust your p-values for multiple testing, and you will adjust them, right?
Finally, personally I would use LASSO regression to solve this, which is a better and simpler option, LASSO automatically performs feature selection and it considers all the variables together, rather than one by one.

A: even though there are better options for feature selection but t-test can also be part of your research. What you is did correct up to some extent but you need to take the t-score as your reference for your feature ranking. the higher the t-score value, the better the feature is. I would recommend information theory-based filter methods and you can take the order of features from a decision tree using information gain and based on my experience it worked far way better than the t-test (t-test cannot remove redundancy) and I was even better than embedded feature selection approaches like L1 penalized logistic regression and RF from the point of feature subset compactness.