text:
Q: instantly update info, but only if changes are made in the database swift/firebase In my app, I have a place to show news, located in one of the 4 tab views. For changing the information, all the aspects related to it are stored in firestore (title, subtitle, text). Currently, I'm using addSnapshotListener to fetch the data, because whenever I change the data in firestore it will automatically and instantly update. However, each time the user clicks on the tabview icon related to the news view, a different call to read data is done. I understand that it would cause lots of readings when the user base grow, causing a higher monthly payment to firebase and maybe delay, right? To fix this, the only solution I think about is changing addSnapshotListener to getDocuments. But, if I do any changes on firestore, the user would need to close the app and then open it to see the updated info.
Is there a way to update instantly the info, but only if changes are made in the database?
This is how I get the information from Firestore:
struct Info: Identifiable{
var id: String = UUID().uuidString
var title: String
var subtitle: String
}

class InfoViewModel: NSObject, ObservableObject {
@Published var infos = [Info]()
func fetchData(){
    Firestore.firestore().collection("infos").addSnapshotListener { (querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {return}
        self.infos = documents.compactMap { (queryDocumentSnapshot) -> Info? in
            let data = queryDocumentSnapshot.data()

           if let title = data["title"] as? String,
              let subtitle = data["subtitle"] as? String{
            print("info successful")
            return Info(title: title, subtitle: subtitle)
           }
           else{
            print("info failed")
            return nil
           }
        }
    }
  }

  }

In the view I want to display the info, I have @ObservedObject var infoModel = InfoViewModel(), a ForEach to display the data and then .onAppear(){self.infoModel.fetchData()}
Each time I change to this view when clicking the tabView icon, I get, on debug, 3x "info successful, as I have 3 documents stored on infos collection.
TabBar View:
struct TabBar: View{

@State var current = 0
@StateObject var LocationModel = LocationViewModel()
var body: some View{
    NavigationView{
    TabView(selection: $current) {

        HomeView()
            .tag(0)
            .tabItem {
                Image(systemName: "house")
                Text("início")
            }
        SearchView(LocationModel: LocationModel)
            .tag(1)
            .tabItem {
                Image(systemName: "magnifyingglass")
                Text("buscar")
            }
        CalendarView()
            .tag(2)
            .tabItem {
                Image(systemName: "calendar")
                Text("histórico")
            }
        AccountView()
            .tag(3)
            .tabItem {
                Image(systemName: (self.current == 3 ? "person.fill" : "person"))
                Text("perfil")
            }

    }.accentColor(Color("Color"))
}
  }
  }

Where firestorm data is displayed:
struct HomeView: View{

@StateObject var LocationModel = LocationViewModel()
@StateObject var model = ModelData()
@ObservedObject var infoModel = InfoViewModel()

var body: some View{

            VStack( spacing: 12) {

                ScrollView(.vertical, showsIndicators: false){
                    ScrollView(.horizontal, showsIndicators: false){
                       HStack(spacing: 15){
                           ForEach(infoModel.infos){ info in
                           HStack(spacing: 20){
                           Text(info.title)
                           .frame(height: 220)
                           .frame(width: 330)
                               .background(Color.yellow)
                          .cornerRadius(18)
                           }
                       }

                       }.padding(.horizontal, 15)
                       .padding(.bottom, 25)
                    }

                }

                .navigationBarTitle("").navigationBarHidden(true)
            }.navigationBarTitle("").navigationBarHidden(true)

         .onAppear(perform: {
            LocationModel.locationManager.delegate = LocationModel

            self.infoModel.fetchData()
              })

         .alert(isPresented: $LocationModel.alert, content: {

            Alert(title: Text("Mensagem"), message: Text(LocationModel.alertMsg), dismissButton: .destructive(Text("Pronto").foregroundColor(Color.blue)))
         })
     }

   }

A: Your VC could have a reference to a controller that manages all communication with the Firestore. In that controller, you can init the snapshot listener. That will fetch all your documents once, which you can store as state in that controller. Any .added, .modified and .removed document changes from that point on can just change the state your controller is holding and update the VC with e.g. a closure.


text:
Q: Global variables in a GUI? I am designing an immediate gui using C++ and SDL2. As I was starting to design my framework, I noticed that basically everything needs a renderer or some sort of event or other relevant information (Fonts, Themes, etc.). Does it make sense to put these is global static object that only the gui functions have access to, or just keep passing everything in.
Would this be ok?
This could be the header:
struct GuiForm {
   GuiId active_id;
   GuiId hot_id;
   std::vector<Window> windows;
   Renderer* renderer;
};

Then this could be the .cpp file:
static GuiForm* gui_form;

void SomeGuiWidget() {
   GuiId current_hot_id = gui_form.hot_id;

   /* Whatever the widget is going to do */
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: create a page which contain a flash can be add text dynamiclly I have to create a web page which can be set to full screen(I mean the real full screen,not like press the F11),in the full screen there should be some words displaying.
Take the http://stackoverflow.com for example:
Normally,it show its contents(the questions),but someday,maybe a VIP come to visit the page,so we want to replace the whole page with a welcome screen.
Of course we can replace the https://stackoverflow.com/index.html (suppose it is the index page) with the welcome text(welcome xxx to our site...) in the server side.
However this is not convenient,and the text can not be full screened.
So I thought the flash,I can add a controller button at the page,when required,I click this button,and set the welcome words,then a flash will start to play with the sepcified words in a full screen model. It would be better if the flash can show the text with a Animation.
I have never did the flash development,so I want to know if this is possible?
BTW,can all the clients change to flash with juse one click?
I mean I click the controller button,then all the client who is visit this page should see the contents replaced by the flash at the same time.
I am not sure if you guys know what I am meaning. If not,I can update more details.
I am really Anxious, Thanks. :)

A: Since you're starting from scratch with Flash, I made a quick example of what I think you want to do. http://clearmpls.com/temp/fullscreen/ - the source files that I made this example with can be grabbed from here: http://clearmpls.com/temp/xml-loading-fullscreen-thing.zip
I used the Flash IDE to create this. You can grab a 60-day trial from Adobe's site here: https://www.adobe.com/cfusion/tdrc/index.cfm?product=flash
This example shows examples of these functions:
- it loads an XML file with text data
- displays that data in a textfield on the stage
- gives you a button where you can toggle back and forth between fullscreen and regular
- resizes the stage and textfield based on what you have written in your XML file


text:
Q: error: LNK 2005 when i include regex, vector, or curlpp in c++ CLR I'm new to C++ CLR development. I'm trying to develop a GUI app but when i include vector/regex/curlpp i get an error while compiling LNK 2005. Anyone have any idea how to get around this problem.
I'm using visual studio 2022 version
MyForm.h
#pragma once

namespace Calculator {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::TextBox^ textBox1;
    private: System::Windows::Forms::TextBox^ textBox2;
    private: System::Windows::Forms::Label^ label1;
    private: System::Windows::Forms::Button^ button1;
    private: System::Windows::Forms::Button^ button2;
    private: System::Windows::Forms::Button^ button3;
    private: System::Windows::Forms::Button^ button4;
    private: System::Windows::Forms::TextBox^ textBox3;
    protected:

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->textBox2 = (gcnew System::Windows::Forms::TextBox());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->button3 = (gcnew System::Windows::Forms::Button());
            this->button4 = (gcnew System::Windows::Forms::Button());
            this->textBox3 = (gcnew System::Windows::Forms::TextBox());
            this->SuspendLayout();
            //
            // textBox1
            //
            this->textBox1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->textBox1->Location = System::Drawing::Point(18, 27);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(72, 29);
            this->textBox1->TabIndex = 0;
            //
            // textBox2
            //
            this->textBox2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->textBox2->Location = System::Drawing::Point(194, 27);
            this->textBox2->Name = L"textBox2";
            this->textBox2->Size = System::Drawing::Size(72, 29);
            this->textBox2->TabIndex = 1;
            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, static_cast<System::Drawing::FontStyle>((System::Drawing::FontStyle::Bold | System::Drawing::FontStyle::Italic)),
                System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0)));
            this->label1->Location = System::Drawing::Point(96, 32);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(88, 20);
            this->label1->TabIndex = 2;
            this->label1->Text = L"Operation";
            //
            // button1
            //
            this->button1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->button1->Location = System::Drawing::Point(117, 55);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(45, 43);
            this->button1->TabIndex = 3;
            this->button1->Text = L"+";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
            //
            // button2
            //
            this->button2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->button2->Location = System::Drawing::Point(117, 104);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(45, 43);
            this->button2->TabIndex = 4;
            this->button2->Text = L"-";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
            //
            // button3
            //
            this->button3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->button3->Location = System::Drawing::Point(117, 153);
            this->button3->Name = L"button3";
            this->button3->Size = System::Drawing::Size(45, 43);
            this->button3->TabIndex = 5;
            this->button3->Text = L"*";
            this->button3->UseVisualStyleBackColor = true;
            this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click);
            //
            // button4
            //
            this->button4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->button4->Location = System::Drawing::Point(117, 202);
            this->button4->Name = L"button4";
            this->button4->Size = System::Drawing::Size(45, 43);
            this->button4->TabIndex = 6;
            this->button4->Text = L"/";
            this->button4->UseVisualStyleBackColor = true;
            this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click);
            //
            // textBox3
            //
            this->textBox3->Enabled = false;
            this->textBox3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->textBox3->Location = System::Drawing::Point(18, 251);
            this->textBox3->Name = L"textBox3";
            this->textBox3->Size = System::Drawing::Size(248, 29);
            this->textBox3->TabIndex = 7;
            this->textBox3->Text = L"Result";
            //
            // MyForm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 293);
            this->Controls->Add(this->textBox3);
            this->Controls->Add(this->button4);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->textBox2);
            this->Controls->Add(this->textBox1);
            this->Name = L"MyForm";
            this->Text = L"MyForm";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
        int output = System::Convert::ToInt16(textBox1->Text) + System::Convert::ToInt16(textBox2->Text);
        textBox3->Text = System::Convert::ToString(output);
    }
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
        int output = System::Convert::ToInt16(textBox1->Text) - System::Convert::ToInt16(textBox2->Text);
        textBox3->Text = System::Convert::ToString(output);
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
        int output = System::Convert::ToInt16(textBox1->Text) * System::Convert::ToInt16(textBox2->Text);
        textBox3->Text = System::Convert::ToString(output);
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
        double output = System::Convert::ToDouble(textBox1->Text) / System::Convert::ToDouble(textBox2->Text);
        textBox3->Text = System::Convert::ToString(output);
}
};
}

MyForm.cpp
#include "MyForm.h"
#include <iostream>

using namespace System;

using namespace System::Windows::Forms;

[STAThread]

void main(array<String^>^ args)

{

    Application::EnableVisualStyles();

    Application::SetCompatibleTextRenderingDefault(false);

    Calculator::MyForm form;

    Application::Run(% form);

}

when i compile this i get this error
Error i get when i compile the above code
Kindly help me fix it.


text:
Q: I want to Post a Json Object of given format in windows phone Earlier I used to make object like:
JObject json = new JObject(
                     new JProperty("user", user,
                     new JProperty("credit", credit),
                     new JProperty("name", name)
                   );

But in this case I want a loop inside the When I am making the Json Object and for its formatting I was using JsonConvert.SerializeObject(data, jsSettings) but I find \ and / slashes and the format what I needed is not in that format.
Json Format :

{
    "user":some value
    "credit":some value
    "data":[
        { "friend":some value
           "friend_list:some value"
        },
        {},..
    ]
}

A: You can use DataContractJsonSerializer and json2Csharp to parse  json object
here are the small example, that may help you.
  MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
   //here are the parse data
RootObject itemDataList = dataContractJsonSerializer.ReadObject(memoryStream) as RootObject;

A: Use : http://james.newtonking.com/json the best json library then try this example
Product p1 = new Product
 {
   Name = "Product 1",
   Price = 99.95m,
   ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
 };
 Product p2 = new Product
 {
   Name = "Product 2",
  Price = 12.50m,
  ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};
List products = new List();
products.Add(p1);
products.Add(p2);
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
for more reference you can check this link : http://james.newtonking.com/json/help/index.html


text:
Q: Changing VSCode-Vim Indent to 4 spaces I am using VSCode's  Vim extension and it seems like the tabs are set to two spaces, but I want to change this because I work mostly in Python, which uses 4 spaces. I have found several posts/articles about changing tab spacings in Vim, but at first glance they don't seem wholly applicable since this is a VS-Code extension. I have one pre-existing mapping that I have added below.
Current Key Remap
    "vim.insertModeKeyBindings": [
        {
            "before": ["j", "j"],
            "after": ["<Esc>"]
        }
    ],

The structure should follow similar to that above, but ideally I would want my normal mode tabbing to be something like shift >  > (which is the default) but with 4 spaces instead of whatever it currently is.

A: Solution
Try running: :set noexpandtab as per this wiki page.
I was having the same issue, specifically [tab] would add tabs, but the o command in Normal Mode would insert spaces on the new line. Seems to be working all around.
VSCode Settings
I would like to post my indent and tab settings so people can compare incase that's the problem as well. Please forgive my screenshots of the settings UI, I cannot be bothered going through all that JSON.

Please let me know if I missed any relevant ones in the comments.
Or, the opposite:
It may be of use to folks who are trying to do the opposite, i.e., go from tabs to spaces, that they should use :set expandtab.

A: I think you just have to modify in Visual Studio Code settings and not in the Vim settings.
See the post here that resume the way to do it.


text:
Q: Parallel evaluation and memory use I have never used Mathematica's parallel evaluation before and have some trouble getting it to work properly. For the record, I am running Mathematica 9 on Linux with an Intel Core i7 processor (4 physical cores).
I have a function Foo that performs randomised numerical calculations with some matrices and returns a small list. I am interested in running it multiple times and collecting the results, so if I use Table on one kernel, everything works fine and I experience no issues. I then attempt to parralelise it with something like:
LaunchKernels[2];
DistributeDefinitions[Foo];

ParallelTable[Foo[bar], {10000}];

Two kernels work fine as well, but in that case Mathematica starts to use up to 10GB of RAM. Running four kernels, however, causes a lot more problems. Mathematica quickly uses up all of my 16GB of RAM leaving the computer literally unusable, complains about running out of memory all the time and keeps shutting down kernels. Even if I get my results, I am often unable to use them because any operation on the returned list causes the shutdown of the main kernel and the loss of all data. MaxMemoryUsed[] gives 37 686 808.
I have tried alternative approaches with ParallelDo and some stranger constructs (motived by wanting to be able to stop the calculations and retain all the results obtained so far) such as
a = {};
Do[
 AppendTo[a, ParallelTable[Foo[bar], {100}]],
{100}]

but these cause an even faster kernel failure due to the lack of memory.
I should also mention that after I stop using 4 kernels and go back to 1-kernel calculations, I frequently run into some random "No more memory available. Mathematica kernel has shut down. Try quitting other applications and then retry." even though Mathematica is not even using much of my system memory at this point. This does not happen prior to attempting 4-kernel evaluation in the same session.
Am I approaching this problem incorrectly? Resources on the internet about Mathematica's parallel evaluation are sparse, so I was unable to find much information. One thread here on StackExchange mentioned that calling  ClearSystemCache[] in the function can free up some memory used by Mathematica in parallel computations, but it seems to have no effect at all.
I would appreciate any information and help. Thank you.

A: On a regular basis i have subkernels eating up my Memory. Still have not a great solution however if finished anyway (Or between two ParallelTables) I handle this problem via:
CloseKernels[];LaunchKernels[];
This frees the memory of the subkernels.


text:
Q: DbContext & DbcontextPool in ef-core I read a lot of documents and articles about DBcontext in Efcore and its lifetime, however, I have some questions.
Based on this link "https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/" the best lifetime of DBcontext and default lifetime of AddDbContext is scope, but there is a contradiction in the two below sentences on this document.

"DbContext is not thread-safe. Do not share contexts between
threads. Make sure to await all async calls before continuing to use
the context instance."

on the other hand, it was mentioned too,

"Dbcontext is safe from concurrent access issues in most
ASP.NET Core applications because there is only one thread executing
each client request at a given time, and because each request gets
a separate dependency injection scope (and therefore a separate
DbContext instance)."

*

*I was confused about whether registering DBcontext as a scoped service is thread-safe or not?

*What are the problems of registering DBcontext as a singleton service in detail?

In addition, I read some docs that prohibit registering singleton DbContext, however, AddDbContextPool makes to register singleton DBcontext.
so there are some questions about the Dbcontextpool.

*what are the impacts of using the DbContextPool instead of the DbContext?

*when we should use it and what should be considered when we use contextPool?

*DbContextPool is thread-safe?

*Has it memory issues because of storing a number of dbset instances throughout the application's lifetime?

*change-tracking or any parts of the ef would be failed or not in the DB context pool?

One DbContext per web request... why?
.NET Entity Framework and transactions

A: I understand why you think the language in the Microsoft documents is confusing. I'll unravel it for you:

*

*"DbContext is not thread-safe." This statement means that it's not safe to access a DbContext from multiple threads in parallel. The stack overflow answers you already referenced, explain this.

*"Do not share contexts between threads." This statement is confusing, because asynchronous (async/await) operations have the tendency to run across multiple threads, although never in parallel. A simpler statement would be: "do not share contexts between web requests," because a single web request typically runs a single unit of work and although it might run its code asynchronously, it typically doesn't run its code in parallel.

*"Dbcontext is safe from concurrent access issues in most ASP.NET Core applications": This text is a bit misleading, because it might make the reader believe that DbContext instances are thread-safe, but they aren't. What the writers mean to say here is that, with the default configuration (i.e. using AddDbContext<T>(), ASP.NET Core ensures that each request gets its own DbContext instance, making it, therefore, "safe from concurrent access" by default.

1 I was confused about whether registering DBcontext as a scoped service is thread-safe or not?

DbContext instances are by themselves not thread-safe, which is why you should register them as Scoped, because that would prevent them from being accessed from multiple requests, which would make their use thread-safe.

2 What are the problems of registering DBcontext as a singleton service in detail?

This is already described in detail in this answer, which you already referenced. I think that answer goes into a lot of detail, which I won't repeat here.

In addition, I read some docs that prohibit registering singleton DbContext, however, AddDbContextPool makes to register singleton DBcontext. so there are some questions about the Dbcontextpool.

The DbContext pooling feature is very different from registering DbContext as singleton, because:

*

*The pooling mechanism ensures that parallel requests get their own DbContext instance.

*Therefore, multiple DbContext instances exist with pooling, while only a single instance for the whole application exists when using the Singleton lifestyle.

*Using the singleton lifestyle, therefore, ensures that one single instance is reused, which causes the myriad of problems laid out (again) here.

*The pooling mechanism ensures that, when a DI scope ends, the DbContext is 'cleaned' and brought back to the pool, so it can be reused by a new request.

what are the impacts of using the DbContextPool instead of the DbContext?

More information about this is given in this document.

when we should use it and what should be considered when we use contextPool?

When your application requires the performance benefits that it brings. This is something you might want to benchmark before deciding to add it.

DbContextPool is thread-safe?

Yes, in the same way as registering a DbContext as Scoped is thread-safe; in case you accidentally hold on to a DbContext instance inside an object that is reused accross requests, this guarantee is broken. You have to take good care of Scoped objects to prevent them from becoming Captive Dependencies.

Has it memory issues because of storing a number of dbset instances throughout the application's lifetime?

The memory penalty will hardly ever be noticable. The so-called first-level cache is cleared for every DbContext that is brought back to the pool after a request ends. This is to prevent the DbContext from becoming stale and to prevent memory issues.

change-tracking or any parts of the ef would be failed or not in the DB context pool?

No, it doesn't. For the most part, making your DbContext pooled is something that only requires infrastructural changes (changes to the application's startup path) and is for the most part transparent to the rest of your application. But again, make sure to read this to familiar yourself with the consequences of using DbContext pooling.


text:
Q: Pop up on ajax success I have this modal pop up when a link is clicked. It has a text area and 2 buttons: Send and cancel
   Message

Create A Message

                    <textarea  id = 'msgContent' cols="48" rows="10" ></textarea>

                        Send

                        cancel

Message sent

                        OK

and i have this code in ajax success when the send button is clicked
  success: function(result)
                        {

                            if (result == true)
                            $( "#success" ).dialog( "" );

                        }

I am working on showing another pop up when the ajax is successful. But I have no idea how to call

A: What you do is check if ajax call is success by keeping an alert in it.
success: function(result){
      if (result == true)
        alert('working');
      else
        alert('not working');

}
if your alert i 'working' then check if you are including jqueryui https://jqueryui.com/dialog/
dialog() is a jquery ui function not a javascript predefine function.


text:
Q: USB stick made with UNetbootin missing BOOTMGR.
Possible Duplicate:
Ubuntu not booting from USB on laptop (no optical drive)

I downloaded 12.04 32-bit ISO and am trying to make a USB stick with it for me to boot from and install on my HD. I followed the instructions in UNetbootin but my USB stick is missing its bootmgr so it won't boot.
Any advice? I don't have a CD-burner nor a CD-ROM on my laptop which I am trying to install on.

A: If you're using some linux distro to make the live USB, you can use the commands given in the following link:
How to make an Ubuntu live USB stick in Fedora?
If you're using Windows, you can try any other Live USB creating software such as YUMI (Your Universal Multiboot Installer) or LinuxLive USB Creator.


text:
Q: how to get fileds which matches a string in text file using php Hi i have a text file
=====1st record
name:sam
designation:developer
area:usa

=====2nd record
name:john
designation:tester
area:canada

like this i have some records(not in same order), my requirement is to extract all "designation" fields with values, how to write a batch file to extract this.
Thanks

A: try this:
<inputfile>outputfile findstr /i "designation"
type outputfile


text:
Q: msbuild - how to modify environment variable for the entire build I want to modify the environment variable for all Exec tasks.
This answer seems to imply that it's not possible to do that and a 2011 blog says outright that it's not possible to change the environment per Exec task . . . so does that mean that it's not possible even to set the environment variable for ALL Exec tasks globally?
Is this possible? If yes, how do I do it?


text:
Q: Need Pattern for lookup tables in Google App Engine I'm using the Python version of Google App Engine and Datastore.  What is a good way to load a table that will contain lookup data?
By look up data I mean that after the initial load no rows will need to be inserted, deleted, or updated
Blowing away all rows and reloading the table is not acceptable if it destroys referential integrity with other rows referring to it.
Here is an example of a couple kinds that I am using that I want to load lookup data into
class Badge(db.Model):
    name = db.StringProperty()
    level = db.IntegerProperty()

class Achievement(db.Model):
    name = db.StringProperty()
    level = db.IntegerProperty()
    badge = db.ReferenceProperty(reference_class=Badge)

Here is an example of a kind not holding look up data but referring to it
class CamperAchievement(db.Model):
    camper = db.ReferenceProperty(reference_class=Camper)
    achievement = db.ReferenceProperty(reference_class=Achievement)
    session = db.ReferenceProperty(reference_class=Session)
    passed = db.BooleanProperty(default=True)
I'm looking to find out two things:
What should the code to load the data look like?
What should trigger the loading code to execute?

A: If it's really created once and never changes within the lifetime of a deployment, and it's relatively small (a few megs or less), store it with your app as data files. Have the app load the data into memory initially, and cache it there.

A: I think you're referring to some kind of write-behind cache but it is not really that clear from your question.
This is a common pattern for reading data slow a slow source (like a database/disk) and caching it in a fast source (like memcache/memory) for quick retrieval later. It is then your responsibility to empty out all the cached items when things change.
See the first example on Using memcache


text:
Q: Using Cypher can I find a specific relationship between 2 distant nodes I have 2 nodes not directly related to one another I know the start node, the end node and the relationship on the end node. For example
(u:USER)-[]->()-[]->()-[:WRITE]->(p:POST)
Is there a query I can write that would return 'p' to me? Also all the relationship in between are not WRITE, so I can't use [:WRITE*]

Secondary question: I'm thinking about permissions and relationships. In my model the User has a relationship on some entity and that entity to another all the way to a WRITE relationship on POST, and I want to therefore say the USER has WRITE on POST. But maybe I'm thinking about this wrong? Maybe I should just be giving USER WRITE on POST directly?
Thank you!

A: One of the great advantages of Neo4j over relational databases is that you don't have to know the labels of nodes or how they are related to perform a useful query.
If you try
(u:User)-[*]->()-[:WRITE]->(p:Post) return p

it should give you what you want.
The structure of your graph will determine the efficiency of this query. If the graph between :USER and :POST is essentially a tree, then the above query should be quite efficient. However, if the intervening nodes and relationships form a network, then the query could spend significant time exploring all paths between :User and :Post in which case your idea of linking :User to :Post via a single relationship would be beneficial.


text:
Q: Drupal 7 - Hide node from views_embed_view I am using views 3 and drupal 7. I have a view setup where it will return all related articles based on the keywords which works perfectly.
The problem is that I don't want the article that I'm on to show up in the results. Is there a way to hide specific nodes from displaying? For instance, lets say I have nodes: 43908 and 43909 that I don't want to show up in the view.
I've added a filter criteria (not contextual filter) to remove these nodes, but is it possible to combine node ID's into one filter? So if I wanted to show all but 43908 and 43909 how would I do that? I've tried to add them as 43908+43909 but that didn't seem to work.

A: You can use the regular expression option for the nid filter.  So for the nid you mention you would do:
[^43908|^43909]

This filters out nodes with nid 43908 and 43909.
As for the scenario you describe, I think a better approach would be to add a separate field to your content type, e.g. field_in_progress, a tick box only visible when editing. Then you can add a filter on that field for the view.

A: This article may help. It involves excluding the current node from a list view.


text:
Q: How to divide string by empty space in Java So, I have the following situation:
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String line= reader.readLine();
String first = ?
String second = ?

So, I know that user will enter something like this: love cats and dogs.
I want that the first word (in this case love) is always in String first and everything else in String second. How can I do it as simple as possible?

A: String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);

String first = parts[0];
String second = parts[1];

A: Simply:
int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);


text:
Q: Sed error "sed: -e expression #1, char [#]: extra characters after command"
sed '/\r$/ {N s/\n//}'
  sed: -e expression #1, char 10: extra characters after command

I want to understand what is wrong with my command line.
When I can do the some of following in a script but not in a command line.
I have been working through the tutorial at www.grymoire.com. When I got stuck at the section
Working with Multiple Lines. These script works fine.

#!/bin/sh
sed '
# look for a "#" at the end of the line
/#$/ {
# Found one - now read in the next line
    N
# delete the "#" and the new line character,
    s/#\n//
}' file

In my case I am looking for \r or return ^M.

#!/bin/sh
sed '
# look for a "#" at the end of the line
/\r$/ {
# Found one - now read in the next line
    N
# delete the "#" and the new line character,
    s/\r\n//
}' file

The problem is when I try to convert it to a single line shell command it gives me an errors.

sed '/\r$/ {N s/\n//}'
  sed: -e expression #1, char 10: extra characters after command
  sed '/\r$/{N s/\n//}'
  sed: -e expression #1, char 9: extra characters after command
  sed '/\r$/{Ns/\n//}'
  sed: -e expression #1, char 8: extra characters after command

I want to understand what is wrong with my command line.
When I can do the following in a script but not in a command line.
I have created a sed script to do the work I want.

cat test.sed
#!/bin/sed -f
/\r$/ {
N
s/\n//
}

A: You need to use a semicolon ; to separate sed commands on the same line. Specifically, between the N and s.  No semicolon is needed when there is a newline which is why your script form works.
change
sed '/\r$/ {N s/\n//}'

to
sed '/\r$/ {N; s/\n//}'
             ^


text:
Q: Validação com método clean no Django 2.0 No meu Model tem esse método abaixo:
def clean(self, *args, **kwargs):
        valortotal = Venda.objects.filter(id=self.id).aggregate(valortotal=Sum(F('item__produto__valor') * F('item__qtde'), output_field=FloatField()))
        valor_nota = self.valor_nota
        if Decimal(valortotal['valortotal']) < valor_nota():
         raise forms.ValidationError("O  valor do Tipo de Pagamento (dinheiro + cartão) não pode ser maior que o valor total da nota.")
        #raise forms.ValidationError(Decimal(valortotal['valortotal']))

Mais ao salvar o sistema aparece o erro:

Alguém sabe alguma solução para isso.


text:
Q: Why can't I use OpenGL ES 3.0 in Qt? I set a QSurfaceFormat on my window, and this surface format has "3.0" set as its GL version number. The code:
static QSurfaceFormat createSurfaceFormat() {
    QSurfaceFormat format;
    format.setSamples(4);
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setVersion(3, 0);
    return format;
}

int main(int argc, char *argv[]) {
    // ...

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    QWindow* window = (QWindow*) engine.rootObjects().first();
    window->setFormat(::createSurfaceFormat());

    // ...
}

Also, in main() I enable OpenGL ES mode, like this:
QGuiApplication::setAttribute(Qt::AA_UseOpenGLES);

This means I'm requesting a GL ES 3.0 context.
The ANGLE docs say (in a table near the beginning) that GL ES 3.0 -> D3D 11 API translation support is implemented. And my system supports D3D 11 according to dxdiag.exe.
But when I launch my app, which contains this QML code...
Text {
    text: OpenGLInfo.majorVersion + "." + OpenGLInfo.minorVersion
}

... I see "2.0" is displayed. Also, using the method I described here, I've determined that the maximal supported shading language version on my PC is "100" aka 1.0.
At the same time, from this Qt blog post I know that Qt supports GL ES 3.0 apps.
So why can't I use OpenGL ES 3.0 in Qt?

A: You need to set a QSurfaceFormat on a QWindow before the window itself is created (via create()). If you create top level windows via QML you have no control on when create() gets actually called, so a solution is changing the default surface format somwhere before you create your Q(Gui)Application:
int main(int argc, char **argv) {
    // createSurfaceFormat() is the function you pasted above
    QSurfaceFormat::setDefaultFormat(createSurfaceFormat());

    QApplication app(argc, argv);
    // etc.


text:
Q: Entity Framework Core with Multiple Foreign Key On Same Column I have 3 tables with relationship to the same TransactionLog.DocumentId column.
I differentiate the Foreign Key with DocumentTypeId:
1 - Invoice,
2 - DebitNote,
3 - CreditNote

I scaffold the entities:
public partial class TransactionLog
{
    public int TransactionLogId { get; set; }
    public int? DocumentId { get; set; }
    public int? DocumentTypeId { get; set; }
    public decimal? Amount { get; set; }

    public CreditNote CreditNote { get; set; }
    public Invoice Invoice { get; set; }
    public DebitNote DebitNote { get; set; }
}

public partial class Invoice
{
    public Invoice()
    {
        TransactionLog = new HashSet<TransactionLog>();
    }

    public int InvoiceId { get; set; }
    public string InvoiceNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> TransactionLog { get; set; }
}

public partial class DebitNote
{
    public DebitNote()
    {
        TransactionLog = new HashSet<TransactionLog>();
    }

    public int DebitNoteId { get; set; }
    public string DebitNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> TransactionLog { get; set; }
}

public partial class CreditNote
{
    public CreditNote()
    {
        TransactionLog = new HashSet<TransactionLog>();
    }

    public int CreditNoteId { get; set; }
    public string CreditNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> TransactionLog { get; set; }
}

I want to insert 1 record to each of the table Invoice, DebitNote and CreditNote, and 3 records for each transaction to TransactionLog.
And this is my code:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<CreditNote>(entity =>
        {
            entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");

            entity.Property(e => e.CreditNoteNumber)
                .HasMaxLength(50)
                .IsUnicode(false);
        });

        modelBuilder.Entity<DebitNote>(entity =>
        {
            entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");

            entity.Property(e => e.DebitNoteNumber)
                .HasMaxLength(50)
                .IsUnicode(false);
        });

        modelBuilder.Entity<Invoice>(entity =>
        {
            entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");

            entity.Property(e => e.InvoiceNumber)
                .HasMaxLength(50)
                .IsUnicode(false);
        });

        modelBuilder.Entity<TransactionLog>(entity =>
        {
            entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");

            entity.HasOne(d => d.CreditNote)
                .WithMany(p => p.TransactionLog)
                .HasForeignKey(d => d.DocumentId)
                .HasConstraintName("FK_TransactionLog_CreditNote");

            entity.HasOne(d => d.DebitNote)
                .WithMany(p => p.TransactionLog)
                .HasForeignKey(d => d.DocumentId)
                .HasConstraintName("FK_TransactionLog_DebitNote");

            entity.HasOne(d => d.Invoice)
                .WithMany(p => p.TransactionLog)
                .HasForeignKey(d => d.DocumentId)
                .HasConstraintName("FK_TransactionLog_Invoice");
        });
    }

However, the DocumentId doesn't save the correct InvoiceId, CreditNoteId, DebitNoteId. I check with SQL Profiler, it will always get the first scope_identity() of the 3 inserts, which in my case is CreditNoteid.

Any idea how to get the correct Id from Invoice, CreditNote and DebitNote ?
Or shouldn't I use relationship in this case.
If not, what is the best practice of logging the transaction into the log?

A: Add the following configurations in your DbContext and then add a migration and update the database accordingly.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Invoice>().HasMany(i => i.TransactionLog).WithOne(tl => tl.Invoice).HasForeignKey(tl => tl.DocumentId);
    modelBuilder.Entity<DebitNote>().HasMany(dn => dn.TransactionLog).WithOne(tl => tl.DebitNote).HasForeignKey(tl => tl.DocumentId);
    modelBuilder.Entity<CreditNote>().HasMany(cn => cn.TransactionLog).WithOne(tl => tl.CreditNote).HasForeignKey(tl => tl.DocumentId);
}

A: I think maybe the Foreign Key's direction is wrong.
As your table definition, the TransactionLog.DocumentId's value must be exist in the three tables (Invoice CreditNote DebitNote) at the same time. So, if only insert two of them, there will maybe have a Exception.

I think you really want table definition is like this.
I delete TransactionLog.DocumentId column and add FKs from the PK of the three tables to TransactionLog.TransactionLogId.

the entities:
public partial class TransactionLog
{
    public int TransactionLogId { get; set; }
    public Nullable<int> DocumentTypeId { get; set; }
    public Nullable<decimal> Amount { get; set; }

    public virtual CreditNote CreditNote { get; set; }
    public virtual DebitNote DebitNote { get; set; }
    public virtual Invoice Invoice { get; set; }
}

public partial class Invoice
{
    public int InvoiceId { get; set; }
    public string InvoiceNumber { get; set; }
    public decimal Amount { get; set; }

    public virtual TransactionLog TransactionLog { get; set; }
}

public partial class CreditNote
{
    public int CreditNoteId { get; set; }
    public string CreditNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public virtual TransactionLog TransactionLog { get; set; }
}

public partial class DebitNote
{
    public int DebitNoteId { get; set; }
    public string DebitNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public virtual TransactionLog TransactionLog { get; set; }
}

code:
Invoice invoice = new Invoice() { InvoiceNumber = "Inv0100", Amount = 66m };
TransactionLog invoiceLog = new TransactionLog() { Amount = invoice.Amount, DocumentTypeId = 1 };
invoice.TransactionLog = invoiceLog;
_context.Invoices.Add(invoice);

CreditNote creditNote = new CreditNote() { CreditNoteNumber = "DN003", Amount = 99.99m };
TransactionLog creditNoteLog = new TransactionLog() { Amount = creditNote.Amount, DocumentTypeId = 2 };
creditNote.TransactionLog = creditNoteLog;
_context.CreditNotes.Add(creditNote);

DebitNote debitNote = new DebitNote() { DebitNoteNumber = "CN009", Amount = 77.77m };
TransactionLog debitNoteLog = new TransactionLog() { Amount = debitNote.Amount, DocumentTypeId = 3 };
debitNote.TransactionLog = debitNoteLog;
_context.DebitNotes.Add(debitNote);

A: I guess you have a wrong relationship there. like one transaction can have multiple invoices but an invoice will have only one transaction record. I might be wrong because sometimes it feels like one-to-one but anyways I gave it a try and here is what you want.
the entities:
public class TestMVCEntities : DbContext
{

    public TestMVCEntities()
        : base("name=TestMVCEntities")
    {
    }

    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<DebitNote> DebitNotes { get; set; }
    public DbSet<CreditNote> CreditNotes { get; set; }
    public DbSet<TransactionLog> TransactionLogs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TransactionLog>()
            .HasRequired(p => p.Invoice)
            .WithMany(p => p.InvoiceLog)
            .HasForeignKey(p => p.DocumentId);

        modelBuilder.Entity<TransactionLog>()
            .HasRequired(p => p.DebitNote)
            .WithMany(p => p.DebitLog)
            .HasForeignKey(p => p.DocumentId);

        modelBuilder.Entity<TransactionLog>()
            .HasRequired(p => p.CreditNote)
            .WithMany(p => p.CreditLog)
            .HasForeignKey(p => p.DocumentId);
    }
}

public partial class TransactionLog
{
    public int TransactionLogId { get; set; }
    public int? DocumentId { get; set; }
    public int? DocumentTypeId { get; set; }
    public decimal? Amount { get; set; }

    public CreditNote CreditNote { get; set; }
    public Invoice Invoice { get; set; }
    public DebitNote DebitNote { get; set; }
}

public partial class Invoice
{
    public int InvoiceId { get; set; }
    public string InvoiceNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> InvoiceLog { get; set; }
}

public partial class DebitNote
{
    public int DebitNoteId { get; set; }
    public string DebitNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> DebitLog { get; set; }
}

public partial class CreditNote
{
    public int CreditNoteId { get; set; }
    public string CreditNoteNumber { get; set; }
    public decimal Amount { get; set; }

    public ICollection<TransactionLog> CreditLog { get; set; }
}

and to insert data:
var invoice = new Invoice()
    {
        InvoiceNumber = "Inv099",
        Amount = 66m,
        InvoiceLog = new Collection<TransactionLog>()
        {
            new TransactionLog(){DocumentTypeId = 1, Amount = 66m}
        }
    };

    var creditNote = new CreditNote()
    {
        CreditNoteNumber = "DN002",
        Amount = 99.99m,
        CreditLog = new Collection<TransactionLog>()
        {
            new TransactionLog(){DocumentTypeId = 3, Amount = 99.99m}
        }
    };

    var debitNote = new DebitNote()
    {
        DebitNoteNumber = "CN008",
        Amount = 77.77m,
        DebitLog = new Collection<TransactionLog>()
        {
            new TransactionLog(){DocumentTypeId = 2, Amount = 77.77m}
        }
    };

    using (var context = new TestMVCEntities())
    {
        context.Invoices.Add(invoice);
        context.CreditNotes.Add(creditNote);
        context.DebitNotes.Add(debitNote);
        context.SaveChanges();
    }

and the table will look like this:


text:
Q: How do I use content containing razor markup as a parameter for a method? What I am trying to do is to be able to write javascript blended with razor styled markup and methods inside .cshtml file and send this to a separate method for usage later on.
My .cshtml looks something like this:
@{SomeClass.SaveForLater(@<script type="text/javascript">window.alert('@Model.SomeParamter')}</script>);

And inside the class SomeClass:
public static void SaveForLater(HtmlString str) {
    // will be using str.ToString() here and save the string output for use later on.
}

But what I receive is this error message:
CS1660: Cannot convert lambda expression to type 'System.Web.HtmlString' because it is not a delegate type
Am I using the wrong type for the argument or do I need to rethink the whole concept?
Solution
Thanks to SLaks below I ended up doing this:
public static void SaveForLater<T>(Func<T, HelperResult> template, dynamic model)
{
    // template(model).ToHtmlString()
}

Using it like this:
 @{SomeClass.SaveForLater<SomeModel>(
        @<script type="text/javascript">window.alert('@Model.SomeParamter')</script>,
        Model
        );

A: You're trying to take an inline helper.
You need to accept a Func<Something, HelperResult>.


text:
Q: Add colon (:) after every 2nd character using Javascript I have a string and want to add a colon after every 2nd character (but not after the last set), eg:

12345678

becomes

12:34:56:78

I've been using .replace(), eg:
mystring = mystring.replace(/(.{2})/g, NOT SURE WHAT GOES HERE)

but none of the regex for : I've used work and I havent been able to find anything useful on Google.
Can anyone point me in the right direction?

A: If you're looking for approach other than RegEx, try this:
var str = '12345678';
var output = '';
for(var i = 0; i < str.length; i++) {
  output += str.charAt(i);
  if(i % 2 == 1 && i > 0) {
    output += ':';
  }
}
alert(output.substring(0, output.length - 1));

Working JSFiddle

A: A somewhat different approach without regex could be using Array.prototype.reduce:
Array.prototype.reduce.call('12345678', function(acc, item, index){
    return acc += index && index % 2 === 0 ? ':' + item : item;
}, ''); //12:34:56:78

A: Without the need to remove any trailing colons:
mystring = mystring.replace(/..\B/g, '$&:')

\B matches a zero-width non-word boundary; in other words, when it hits the end of the string, it won't match (as that is considered to be a word boundary) and therefore won't perform the replacement (hence no trailing colon, either).
$& contains the matched substring (so you don't need to use a capture group).

A: mystring = mystring.replace(/(..)/g, '$1:').slice(0,-1)

This is what comes to mind immediately. I just strip off the final character to get rid of the colon at the end.
If you want to use this for odd length strings as well, you just need to make the second character optional. Like so:
mystring = mystring.replace(/(..?)/g, '$1:').slice(0,-1)

A: mystring = mytring.replace(/(.{2})/g, '\:$1').slice(1)

try this

A: Easy, just match every group of up-to 2 characters and join the array with ':'
mystring.match(/.{1,2}/g).join(':')

var mystring = '12345678';

document.write(mystring.match(/.{1,2}/g).join(':'))

no string slicing / trimming required.

A: It's easier if you tweak what you're searching for to avoid an end-of-line colon(using negative lookahead regex)
mystring = mystring.replace(/(.{2})(?!$)/g, '\$1:');

A: mystring = mystring.replace(/(.{2})/g, '$1\:')

Give that a try

A: I like my approach the best :)
function colonizer(strIn){
  var rebuiltString = '';
  strIn.split('').forEach(function(ltr, i){
    (i % 2) ? rebuiltString += ltr + ':' : rebuiltString += ltr;
  });
  return rebuiltString;
}

alert(colonizer('Nicholas Abrams'));

Here is a demo
http://codepen.io/anon/pen/BjjNJj


text:
Q: How can get the type of nested generic type There is a third-party component library like this:
 public static class GenericExcuteTestClassExtension
 {
    public static void Excute<T>(this GenericExcuteTestClass clazz,
                             string parameter, Action<ReturnClass<T>> callback)
    {
        ReturnClass<T> rClazz = new ReturnClass<T>(parameter);
        rClazz.Property5 = typeof(T).ToString();
        callback.Invoke(rClazz);
    }

    public static void Excute<T>(this GenericExcuteTestClass clazz,
                               string parameter, Action<ReturnClass> callback)
    {
        ReturnClass rClazz = new ReturnClass(parameter);
        rClazz.Property5 = typeof(T).ToString();
        callback.Invoke(rClazz);
    }
}

I want to reflect to invoke the methodExcute<T>(this GenericExcuteTestClass clazz,  string parameter, Action<ReturnClass<T>> callback).

*

*I use thetypeof(GenericExcuteTestClassExtension).GetMethod("Excute", new Type[] { typeof(GenericExcuteTestClass), typeof(string), typeof(Action<ReturnClass<>>)}), but the compiler get the error "Type expected". How can I get type of (Action<ReturnClass<>>), Action<> can compliled, but it's not my expected.

*I want to pass the a custom action<ReturnClass<>> like (result)=>{....} to the method, how can I do it?
Please help ,thanks.
Why I use reflect to execute this ?
Because this method must execute in aop intercept
this real situation is like this:
I want to use restsharp in my app, and I write an interface like
 [RestfulService(Constants.BASE_URL + "/login")]
 public interface UserService
 {
    [Request("/login")]
    void Login([Paramter] string name, [Paramter] string password, Action<T> callBack);
 }

and Intercept the interface to get the parameter to execute restsharp ExecuteAsync<T>(this IRestClient client, IRestRequest request, Action<IRestResponse<T>> callback) to get data.
So I need to pass the T in UserService to ExecuteAsync<T> in Intercept method public void Intercept(IInvocation invocation) of castle.windsor, in this method body, we only can get GenericType's Type cannnot get T, so if I directly call ExecuteAsync, I cannot pass the GenericType T to this method. I must use like this:...GetMethod("...").MakeGenericType(new Type[]{piLast.ParameterType.GenericTypeArguments})

A: The whole problem comes from the fact, that nested generic types are not well handled by the reflection system in .NET.
The simplest solution in your case is to filter the methods yourself. A quick&dirty snippet:
MethodInfo method = null;

foreach (var m in typeof(GenericExcuteTestClassExtension)
                  .GetMethods(BindingFlags.Public | BindingFlags.Static))
{
    var parameters = m.GetParameters();

    if (!parameters.Any())
        continue;

    var lastParameterType = parameters.Last().ParameterType;
    var genericArgument = lastParameterType
        .GetGenericArguments()
        .SingleOrDefault();

    // you can/should add more checks, using the Name for example
    if (genericArgument != null && genericArgument.IsGenericType)
    {
        method = m;
        break;
    }
}

You should probably make an utility method from this. A general approach allowing to search for any method with nested generics can be found here. There is also another possibility using Expressions here.


text:
Q: Programmatic change macOS Mojave accent color I'm writing an app that allows user to set the accent color of the macOS Mojave.
My first attempt was using AppleScript. But I realized that the API is not up to date yet:

The underlined API works, but it only has 2 color options, while the new OS has 8.
I'm wondering if there is any workaround. Language is not limited, as long as it works. Thanks.

A: Here is a complete AppleScript solution which allows the user to choose light or dark mode, highlight colors, and accent colors. If the user chooses "Other" in the highlight color options, the script may throw an error because I did not define any actions for that option (figuring that part may be a good process for you to learn and figure out on your own)
property appearanceMode : {"Light", "Dark"}
property accentColors : {"Blue", "Purple", "Pink", "Red", "Orange", "Yellow", "Green", "Graphite"}
property highlightColors : {"Blue", "Purple", "Pink", "Red", "Orange", "Yellow", "Green", "Graphite", "Other"}

set chosenAppearanceMode to (choose from list appearanceMode ¬
    with title "Please Choose Your Accent Color" with prompt ¬
    "Please Choose Your Accent Color" OK button name ¬
    "OK" cancel button name "CANCEL") as string

set chosenAccentColor to (choose from list accentColors ¬
    with title ¬
    "Please Choose Your Accent Color" with prompt ¬
    "Please Choose Your Accent Color" OK button name ¬
    "OK" cancel button name "CANCEL") as string

set chosenHighlightColor to (choose from list highlightColors ¬
    with title ¬
    "Please Choose Your Highlight Color" with prompt ¬
    "Please Choose Your Highlight Color" OK button name ¬
    "OK" cancel button name "CANCEL") as string

tell application "System Preferences"
    reveal anchor "Main" of pane id "com.apple.preference.general"
end tell

tell application "System Events"
    repeat until exists of checkbox chosenAppearanceMode of window "General" of application process "System Preferences"
        delay 0.1
    end repeat
    -- Appearance
    click checkbox chosenAppearanceMode of window "General" of application process "System Preferences"
    -- Accent Color
    click checkbox chosenAccentColor of window "General" of application process "System Preferences"
    -- Dropdown Menu For Highlight Color
    click pop up button 1 of window "General" of application process "System Preferences"
    -- Highlight Color
    click menu item chosenHighlightColor of menu 1 of pop up button 1 of window "General" of application process "System Preferences"
end tell

tell application "System Preferences" to quit


text:
Q: Pegar valor específico de um arquivo Tenho o seguinte formato de arquivo:
username=teste1;
status=ONLINE;
username=teste2;
status=ONLINE;
username=teste3;
status=OFFLINE;

Onde uma das linhas representa o nome do usuário e a linha de baixo o status do usuário logo acima.
Gostaria de pesquisar por um username específico e mostrar o status dele, mas não consigo pensar em qual o problema por trás deste código.
Por enquanto tenho o seguinte código:
int isUserOnline(char *username) {

    FILE *f;

    f = fopen(FILE_NAME,"r");
    int i = 0;

    char line[MAX] = {'\0'};
    char destiny[MAX] = {'\0'};
    while(!feof(f)) {

        bzero(destiny, sizeof(destiny));

        fgets(line, sizeof(line), f);
        valueAfterEquals(destiny, line);

        if(strcmp(destiny, username)) {
            bzero(destiny, sizeof(destiny));
            fgets(line, sizeof(line), f);
            valueAfterEquals(destiny, line);
            printf("is: %s \n", destiny);
            if(strcmp(destiny, "OFFLINE")) {
                return 1;
            }
            else
                return 0;
        }
    }
}

Este acima deveria buscar o username e verificar se existe, se estiver offline, retorna um;
A função valueAfterEquals é está, simplesmente pega o valor depois do igual e concatena:
void valueAfterEquals(char * destiny, char * buffer){

    int k = 0;
    while(buffer[k] != '='){
        k++;
    }

    int i = 0;
    k++; //pular o '='
    while(buffer[k] != ';'){
        destiny[i] = buffer[k];
        k++;
        i++;
    }
}

A: A função strcmp() tem que ser igual a 0.
#include <iostream>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)

const char* FILE_NAME = "file1.txt";
const int MAX = 128;

void valueAfterEquals(char* destiny, char* buffer) {

    int k = 0;
    while (buffer[k] != '=') {
        k++;
    }

    int i = 0;
    k++; //pular o '='
    while (buffer[k] != ';') {
        destiny[i] = buffer[k];
        k++;
        i++;
    }
}

int isUserOnline(const char* username) {

    FILE* f;

    fopen_s(&f, FILE_NAME, "r");

    char line[MAX] = { '\0' };
    char destiny[MAX] = { '\0' };
    while (!feof(f)) {

        bzero(destiny, sizeof(destiny));

        fgets(line, sizeof(line), f);
        valueAfterEquals(destiny, line);
        if (strcmp(destiny, username) == 0) {
            printf("is: %s \n", destiny);
            bzero(destiny, sizeof(destiny));
            fgets(line, sizeof(line), f);
            valueAfterEquals(destiny, line);
            if (strcmp(destiny, "OFFLINE") == 0) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
}

int main()
{
    const char* username = "teste1";
    printf("%d\n", isUserOnline(username));
}


text:
Q: Higher covariant derivatives and the exterior derivative Let me start with the following tl;dr version of my question

What is a higher-order derivative, in general? How does it relate to the exterior
  derivative and to differential forms?

Suppose we have a bundle and a section $E \overset{\sigma}{\underset{\pi}{\leftrightarrows}} M$. Assume we have a connection on $E$. (One of the links assumes we   also have a connection on $\tau^*M$; assume that also, if you like.) It seems

*

*The $k$th order derivative should be a bundle map $\bigoplus_{i=0}^k \otimes^i \tau M \to E$ over M. Perhaps it always will satisfy some condition (such as symmetry) that will allow us to pass to a quotient of  $\bigoplus_{i=0}^k \otimes^i \tau M$.

*The covariant derivative should take us from $k$th order derivatives to $k+1$st order derivatives. It should be multilinear in the entries.

Regarding the last bullet, I could believe that the higher-order derivative might not always be found by an iterated derivative. Like in calculus where we have to recognize that a multidimensional integral isn't the same as an iterated integral, and under nice circumstances, they are equivalent.
One suggestion is that a higher covariant derivative of a section $\sigma: M \to E$ is the prolongation $E \to J^k E$ induced by $\sigma$.
This answer gives an outline of what I'm looking for, but it does so in quite a vague way. This answer seems to be addressing the issue head-on, but I haven't a clue what he's doing with his notation. See also this question about higher covariant derivatives.
This is maybe how an explanation could proceed:

*

*A higher-order covariant derivative $\nabla^k s$ of a section of a vector bundle $E \to M$ should be the prolongation $E \to J^k E$of the $k$th jet bundle $J^kE \to E$.

*Sections of $J^kE \to E$  are elements of $\Gamma \left( \left( \bigoplus\limits_{i=0}^k\operatorname{Sym}^i \tau^* M \right) \otimes E \right)$. So we can think of them like "polynomials of degree $\leq k$ where we plug in tangent vectors and get out elements of $E$." This maps nicely onto Taylor polynomials and $k$th order approximations of a function.

*The anti-symmetry of the exterior derivative (alternately, the anti-symmetry of the wedge product) kills all but the first-order derivatives. (Becoming a little vague. This is what the first link above says, but does not explain.)

(How can we make the last bullet rigorous? One relevant fact is that if $V$ is a vector space, and we view the symmetric and anti-symmetric tensors of order $k$ as subgroups of $\otimes ^kV$ (really they are quotients), then $\operatorname{Alt}^kV \cap \operatorname{Sym}^k V = 0$ except when $k=1$.)
We'd like to say something like

*

*The usual exterior derivative $d: \wedge^k \tau^*M \to \wedge^{k+1} \tau^*M$ or $d: \wedge^k \tau^*M \otimes E \to \wedge^{k+1} \tau^*M \otimes E$ somehow only captures one level at a time(?) of what the higher derivatives do?

*We also like anti-symmetry for modeling a "volume of a parallelipiped"-type function which is multilinear and vanishes when there are collinear entries (like the determinant). And we like the exterior derivative for being dual to the boundary in Stokes' theorem. Hence we extract this information in differential geometry.

This morning I've been boring through the "Natural Operations..." book by Kolar et al, but boy...it's encyclopedic, and has quite esoteric notation to boot. Kolar claims he's outlined what a higher-order derivative should be in generality, in an article called "On the Absolute Differentiation of
Geometric Object Fields" from 1973. As the title suggests, that article is pretty obscure, and some of the math therein is, also, at least to me.

A: I'm just going to focus on how totally anti-symmetrized higher covariant derivatives of $\sigma$ can be expressed in terms of $\sigma$ and $\nabla \sigma$ - no derivatives of $\sigma$ higher than first order. I think that's the main point you're looking for more detail about. (I won't comment on the jet bundles and stuff since I'm mostly unfamiliar with the formalism.)
We know that $\nabla^2 \sigma(X,Y)-\nabla^2 \sigma(Y,X) = \text{Riem}(X,Y) \sigma$. This is as seen in the other question from MathOverflow you've referred to a few times. It is also written in various other styles of notation, such as $d^\nabla(d^\nabla \sigma)(X,Y)$, or in an index-based notation as
$$
  \nabla_{[i} \nabla_{j]} \sigma^\alpha = \frac{1}{2} R^\alpha{}_{\beta i j} \sigma^\beta.
$$
(Square brackets on the lower indices denote anti-symmetrization: e.g. $A_{[ijk]} := \frac{1}{3!} \sum_{\pi} \text{sgn}(\pi) A_{\pi(i)\pi(j)\pi(k)}$, a sum over permutations of $i$, $j$, and $k$. Also, vertical bars can be used to exclude indices from the anti-symmetrization: e.g. $A_{[ij|k|l]} := \frac{1}{3!} \sum_{\pi} \text{sgn}(\pi) A_{\pi(i)\pi(j) k \pi(l)}$.)
The curvature formula takes care of the second covariant derivative - but what about even higher derivatives? At third order, we are looking at $d^\nabla(d^\nabla(d^\nabla \sigma))(X,Y,Z)$, or $\sum_{\pi} \text{sgn}(\pi) \nabla^3 \sigma(\pi(X),\pi(Y),\pi(Z))$, or $\nabla_{[i} \nabla_j \nabla_{k]} \sigma^\alpha$. We can compute it as follows:
$$
\begin{align}
  \nabla_{[i} (\nabla_j \nabla_{k]} \sigma^\alpha)
    &= \nabla_{[i} ( \frac{1}{2} R^\alpha{}_{|\beta| j k]} \sigma^\beta ) \\
    &= \frac{1}{2} (\nabla_{[i} R^\alpha{}_{|\beta| j k]}) \sigma^\beta
        + \frac{1}{2} R^\alpha{}_{\beta [j k} (\nabla_{i]} \sigma^\beta) \\
    &= \frac{1}{2} R^\alpha{}_{\beta [j k} \nabla_{i]} \sigma^\beta.
\end{align}
$$
(The vanishing of $\nabla_{[i} R^\alpha{}_{|\beta| j k]}$ is the Bianchi identity, although the fact that it vanishes will not really be essential to us.) Translated back to the other notation, this is
$$
  \nabla^3 \sigma(X,Y,Z) - \nabla^3 \sigma(X,Z,Y)
      + \nabla^3 \sigma(Y,Z,X) - \nabla^3 \sigma(Y,X,Z)
      + \nabla^3 \sigma(Z,X,Y) - \nabla^3 \sigma(Z,Y,X)
  = \text{Riem}(X,Y) \nabla \sigma (Z)
      + \text{Riem}(Y,Z) \nabla \sigma (X)
      + \text{Riem}(Z,X) \nabla \sigma (Y).
$$
At fourth order, we have:
$$
\begin{align}
  \nabla_{[i} (\nabla_j \nabla_k \nabla_{l]} \sigma^\alpha)
    &= \nabla_{[i} ( \frac{1}{2} R^\alpha{}_{|\beta| k l} \nabla_{j]} \sigma^\beta ) \\
    &= \frac{1}{2} (\nabla_{[i} R^\alpha{}_{|\beta| k l}) (\nabla_{j]} \sigma^\beta )
        + \frac{1}{2} R^\alpha{}_{\beta [k l} (\nabla_i \nabla_{j]} \sigma^\beta ) \\
    &= 0 + \frac{1}{4} R^\alpha{}_{\beta [k l} R^\beta{}_{|\gamma| i j]} \sigma^\gamma.
\end{align}
$$
(Aside: The reason I've been preferring index notation is because it makes these expression concise. These notes I found on the internet give the computations without index notation, which you might prefer, although they're very verbose.)
The point is, the expansion of $(d^\nabla)^m \sigma (X_1, ..., X_m)$ or $\nabla_{[i_1} \cdots \nabla_{i_m]} \sigma^\alpha$ contains only various combinations Riemann curvature tensor, $\sigma$, and $\nabla \sigma$. Any time it would have contained an expression that looks like "$\nabla \nabla \sigma$", we replace can it with "$\text{Riem} \, \sigma$" because we've anti-symmetrized over every "$\nabla \nabla$".
The only "miracle" occurs at second order ("$\nabla^2 \sigma(X,Y)-\nabla^2 \sigma(Y,X) = \text{Riem}(X,Y) \sigma$"). Everything else follows from that; there are no "new miracles" at higher orders. That sums up how higher covariant derivatives behave after total anti-symmetrization.


text:
Q: Cropped image is getting zoomed in iPhone? I have an application in which i am scaling my image of(360,480)to (320,480),then cropping the image.It is working fine.But when we got the image it is getting a little zoomed type image.projected up to front.Here is how i am doing it.`
[self imageWithImage:(UIImage *)image scaledToSize:CGSizeMake(160.0f,240.0f)];

and my defenition is -
-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self cropimage:newImage];
    return newImage;
}

and in cropimage i am doing like this -
-(void)cropimage:(UIImage *)image
{

   CGRect cropRect = CGRectMake(20,100,280,200);
     CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    UIImage* croppedImage = [UIImage imageWithCGImage:imageRef];
         CGImageRelease(imageRef);

    NSData *pictureData = [NSData dataWithData:UIImagePNGRepresentation(croppedImage)];
}

can anybody find out what is wrong in my approach?

A: Try passing image.scale for the scale instead of 0.0 to force it to use the passed in image scale.
-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, image.scale);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self cropimage:newImage];
    return newImage;
}


text:
Q: Accessing type="file" input from POST method on server side Having some difficulty understanding how to access type="file" input on the server side. Below is the code I'm using. I use AJAX because I want my web app to not require refreshing, and am using a slightly roundabout way of submitting my form so I can have a better UI.
My HTML:
<form id="updateProfileImageForm" enctype="multipart/form-data">

Upload new image

              <input type="file" id="imageToUpload" name="image" style="display: none;" onChange="$(this).closest('form').trigger('submit');"></input>

          </form>

My JS:
function changeImageToUpload() {
  $('#imageToUpload').trigger('click');
}

$('#updateProfileImageForm').submit(function(e) {
      e.preventDefault();
      var form_data = new FormData(this);

      $.ajax({
        type: 'POST',
        url: '/changeProfile',
        data: form_data,
        processData: false,
        success: function(response) {
          if(response.message != null) {
            alert(response.message);
          } else {
            // Change profile image displayed
            $('.updateProfileImage').attr("src", response.newProfileImage);
            alert('Profile picture successfully updated! Refresh your browser to update your window!');
          }
        }
      })
    });

My Server PHP:
if (isset($_FILES['image'])) {
      $image = $_FILES['image'];
  }

Var_dump on $_FILES shows an empty array, while var_dump on $_POST shows a lot of information (which I'm assuming is my data file). However, accessing the 'image' property on either $_POST or $_FILES (through either $_POST['image'] or $_FILES['image']) gives me either "undefined index" or "undefined variable".
Would you guys be so kind as to educate me on:

*

*What's the difference between $_POST and $_FILES?

*How should I be accessing the file in this case?
Thanks!

A: You're missing a necessary config option in your ajax request, you need to set contentType to false
  $.ajax({
    type: 'POST',
    url: '/changeProfile',
    data: form_data,
    processData: false,
    contentType: false,
    success: function(response) {
      if(response.message != null) {
        alert(response.message);
      } else {
        // Change profile image displayed
        $('.updateProfileImage').attr("src", response.newProfileImage);
        alert('Profile picture successfully updated! Refresh your browser to update your window!');
      }
    }
  })

jQuery.ajax sets the content type by default to application/x-www-form-urlencoded which is incorrect for your FormData object, if you set it to false it will be set correctly by the underlying XMLHTTTPRequest object.

A: Idea behind it.
Instead of using file as post to PHP, simply convert image to base64 and receive that string using ajax in php.
Refer to this URL


text:
Q: Asp.net mvc vs Angular JS for developing applications What I understand:
Asp.net MVC is used to develop applications that processes request at server. It also delivers view. But ultimately it renders the view at server and sends plain HTML to user.
On the other hand, angular JS does not do any processing at server. It only serves HTML or JavaScript files to client and then client executes those files. Angular Application only expects Data via services that run on server.
My Question:
If at all angular does not cause any server side processing load, why not to use it always to develop front end application, and on server why not to use any service (Such as web API or WCF) instead of MVC?
In short, why do we need to server side view processing framework at all, instead we can have service at server and angular application on client?

A: Both ASP.NET MVC and AngularJS has their own purposes and advantages.
As with your specific question, AngularJs is better for SPA (Single Page Applications), where as ASP.NET MVC is a full fledged server side Application which can contain WebAPIs, Routing engine as well as HTML emitting Views.
The reason why always a server side application like ASP.NET MVC is preferred first is that, it caters all basic needs, whereas AngularJs in many cases is cherry on top of the cake. It gives a smooth user experience for web applications. Also AngularJs is not very consistent as it depends on the user's browser which varies a lot and could lead to inconsistent results. So a server side application is always the best fallback to make sure the user's basic purpose is fullfilled.


text:
Q: What is the difference between role=dialog and role=alertdialog? According to the WAI-ARIA specification both roles should have:

*

*Focus on first focusable element

*User should not be able to leave dialog

*Should have proper aria-label set

*Should be used to interrupt flow and should require to take some action e.g. to click a button or to type something

The only difference I see is that alertdialog should have aria-describedby set.
This leads me to a question. Whats the practical difference between role=dialog and role=alertdialog? When shall we use one or another?

A: As described here, alertdialog is a subtype of dialog.
What differentiate them is their role. As the name implies, alertdialogs should be used when the context requires the user's immediate attention (i.e in case of alerts, warnings or errors).
edit: corrected the explanation thanks to @cjl750 comment.


text:
Q: Worksheet function trouble I have a version of this that works but this version dosen't
Public Const GlobalSheetName As String = "Sammanställning,Pris_Schrack,Pris_Pelco,Pris_Swansson,Pris_Övrig"

Sub Tabortblad()
 Dim ws As Worksheet
 Dim ShName As String
 Dim SnNumm As Long
 char = Split(GlobalSheetName, ",")
 SnNumm = UBound(char) - LBound(char) + 1
    If Worksheets.Count = SnNumm Then    'bör ändra denna till större antal
       MsgBox "Där finns bara " & SnNumm & " blad"
    Else
       strCancel = MsgBox("Är du säker på att du vill radera bladen", vbOKCancel, "Radera Blad")
           If strCancel = "1" Then
              Application.ScreenUpdating = False
               Application.DisplayAlerts = False
                For Each ws In ActiveWorkbook.Worksheets
                   For Each char In Split(GlobalSheetName, ",")
                        If Not ws.Name = char Then
                           ws.Activate
                           Worksheets(ws.Name).Delete
                        End If
                   Next
                Next
                 Sheets("Sammanställning").Range("B:B").Value = ""
                 Sheets("Sammanställning").Range("P68:R" & Sheets("Sammanställning").Cells(Rows.Count, "R").End(xlUp).Row + 1).Value = ""
                 Application.DisplayAlerts = True
            End If
       Application.ScreenUpdating = True
       Worksheets("Sammanställning").Activate
       Range("A1").Select
     End If
End Sub

Now this is the version that works
Sub Tabortblad()
 Dim ws As Worksheet
 Dim ShName As String
 If Worksheets.Count = "5" Then    'bör ändra denna till större antal
    MsgBox "Där finns bara 5 blad"
 Else
    strCancel = MsgBox("Är du säker på att du vill radera bladen", vbOKCancel, "Radera Blad")
    If strCancel = "1" Then
       Application.ScreenUpdating = False
        Application.DisplayAlerts = False
         For Each ws In ActiveWorkbook.Worksheets
          If Not ws.Name = "Sammanställning" Then
          If Not ws.Name = "Pris_Schrack" Then
          If Not ws.Name = "Pris_Pelco" Then
          If Not ws.Name = "Pris_Swansson" Then
          If Not ws.Name = "Pris_Övrig" Then
            ws.Activate
               Worksheets(ws.Name).Delete
          End If
          End If
          End If
          End If
          End If
         Next
          Sheets("Sammanställning").Range("B:B").Value = ""
          Sheets("Sammanställning").Range("P68:R" & Sheets("Sammanställning").Cells(Rows.Count, "R").End(xlUp).Row + 1).Value = ""
         Application.DisplayAlerts = True
     End If
   Application.ScreenUpdating = True
   Worksheets("Sammanställning").Activate
   Range("A1").Select
  End If
End Sub

The problem is ws.Name it returns a fault in the first version and in the second it works fine.
I use this to delete the proper worksheets that I added in another sub.
I'm using the constant to collect the sheet names so if I have to add one it's easier.

A: I confirmed that the first subroutine worked and then confirmed that I was unable to get the second, "not working" subroutine to work.  Then, I was able to get the second subroutine to run completely through by adding the following:
option Explicit
Dim strCancel As String, char As Variant

First, you should always include "option explicit" at the top of your modules since it forces you to properly define your variables. This was the source of the problem since the char variable was not defined and some of the lines of your code expected an array, so it failed at that point. At least, that's what happened for me before I changed char to a Variant. You may not want to use a variant for char, and I suggest research into the lines of your code using this variable.
I can't help further because I'm not entirely clear what the goal of your code is and I don't understand the non-English words used. Let me know if you have more questions.

A: Run through the worksheets as their count backwards.
dim w as long
For w=ActiveWorkbook.Worksheets.count to 1 step-1
  If iserror(application.match(Worksheets(w).Name, array("Sammanställning", "Pris_Schrack", "Pris_Pelco", "Pris_Swansson", "Pris_Övrig"), 0)) Then
       Worksheets(w).Delete
  End If
Next w

Be careful the the VBE does not mess up letters like ä or Ö by converting them to ?. The VBE doesn't handle unicode.

A: you could consider deleting in one shot:
Dim ws As Worksheet
Dim names As String
For Each ws In ActiveWorkbook.Worksheets
    If InStr(GlobalSheetName, ws.Name) = 0 Then names = names & ws.Name & "|"
Next
If names <> "" Then Worksheets(Split(Left(names, Len(names) - 1), "|")).Delete


text:
Q: Django REST: AttributeError: 'WSGIRequest' object has no attribute 'session' I've created a Login APIView for my Django app. I'm continually getting the error,  AttributeError: 'WSGIRequest' object has no attribute 'session'. I've looked at other posts and people mention reordering the middleware placing sessionMIddleware first which doesn't work. Here is the setup of the API. The error is occurring at login(request, user).
from django.contrib.auth import authenticate, login
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import LoginSerializer
from rest_framework.permissions import AllowAny

class Login(APIView):
    permission_classes = (AllowAny, )
    authentication_classes = ()
    serializer = LoginSerializer

    def post(self, request, format=None):
    login_form = self.serializer(data=request.data)
    data = dict()
    if login_form.is_valid():
        username = login_form.data['username']
        password = login_form.data['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            print(request.data)
            login(request, user)
            data['data'] = 'OK'
            return Response(data=data, status=200)
        else:
            data['error'] = 'Invalid login information provided'
            return Response(data=data, status=401)
    else:
        data['invalid'] = 'Bad Request, form is invalid'
        return Response(data=data, status=400)

A: Ok, I had my middleware defined as MIDDLEWARE in my settings.py instead of MIDDLEWARE_CLASSES. Pycharm generated it for me like that when I setup the new project. I believe Django 1.10 uses MIDDLEWARE and I'm using 1.9.


text:
Q: Create another file but don't split worksheets into separate files Separate worksheets into separate files
Hi I am using code
Sub Split_Sheet_into_ExcelFiles()
    Dim FilePath As String
    FilePath = Application.ActiveWorkbook.Path
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each Sheet In ThisWorkbook.Sheets
    Sheet.Copy
    Application.ActiveWorkbook.SaveAs Filename:=FilePath & "\" & Sheet.Name & ".xlsx"
    Application.ActiveWorkbook.Close False
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

It creates the same file but I was trying to split multiple worksheets into individual files. ANy idea what I'm typing wrong? Thanks

A: Export Each Sheet to an Individual File
Option Explicit

Sub ExportSheets()

    Const PROC_TITLE As String = "Export Sheets"

    Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code

    Dim dFilePath As String: dFilePath = swb.Path

    If Len(dFilePath) = 0 Then
        MsgBox "The path cannot be determined." & vbLf & "Please save the " _
            & "workbook before using this procedure.", vbCritical, PROC_TITLE
        Exit Sub
    End If

    Application.ScreenUpdating = False

    Dim dwb As Workbook, ssh As Object, sshCount As Long

    For Each ssh In swb.Sheets
        If ssh.Visible = xlSheetVisible Then ' sheet is visible
            ssh.Copy
            Set dwb = Workbooks(Workbooks.Count)
            Application.DisplayAlerts = False ' overwrite without confirmation
                dwb.SaveAs Filename:=dFilePath & "\" & ssh.Name
            Application.DisplayAlerts = False
            dwb.Close SaveChanges:=False
            sshCount = sshCount + 1
        'Else ' sheet is not visible; do nothing!?
        End If
    Next ssh

    Application.ScreenUpdating = True

    MsgBox sshCount & " sheet" & IIf(sshCount = 1, "", "s") _
        & " exported.", vbInformation, PROC_TITLE

End Sub


text:
Q: How can I make the value of a field default to something when a class is constructed? I have the following class:
 public abstract class AuditableTable : TableServiceEntity, IAuditableTable
    {

    protected AuditableTable()
        : base()
    {
        Status = "3";
    }

    protected AuditableTable(string pk, string rk)
        : base(pk, rk)
    {
    }
    public string Status { get; set; }

Is there a simple way that I can make the value of Status always default to "3" when a new instance is created? What is the way that most people use?
Update
I added a setter but then it will not set if the other constructor is called.

A: You can do it in the constructor. That's the use of them.
public abstract class AuditableTable : TableServiceEntity, IAuditableTable
{

    protected AuditableTable()
        : base()
    {
        InitFields();
    }

    protected AuditableTable(string pk, string rk)
        : base(pk, rk)
    {
        InitFields();
    }
    private InitFields()
    {
        Status = "3";
    }
    public string Status { get; set; }
}

UPDATE:
As you have updated the question, you can also look at this answer to rearrange your constructors.

A: protected AuditableTable() { // no need to use : base(), it is called implicitly
    Status = 3;
}

A: Do not use auto-implemented property. Declare a private field with initial value.
private int _status=3;

public int Status
{
  get { return _status;}
  set {_status=value;}
}

EDIT: Assign property value in constructor is good practice but if that class has more than one constructors than I think it will be good to initialize member at declaration.

A: This is typically done by chaining constructors. You have every constructor call "up" through a common constructor. For example:
public class MyThing : MyBaseThing
{
    public MyThing()
        : this(null, null)
    {
    }

    public MyThing(string pk, string rk)
        : base(pk, rk)
    {
        Status = "3";
    }

    public string Status { get; set; }
}

That works well if you can chain constructors. But sometimes you'll have constructors that can't be chained. If that's the case, then you make sure that each of your "leaf" constructors calls a private Init() method of some kind, that does common initialization. That's kind of a pain in the neck at times, when you have a readonly field, because readonly fields can only be modified in the constructor--not in a method that's called by a constructor.
A deleted answer proposed using a property with an explicit backing field, rather than using an auto-implemented property. That's a perfectly valid and quite reasonable thing to do, negative comments notwithstanding. Sure, it's not as pretty as an auto-implemented property, but it's very effective. It's what we did before we had auto-implemented properties, and there's no reason not to do it if you really need a default value for a property. In case you can't see the deleted answer:
public class MyThing : MyBaseThing
{
    private string _status = "3";
    public string Status
    {
        get { return _status; }
        set { _status = value; }
    }

    // constructors go here.
}


text:
Q: Mapping between Android permissions (that we define in the manisfest file ) to corresponding API calls /methods Where can I find the mapping between Android permissions (that we define in the manisfest file ) to corresponding API calls /methods?
For example
GET-ACCOUNTS" is a permission type which maps to
getAccountsByType(), getDeviceId(), and getLine1Number().

Similarly I want to know, If I use permission Internet,ACCESS_COARSE_LOCATION,ACCESS_WIFI_STATE etc.. Then which all methods/API calls
map to it?
Please let me know where can I find this information. Below link lists the permission
http://developer.android.com/reference/android/Manifest.permission.html
But could not find the mapping.
If this is not the right forum to post this , Then please let me know where should I post this?

A: The mapping is not provided by Google, but two three major research studies have been attempted to recover this information.
The first study was done by Berkeley using a dynamic analysis technique to mine the mapping from Android 2.2. They created an online tool where you can submit your app for some analysis (now offline).
The second study was done by the University of Toronto.  They used a static analysis approach to mine the mappings from a few representative versions of Android (2.2.3, 2.3.6, 3.2.2, 4.0.1, and 4.1.1). Note that it appears that PScout is now being actively maintained again by the authors and there are current mappings available.
Both of these tools have some caveats as discussed by the papers and as a result the mappings produced are not perfect, but it is better than nothing.

Update: PScout is no longer being actively maintained. A group in Germany at Saarland University was able make some improvements on PScout and produce published mapping results for Android APIs 16, 17, 18, 19, 21, 22, and 23. The tool source does not appear to be available.

Link: Berkeley Paper (Android Permissions Demystified)
Link: Berkeley Stowaway Tool (tool appears to be permanently offline now, and the authors now recommend using PScout results for analysis)
Link: Toronto Paper (PScout: Analyzing the Android Permission Specification)
Link: Toronto PScout Tool
Link: PScout II on Github
Link: Saarland University Paper (axplorer: On Demystifying the Android Application Framework: Re-Visiting Android Permission Specification Analysis)
Link: axplorer Permission Mapping Results

Update: Shameless self-promotion of my Android Essentials Toolbox open source Eclipse plugin that can be used to apply the permission mappings in the Atlas visual program analysis framework. Permission mappings are based on PScout and axplorer results and can be applied to Android source or binary projects. A UI is included for browsing the permission mappings (used permissions are highlighted red).

A: Original PScout website doesn't work anymore but I extracted the mapping from original PScout and pushed it to Github. You can easily check it out and parse it if you need it.
Here you can find all methods that PScout found which require Android permissions.
PScout results- map of Android permissions and methods that require those permissions

A: The last (2016) "state of the art" paper about permission mapping is Axplorer
In their github project you can find the extracted mapping (api 25).


text:
Q: Not able to persist array of objects in mongo using mongoose I'm trying to persist an array of objects in a document using mongoose. I have tried multiple times but it's not persisting array in document. It places an empty array in document.
Following is my Schema:
var ProfileSchema = new Schema({

  name: String,
  PagesData: [{
    pageAccessToken: {type: String, get: decryptText, set: encryptText},
    category: String,
    name: String,
    id: String,
    perms: [String]
  }]

});

module.exports = mongoose.model('Profile', ProfileSchema);

I'm trying to save a document with an array of objects using following query:
var newProfile = new Profile();
newProfile.name = "someName";
newProfile.PagesData = [ { pageAccessToken: 'someToken',
    category: 'Bags/Luggage',
    name: 'someBrandName',
    id: '12345',
    perms:
     [ 'ADMINISTER',
       'EDIT_PROFILE',
       'CREATE_CONTENT' ] } ];

newProfile.save(function(err, result, numAffected){
    if(err) {
        console.log(err);
        res.send(500, "Error");
    }
    console.log(result);
    res.send(200, "Success");
});

I tried debugging the mongo commands using

require('mongoose').set('debug', true)

On Debug logs it shows, empty array during insert command execution.
Can anyone please tell me how can I store this array of object in my schema ?
Thanks,
Update:
It's been too long and I'm still not able to figure out the root cause of the problem. There is a long thread going on github for this.
https://github.com/Automattic/mongoose/issues/3249
I would like other experts to please take a look and suggest me some way by which I can solve the issue. I'm really stuck at this.
Update 2:
None of the solution worked for me so far, so I decided to modify the schema only to meet my requirements. This resulted in a different problem:
I want to create a map with a objectId as key and an array of string values as its value. The closest that I can get is:
var schema = new Schema({
   map: [{myId: {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'}, values: [String]}]
});

But somehow this is not working for me. When I perform an update with {upsert: true}, it is not correctly populating the key: value in the map. In fact, I'm not even sure if I have declared the schema correctly.
Can anyone tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema?
Also, if above is not correct and can;t be achieved then how can I model my requirement by some other way. My use case is I want to keep a list of values for a given objectId. I don't want any duplicates entries with same key, that's why picked map.
Please suggest if the approach is correct or should this be modelled some other way?
Thanks

A: I tried the exact code you have provided here and it's working for me. I am not sure what is causing the issue for you. Until and unless we get the same issue, it's very difficult to rectify it.
Here are few suggestions which you might try:

*

*Create a simple schema and try storing the object, that way you can
figure it out if it has to do something with the schema.

*You can try out your schema in a sample app to find if some
dependency is causing the problem.

Once you know where exactly the problem is, you would be able to figure out a solution too. I hope it helps.

A: I tested this and the insert works for me using the below:
(I had to remove the get: decryptText, set: encryptText)
var n = { name: "Testing for mongoose", PagesData : [{ pageAccessToken: 'someToken',
    category: 'Bags/Luggage',
    name: 'someBrandName',
    id: '12345',
    perms:
     [ 'ADMINISTER',
       'EDIT_PROFILE',
       'CREATE_CONTENT' ] } ] }

Profile.create(n, function (err) {
            if (!err) {

                return 'records saved successfully';
            }
            else {

                return error on save:' + err;
            }
        });

A: To create multiple pageDatas you can use it as an embedded collection instead of using arrays.
The Schema will be as follows:
var PagesDataSchema = new Scheme({

    pageAccessToken: {type: String, get: decryptText, set: encryptText},
    category: String,
    name: String,
    id: String,
    perms: [String]
})
var ProfileSchema = new Schema({

  name: String,
  PagesData: [PagesDataSchema]

});

module.exports = mongoose.model('Profile', ProfileSchema);

Reference: http://mongoosejs.com/docs/subdocs.html
For Saving the document you can use like.
exports.save = function(req,res){
var test = new ProfileSchema;  // new object for ProfileSchema domain.
test.name= req.body.name;
if(req.body.PagesData){
 req.body.PagesData.forEach(function(page){  // For every element of pageData from   client.
    test.PagesData.push(page)  // This pushes each and every pagedata given from the client into PagesData.
})
}
test.save(function (saveErr, saved) {  // Saves the new document into db.
if (saveErr) {
    console.log(saveErr)
    return;
}
res.status(HttpStatus.OK).json(saved);
});
};

Hope this helps.

A: Have you tried
Profile.create({
  name: "someName",
  PagesData: [
    {
      pageAccessToken: 'someToken',
      category: 'Bags/Luggage',
      name: 'someBrandName',
      id: '12345',
      perms: [
        'ADMINISTER',
        'EDIT_PROFILE',
        'CREATE_CONTENT'
      ]
    }
  ]
}, function(err, profile) {
    // do your stuff
})

?