text:
Q: Fastest HTML Downloader I want the fastest method to download the source of HTML with given URL address
Is there any solution beyond normal C# solutions like (WebClient Download or HttpWebRequest, HttpWebResponse)
that speed up fetching HTML source code ??

A: I normally just use this function when downloading and viewing html.
string getHtml(string url)
        {
            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            myWebRequest.Method = "GET";
            // make request for web page
            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
            string myPageSource = string.Empty;
            myPageSource = myWebSource.ReadToEnd();
            myWebResponse.Close();
            return myPageSource;
        }

http://www.devasp.net/net/articles/display/994.html


text:
Q: QApplication: invalid style override 'adwaita' passed, ignoring it When I run my Python file I get the following error:
class Window(QMainWindow):
   def __init__(self):
       super().__init__()

       # GUI Styling
       self.setWindowTitle('My Application')
       self.setFixedHeight(350)
       self.setFixedWidth(700)
       self.setStyleSheet('background-color: #FFFFFF')

       # Show Widgets
       self.show()

   # Run Application
   App = QApplication([])
   App.setStyle('Fusion')
   Config = Config()
   Config.LoadJson()
   sys.exit(App.exec())

I get the following error:
QApplication: invalid style override 'adwaita' passed, ignoring it.
        Available styles: Windows, Fusion

Does anyone know how I can fix this? I am using Zorin 16.1 Pro, Python 3.8.10 & Pip 20.0.2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unit Test case to cover router.navigate.then in jasmine angular mockRouter does not cover inside then,
let mockRouter = { navigate: jasmine.createSpy('navigate') };
Need a solution for coverage of below code
this.router.navigate(['path/to']) .then(() => { window.location.reload(); });


text:
Q: ruby on rails usage of debugger and ytml I'm new to ruby on rails.
Can anyone suggest a debugging method for ruby on rails.
(Like var_dump, print_r in php).
I saw debugger and ytml. could anyone explain how to use them?

A: Add in your Gemfile
gem 'debugger'

then bundle install.
Then use like this in methods
def index
  debugger
  @files = Example.order('created_at DESC')
end

And in views(.erb) use like this.
<%debugger%>

This will cause debugger to break code execution and give you an interactive console on the line "debugger". You can type "step" to dive into the line of code or type "next" to stay at the same level and process the line you're on.
Typing "continue or c" will resume code execution until the next "debugger" line is encountered, if any

A: I would suggest you look into pry, a debugging REPL you can use inside of rails. For other cases, there's the rails console command, which will allow you to open up a REPL in the context of your running application in development mode, and should be sufficient for most development needs.


text:
Q: How to convert RGB Pixel Buffer to IRandomAccessStream^ I have structure like this:
struct PixelBuffer
{
    unsigned int width,height,stride;
    PixelFormat format;
    unsigned char * buffer;
}

I want to convert it to IRandomAccessStream^ how do I do that? (bytes that buffer is pointing to)
I am not sure if PixelFormat makes difference and if there is favourable one, but let's say it is RGB format.
Thanks!
Note
I need SoftwareBitmap^ So my idea is to get IRandomAccessStream^ and then get BitmapDecoder^ from which I would get SoftwareBitmap^ if there is some shortcut that I am not aware of that would be great!

A: There is no need to go through Stream if SoftwareBitmap^ is what you need, you can get it directly from buffer like this
vector<unsigned char> bufferBGRA; // Convert your bytes to BGRA
DataWriter ^writer = ref new DataWriter();
writer->WriteBytes(Platform::ArrayReference<BYTE>(
            bufferBGRA.data(),
            width * height * 4)); // 4 channels (BGRA)
IBuffer ^buff= writer->DetachBuffer();

// Create SoftwareBitmap from buff
SoftwareBitmap^ softwareBitmap = ref new SoftwareBitmap(BitmapPixelFormat::Bgra8, width, height);
softwareBitmap->CopyFromBuffer(buff);

And yeah in this case BGRA is the favorable format, since you will need to convert your buffer to the format that BitmapPixelFormat supports like BGRA


text:
Q: ASP.NET MVC - Directory-like URL I'm learning MVC and faced this challenge which I can't figure out how. When I was at beginning I'm happy with such URL:
http://www.domain.com/stories/1

where 1 is the ID of one story in the database.
Then I decided to put chapters for each story, to read each chapter I used such URL:
http://www.domain.com/chapters/1

where 1 is the ID of chapter in the database.
Now, I want readers to see what is the ID of the story they are reading, here's my ideal URL:
http://www.domain.com/stories/1/chapters/2

But how can I achieve this?
Thanks in advance.

A: What you are looking for is MapRoute.

A: You can achieve it using two different methods.
Method 1. (tested)
If you want in the stories cotroller, you have to creating a route map like this
   routes.MapRoute(
            "story-with-chapter", // Route name
            "stories/{storyid}/chapters/{chapterId}", // URL with parameters
            new { controller = "stories", action = "chapters"} // Parameter defaults
        );

and your action should look like this
public ActionResult Chapters(int storyid,int chapterId)
{

     return View();
}


text:
Q: Loading dlls from a different directory using "probing" When compiling a C# project which has external references, the referenced dlls are being copied to the project's output path (next to the exe).
When running the application, it expects to find the dlls next to the exe.
I'm looking for a way to spread my dll files into different directories Dlls for starters). And have the exe look for the dll files in those directories.
Example:
Let's say we have an application called "App" located under C:\App\App.exe, and also it uses a dll file called "App.dll" which is currently also located under C:\App.
I wish to create a new directory called C:\App\Dlls and move the App.dll file to there, while making sure that the App.exe file will know to look for the dll in the new location.
I've searched the internet and found the probing solution. Here's my code (edited "App.config" file):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas=microsoft-com:asm.v1">
      <probing privatePath="Dlls" />
    </assemblyBinding>
  </runtime>
</configuration>

I compiled my application, created the Dlls directory and moved all the dll files to that directory, but the application crashes.
What am I missing?

A: Found the solution, the file App.exe.config was missing from my base directory. That's why it didn't work. Now everything works smoothly.


text:
Q: Most suitable approach for repeated tasks in Android background thread I'm writing an android application to mock GPS location. Its purpose is to help in testing and once it starts mocking it will be sent to the background. I need to execute a location update every n seconds and that needs to continue when the application is not visible.
I'm really confused by the different options of executing code outside the UI thread, the various recommendations about when each is most appropriate, which can / cannot be cancelled, and which can / cannot communicate data to the UI thread.
Can someone please tell me which approach will enable me to execute code periodically when my application is in the background and also satisfy the following requirements? I've tried to keep this general so that the question is not too specific to my problem.

*

*can access data from the UI thread

*can update data within the UI thread

*can be cancelled

*can itself schedule future work, e.g. when executing location update 1, schedule location update 2. when executing location update 2, schedule location update 3


text:
Q: Eclipse - C++ hello world project's error I am using a 64-bit Winodws 7. I've downloaded a CDT Eclipse and have downloaded MinGW. After that, I created a c++ hello world project.
This is the code:
#include <iostream>
using namespace std;

int main() {
    cout << "!!!Hello World!!!" << endl; // This is supposed to print "Hello World!!!"
    return 0;
}

But when I want to run it, this error pops up:
"Launch failed. Binary not found."
Any help would be highly welcomed.

A: You have to "Build" your project before you can "Run" it.
When using Eclipse for Java, you simply click the "Run" icon, then Eclipse will automaticly compile your program and then run it.
With C++ however, this is for whatever reason not the case. Instead of just clicking the "Run" icon, you need to click the "Build" icon first. This is where Eclipse will create a makefile and compile your program. Then you can run it by clicking the "Run" icon.
I hope this solves your problem.

A: Has eclipse built the EXE file correctly for you? Look for helloworld.exe or whatever, and try running it from a Windows Command prompt.
If not, then you've got a problem with your build. Build it again and check for errors.
If the EXE file is there, but cannot be run from within Eclipse then check that the PE Windows Binary Parser is enabled for your project.
UPDATE:  To fix "Unresolved Inclusion" errors, see here. In particular, try this:

*

*Right-click on the probject and select "Properties"

*Go to "C/C++ General" -> "Paths and Symbols" and select "Includes" tab

*Select "GNU C++"

*Press on "Add..."

*Look for the folder "C:\dev\eclipse\mingw\lib\gcc\mingw32\4.4.1-dw2\include\c++"
  or similar

UPDATE See also this link:
http://wiki.eclipse.org/CDT/User/FAQ#I_am_using_a_non_gnu_compiler_and_I_get_the_following_messages:_.22Error_launching_external_scanner_info_generator_.28gcc_-E_-P_-v_-dD.22_and_.22File_not_indexed_because_it_was_not_built_.22._How_do_I_get_rid_of_them.3F

A: The problem is because you Windows is 64 bit and Eclipse just sort of chooses to ignore executables in this format without reporting any error. Pretty convenient, huh? Try this to fix it:
Right-click your project -> Properties -> expand "MinGW C++ Liker" in the right side pane and select the Miscellaneous option
Under "Other options" you will add a new option:
-arch=i386

Rebuild your application, refresh, and you should see a Binaries folder that contains your executable. You can run it by going to Run As -> Local C/C++ Application

A: First check the toolchain selected,while creating the new c++ project.It should be MinGW as you have stated,(hope you have made the entries in the environmental variables).Write the code .press ctrl+b to build the workspace. Rt click the project and select clean project.press f5 to refresh.then ctrl+f11 to run your prg.Hope this helps..

A: Make sure you select the correct Toolchain when you create the project.

A: This happens due to windows execution permission (I assume that you're running eclipse from an external drive or from another partition), if you run eclipse as an administrator you will be able to debug your application without problems..


text:
Q: GraphQL - Syntax error: expected ":", found ")" I am working on a project using GraphQL with some basic queries and mutations.  I have set up the typeDefs and resolvers in the same format as I have in the past, and mostly expect the same result.  However, when I try to start my server, I get the below error.  So far I have cut queries and mutations out of my typeDefs one at a time, as well as commented out resolvers one at a time with no effect.  I've perused the error locations, but haven't been able to really find any information that would point me to the area or even file that this syntax error exists.  Any help would be super helpful!

$ npm start

> crm-tools@1.0.0 start E:\Coding_Bootcamp\projects\CRM-Tools\server
> node server.js

E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:1413
    throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));
    ^

GraphQLError [Object]: Syntax Error: Expected ":", found ")".
    at syntaxError (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\error\syntaxError.js:15:10)
    at Parser.expectToken (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:1413:40)
    at Parser.parseInputValueDef (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:912:10)
    at Parser.optionalMany (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:1503:28)
    at Parser.parseArgumentDefs (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:900:17)
    at Parser.parseFieldDefinition (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:880:21)
    at Parser.optionalMany (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:1503:28)
    at Parser.parseFieldsDefinition (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:868:17)
    at Parser.parseObjectTypeDefinition (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:812:23)
    at Parser.parseTypeSystemDefinition (E:\Coding_Bootcamp\projects\CRM-Tools\server\node_modules\graphql\language\parser.js:708:23) {
  locations: [ { line: 53, column: 25 } ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! crm-tools@1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the crm-tools@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shawn\AppData\Roaming\npm-cache\_logs\2021-07-02T03_23_00_391Z-debug.log

/typedefs.js

const { gql } = require('apollo-server-express');

// create our typeDefs
// TODO timecard formatting?
const typeDefs = gql`
type Employee {
  _id: ID
  firstName: String
    lastName: String
    street: String
    city: String
    state: String
    zipcode: Int
    email: String
    phone: String
    timeCards: [Int]
}

type Client {
    _id: ID
    firstName: String
    lastName: String
    street: String
    city: String
    state: String
    zipcode: Int
    email: String
    phone: String
    workOrders: [WorkOrder]
  }

  type WorkOrder {
    _id: ID
    date: String
    description: String
    notes: [String]
    parts: [String]
    invoice: String
    timeClocks: [Int]
  }

  type Warehouse {
    parts: [String]
    laborItems: [String]
  }

  type Query {
    me: Employee
    employees(_id: ID): [Employee]
    employee(_id: ID!): Employee
    clients: [Client]
    client(_id: ID!): Client
  }

  type Mutation {
    addEmployee(Employee): Employee
  }
`;

// export the typeDefs
module.exports = typeDefs;

resolvers.js

const { Client, Employee } = require('../models');

const resolvers = {
    Query: {
        // get all clients
        clients: async () => {
            return Client.find()
            .populate("workOrders");
        },

            // get single client
        client: async (parent, { _id }) => {
            return Client.findOne({ _id })
            //.populate("workOrders");
        },

        // get all employees
        employees: async () => {
            return Employee.find()
            .populate("timeCards");
        },

        // get single employee
        employee: async(parent, { _id }) => {
            return Employee.findOne({ _id })
            .populate("timeCards");
        }
    },

    Mutation: {
        addEmployee: async (parent, args) => {
            const employee = await Employee.create(args);
        }
    }
};

module.exports = resolvers;

A: The definition for the mutation is incorrect, it needs a variable before the type:
type Mutation {
  addEmployee(employee: Employee): Employee
}

You can validate the syntax of your graphql via a graphiql plugin, or this publicly available one.


text:
Q: Add shadowPath to UITableView subclass I want to create a shadow on a subview on my UITableView:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    mainBackground = UIView()
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    backgroundColor = .clear

    mainBackground.backgroundColor = .red
    mainBackground.translatesAutoresizingMaskIntoConstraints = false
    mainBackground.layer.cornerRadius = 15
    mainBackground.layer.masksToBounds = true

    contentView.addSubview(mainBackground)

    setupConstraints()
}

func setupConstraints() {
    NSLayoutConstraint.activate([
        mainBackground.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5),
        mainBackground.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5),
        mainBackground.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        mainBackground.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.5)
    ])
}

I'm placing my shadow code in layoutSubviews, where I also use UIEdgeInsets to make my subview smaller:
override func layoutSubviews() {
    super.layoutSubviews()
    let margins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
    contentView.frame = contentView.frame.inset(by: margins)
    contentView.layer.cornerRadius = 8
    setupShadow()
}

public func setupShadow() {
    self.layer.shadowOffset = CGSize(width: 0, height: 3)
    self.layer.shadowRadius = 3
    self.layer.shadowOpacity = 1.0
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowPath = UIBezierPath(rect: self.mainBackground.frame).cgPath
    self.clipsToBounds = true
}

Without the shadowPath this seems to work, but with it I don't get a shadow at all. I want to use a shadowPath to make the drawing of the shadow efficient. How do I add the shadowPath here?

A: I'm sorry I don't quite understand what kind of result do you expect to achieve.
I don't think it's possible to get any kind of "shadow" for a UITableViewCell because usually shadows are outside/around the view, but table view cells stay next to each other, without any gap in between. So any shadow of the first cell will be overlapped by the second cell.
self.layer.shadowPath = UIBezierPath(rect: self.mainBackground.frame).cgPath

here you add a shadow to the cell, but the shadow is overlapped by mainBackgroundView so the shadow is invisible
try that:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    mainBackground.backgroundColor = .red
    mainBackground.translatesAutoresizingMaskIntoConstraints = false
    mainBackground.layer.cornerRadius = 15

    mainBackground.layer.shadowOffset = CGSize(width: 0, height: 3)
    mainBackground.layer.shadowRadius = 3
    mainBackground.layer.shadowOpacity = 1.0
    mainBackground.layer.shadowColor = UIColor.black.cgColor

    contentView.addSubview(mainBackground)
}

override func layoutSubviews() {
    super.layoutSubviews()

    mainBackground.frame = contentView.bounds.insetBy(dx: 20, dy: 20)
    mainBackground.layer.shadowPath = UIBezierPath(rect: self.mainBackground.bounds).cgPath
}

and increase the height of your cells to ~100pt
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    100
}

and you will be able to play with a shadow applied to mainBackgroundView

A: Try this,
  var setupShadowDone: Bool = false

    public func setupShadow() {
        if setupShadowDone { return }
        print("Setup shadow!")
        self.layer.cornerRadius = 8
        self.layer.shadowOffset = CGSize(width: 0, height: 3)
        self.layer.shadowRadius = 3
        self.layer.shadowOpacity = 0.3
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height:
8)).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale

        setupShadowDone = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        print("Layout subviews!")
        setupShadow()
    }


text:
Q: How to get the license text for Google Maps on Xamarin iOS? I'm using the Xamarin.Google.iOS.Maps NuGet. Google documentation tells me display the text of the license in my app, saying

You can get the attribution text by making a call to [GMSServices openSourceLicenseInfo]

Fine, however the NuGet does not support GMSServices, and after searching high and low I can't find the license text anywhere on the web.
How do I get the text?

A: [GMSServices openSourceLicenseInfo] equals Google.Maps.MapServices.OpenSourceLicenseInfo in Xamarin.
re: https://github.com/xamarin/GoogleApisForiOSComponents/blob/b4d46b01784fc0c30ad2553b0307e0923586cff4/source/Google/Maps/ApiDefinition.cs#L1244

Attribution Requirements
If you use the Google Maps SDK for iOS in your application, you must include the attribution text as part of a legal notices section in your application. Including legal notices as an independent menu item, or as part of an "About" menu item, is recommended.
You can get the attribution text by making a call to Google.Maps.MapServices.OpenSourceLicenseInfo


text:
Q: How to use term distances for ranking in Solr/Lucene Is it possible to use term distances for ranking in Solr/Lucene? For example when searching for a b c a document with the phrase "a b c" should get an higher score than a document that contains all terms but with a larger term distance (a x x x b x x x c), a different order (c b a) or a subset of terms (a b).
I'm aware of proximity searches but their influence on the score seems unclear. Do they fulfill my requirements? Since I wan't to search in the complete document, does it make sense to use sth. like 99999 as the proximity (e.g. "a b c"~99999)?


text:
Q: Inheritance person class not working I've made an inheritance class with base class Person
Person.h
#include <iostream>
#include <string>

using namespace std;

class Person
{
    friend ostream& operator<<(ostream &os, const Person &p);
    friend istream& operator>>(istream &is, Person &p);
private:
    char* m_name;
    int m_age;
    string m_ssn;
protected:
    virtual void Read(istream &is);
    virtual void Write(ostream &os) const;
public:
    Person();
    Person(const char* const name, int age, const string &ssn);
    Person(const Person &p);
    ~Person();
    Person & operator = (const Person& other);
    virtual string getName() const;
    virtual int getAge() const;
    virtual string getSSN() const;
    void setName(const char* const name);
    void setAge(int age);
    void setSSN(string ssn);
    string getType() const;
};

Person.cpp

#include <iostream>
#include <string>
#include "Person.h"

using namespace std;

ostream& operator<<(ostream &os, const Person &p)
{
 p.Write(os);
 return os;
}

istream& operator>>(istream &is, Person &p)
{
 p.Read(is);
 return is;
}

Person::Person()
{
 m_name = new char[10];

 for (int i = 0; i < 10-1; i++)
 {
  m_name[i] = 'X';
 }
 m_name[10 - 1] = '\0';

 m_age = 0;
 m_ssn = "XXX-XX-XXXX";
}

Person::Person(const char* name, int age, const string &ssn)
{
 m_name = new char[(int)strlen(name)+1];

 for (int y = 0; y < (int)strlen(name); y++)
  m_name[y] = name[y];
 m_age = age;
 m_ssn = ssn;
}

Person::Person(const Person& P)
{
 m_name = new char[(int)strlen(P.m_name)+1];

 for (size_t i = 0; i <= (int)strlen(P.m_name); i++)
 {
  m_name[i] = P.m_name[i];
 }
 m_age = P.m_age;
 m_ssn = P.m_ssn;
}

Person::~Person()
{
 delete[] m_name;
}

Person& Person::operator=(const Person& other)
{
 if (this == &other)
  return *this;
 delete [] m_name;

 m_name = new char[(int)strlen(other.m_name) + 1];
 for (int i = 0; i <= (int)strlen(other.m_name); i++)
 {
  m_name[i] = other.m_name[i];
 }

 m_age = other.m_age;
 m_ssn = other.m_ssn;
}

string Person::getName() const
{
 return string(m_name);
}

int Person::getAge() const
{
 return int(m_age);
}

string Person::getSSN() const
{
 return string(m_ssn);
}

void Person::setName(const char* const name)
{
 delete[] m_name;
 m_name = new char[(int)strlen(name) + 1];

 for (int i = 0; i <= (int)strlen(name); i++)
 {
  m_name[i] = name[i];
 }
}

void Person::setAge(int age)
{
 m_age = age;
}

void Person::setSSN(string ssn)
{
 m_ssn = ssn;
}

string Person::getType() const
{
 return string("Person");
}

void Person::Write(ostream &os) const
{
 if (&os == &cout)
 {
  os << "Name: " << m_name << "\nAge: " << m_age << "\nSSN: " << m_ssn;
 }
 else
  os << m_name << "\n" << m_age << "\n" << m_ssn;
}

void Person::Read(istream &is)
{
 string name;
 if (&is == &cin)
 {
  cout << "Enter the Name: " << flush;
  getline(is, name);
  if (name.length() == 0)
   getline(is, name);
  cout << "Enter the Age: " << flush;
  is >> m_age;
  cout << "Enter the SSN: " << flush;
  getline(is, m_ssn);
  is.get();
 }
 else
 {
  getline(is, name);
  if (!is)
   return;
  if (name.length() == 0)
   getline(is, name);
  is >> m_age;
  getline(is, m_ssn);
  is.get();
 }
 delete[] m_name;
 m_name = new char[name.length() + 1];
 for (int i = 0; i < (int)name.length(); i++)
 {
  m_name[i] = name[i];
 }
 m_name[name.length()] = '\0';
}

I'm not even going to put in the inheriting class, which is Student, because I already get errors when I test out my Person class.
I've tried in my main the following:

#include "Person.h"
#include "Student.h"

int main()
{

 Person ptr2Stu("Joe", 22, "123-45-6678");
 cout << ptr2Stu.getName() << endl;
 cout << ptr2Stu.getAge() << endl;
 cout << ptr2Stu.getSSN() << endl;
 cout << ptr2Stu.getType() << endl;

 system("pause");
}

I receive errors when trying to build this.

A: There is problem in Person.cpp
Person::Person(const char* name, int age, const string &ssn)

In header file, declaration is
Person(const char* const name, int age, const string &ssn);
                    ^^^^

So, change the either of the declaration/definition.
You can omit typecasts in getSSN and getAge.


text:
Q: Use webpage link to access mobile GPS app and pass current location to the app My objective is to use my current webpage to access a native mobile gps app, from a link on the webpage, and have that link send my current location and destination location to the application. It must all be done from my web page. For example I click a building address link and it takes me to that building thru the application. The user will have to be browsing on a mobile device.

A: all the mobile browsers support the GEO location API and you can use their location to center a map with Virtual Earth or Google and of course add items you need to add to the map like pushpins etc. I have a blog post about it:
http://professionalaspnet.com/archive/2012/05/25/A-Study-Using-The-HTML5-Geolocation-API.aspx


text:
Q: kv_do() not working as expected This is in my init.c:
server_data_t **data = (server_data_t**)get_env(argv, US_SERVER_DATA);
data[0] = (server_data_t*)calloc(1, sizeof(server_data_t));

kv_t *channels = &data[0]->channels;
kv_t *users = &data[0]->users;

kv_init(channels, "channels.dat", 10*1024, 0, 0, 0);
kv_init(users, "users.dat", 10*1024, 0, 0, 0);

These initializations were only for testing puproses:
channel_t *channel = (channel_t*)calloc(1, sizeof(channel_t));
channel->name = strdup("Test channel");
channel->id = 1;

kv_item channel_item;
channel_item.key = (char*)&channel->id;
channel_item.klen = sizeof(u32);
channel_item.val = (char*)channel;
channel_item.in_use = 0;

kv_add(channels, &channel_item);

channel_t *channel2 = (channel_t*)calloc(1, sizeof(channel_t));
channel2->name = strdup("Test channel2");
channel2->id = 2;

kv_item channel_item2;
channel_item2.key = (char*)&channel2->id;
channel_item2.klen = sizeof(u32);
channel_item2.val = (char*)channel2;
channel_item2.in_use = 0;

kv_add(channels, &channel_item2);

kv_do(channels, NULL, sizeof(u32), test_proc, 0);

The user defined process kv_do process:
static int test_proc(const kv_item *item, const void *ctx)
{
    return 1;
}

Starting the server segfaults after the kv_do test process starts an infinite loop when trying to visit all items. It works fine with one item in the list, then it just visits the first item and quits. I can also visit the items one by one with the ID using kv_get.
I found an edge case where it worked with two items if my key was "Test Channel" key length was strlen("Test Channel") and then the next channel key was "Test Channel2" where key-length was as long as the first items key-length. Pretty confusing.
Is the mistake in the code (pointers and such) or how the process is supposed to work with the return value of 1?
I know that gwan sometimes have trouble with KVMs so if it could be that, I'm running Oracle VM VirtualBox v5.0.24 with Ubuntu.

A: Are the kv.c and persistence.c G-WAN examples working for you?
If any of them crashes, then you are probably using out-of-sync. G-WAN headers (gwan.h) with a recent ./gwan executable.


text:
Q: CORS AWS API-Gateway with Authentication Angular2 my AWS API-Gateway is configured as Lambda Proxy. In Lambda i added the following Headers:
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key'

First, everythink works fine with it. Now i added an Authorizer with CognitoUserPool and i get the following Error:
XMLHttpRequest cannot load https://xxx.eu-west-1.amazonaws.com/xxx/xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.

I think the problem is, that with Authentication my Lambdafunction is not invoked and so no Headers were set. I call the Endpoint from an Angular2 Application with
const headers = new Headers();
headers.append('Authorization', 'authtoken');
http.get('address...', headers);

But the headers were not set/append to the request because of any CORS-reasons i think.
Anyone an idea how can i solve this?
P.S.: I tried the "Enable Cors" feature of API-Gateway but that does not work.
Edit: I also have a "OPTIONS" Method in Gateway with Authentication, that responds with the Headers above.
Greetings

A: Is your Lambda Proxy function mapping to the ANY HTTP method type? If so, it may be attempting to perform authentication on the pre-flight (OPTIONS) request. If this is the case, try mapping your proxy function to POST, GET, etc. specifically.

A: I found the solution of the problem. It was not caused by API-Gateway. Problem was this code:
const headers = new Headers();
headers.append('Authorization', 'authtoken');
http.get('address...', headers);

The "get" needs a "RequestOptions"-object. It has to be:
const headers = new Headers();
headers.append('Authorization', 'authtoken');
const options = new RequestOptions({headers: headers});
http.get('address...', options);


text:
Q: IIS + PHP - Url Rewrite Issue first of all my english is not so good and thats because i cant found what i found.
Ok, here is my web.config rules
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
            <rule name="Imported Rule 1">
                <match url="^Girisyap$" ignoreCase="true" />
                <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Rewrite" url="giris.php" />
            </rule>
                <rule name="Imported Rule 2" stopProcessing="true">>
                  <match url="^([0-9a-zA-Z-_/]+)$" />
                  <action type="Rewrite" url="Sayfalar.php?Sayfa={R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
        <directoryBrowse enabled="false" />
    </system.webServer>
</configuration>

With this rules, when i try to visit http:// localhost:84/Girisyap it showing giris.php as well.If i visit http:// localhost:84/Around showing me Sayfalar.php?Sayfa=Around as well to.But when i visit http:// localhost:84/ it giving me 403.14 - Forbidden error. Because im not using index.php or default.php and i dont want it.

How can show 'Sayfalar.php?Sayfa=' (Sayfa is empty) visiting to http:// localhost:84/ as well

A: In Apache you will find an index.php file in htdocs that will set the default website to xampp folder(by default). Maybe you must find the same case in IIS. Try to edit the default website to your website's directory and maybe you can set you binding to other port(as you want and it is enable to use=84). Good luck, it's working to me.
Add this code to web.config file
<system.webServer>
     <defaultDocument>
        <files>
          <add value="Login.aspx" />
        </files>
     </defaultDocument>
     <directoryBrowse enabled="false" />
</system.webServer>

Note : Login.aspx is an example. Change it to your default document.


text:
Q: How to share snapshots and ami? I have a snapshot of my ebs backed instance. I have registered an image of it. I wanted to share my snapshot with other account. Sharing was successful but when I tried to create an image from it, It showed an error (shown below)
"Invalid snapshot snap-xxxxxx" You are not authorized.

So, My questions are:

*

*How can I make it successful ?

*Do I need to create a volume by myself so that new image being created has a volume?

*If I share an ami to other user, and other user runs an instance from it. who will be paying for this running instance ?

*Any other ideas are welcome.

A: You almost certainly did not apply the launch permission that you thought you did.
Run the command

ec2-describe-image-attribute ami-xxxxxxxx -l launchPermission ami-xxxxxxxx group all

and make sure that the AMI generated from the snapshot has launch permissions that allow the other account to launch it.


text:
Q: Alias name in Snowflake Can someone please say how to create an alias name for a table in a snowflake?
sample table:
CREATE OR REPLACE TABLE USER.EMPLOYEE(
    EMPNO CHAR(6 ) COLLATE 'en_US-upper-rtrim' NOT NULL,
    FIRSTNME VARCHAR(12 ) COLLATE 'en_US-upper-rtrim' NOT NULL,
    MIDINIT CHAR(1 ) COLLATE 'en_US-upper-rtrim' NULL,
    LASTNAME VARCHAR(15 ) COLLATE 'en_US-upper-rtrim' NOT NULL,
    WORKDEPT CHAR(3 ) COLLATE 'en_US-upper-rtrim' NULL,
    PHONENO CHAR(4 ) COLLATE 'en_US-upper-rtrim' NULL,
    HIREDATE DATE NULL,
    JOB CHAR(8 ) COLLATE 'en_US-upper-rtrim' NULL,
    EDLEVEL SMALLINT NOT NULL,
    SEX CHAR(1 ) COLLATE 'en_US-upper-rtrim' NULL,
    BIRTHDATE DATE NULL,
    SALARY NUMBER(9,2) NULL,
    BONUS NUMBER(9,2) NULL,
    COMM NUMBER(9,2) NULL
);

Alias:
CREATE ALIAS "USER"."EMP" FOR TABLE "USER"." EMPLOYEE"

A: If you are searching for SYNONYM/ALIAS, they are not supported by Snowflake.
CREATE SYNONYM EMP FOR USER.EMPLOYEE;

Reference: Migrating Oracle Database to Snowflake: Reference Manual - APPENDIX D

Depending on requirements VIEW could be used instead:
CREATE VIEW USER.EMP
AS
SELECT *
FROM  USER.EMPLOYEE;


text:
Q: Reset current exception chain I have this code in my app:
try:
    return self.wsgi_app(environ, start_response)
except Exception:
    logger.warning('Failed to render the custom %s page', exc.code, exc_info=True)

When my MongoDB is down, I have this:
18:44:55 WARNING Failed to render the custom 500 page
Traceback (most recent call last):
...
  File ".../venv/lib/python3.5/site-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 61] Connection refused

I don't want info about the first exception -- I already logged it my code before. I want only exception which happens inside the try/except block to be logged (the one which is shown after "During handling of the above exception, another exception occurred:").
How can I reset current exception chain before the try/except block?
I could try:
try:
    ...
except Exception as exc:
    exc.__cause__ = None
    logger.exception(...)

But it would spoil the useful chain of several exceptions which might have happened inside try/except.


text:
Q: Accessing BcdStore from Delphi I'm trying to convert this code fragment into Delphi and I got stuck on the for each objWBL in colObjects.
if not objBcdStore.EnumerateObjects( &h10200003, colObjects ) then
    WScript.Echo "ERROR objBcdStore.EnumerateObjects( &h10200003 ) failed."
    WScript.Quit(1)
end if

for each objWBL in colObjects
    WScript.Echo ""
    WScript.Echo "Windows Boot Loader"
    WScript.Echo "-------------------"

    WScript.Echo "identifier              " & GetBcdId( objWBL.Id )

    If objWBL.Id = current then

      if not objWBL.GetElement(BcdOSLoaderInteger_NumberOfProcessors, objElement ) then
          WScript.Echo "ERROR WBL GetElement for " & Hex(BcdOSLoaderInteger_NumberOfProcessors) & " failed."
          WScript.Quit(1)
      end if
      WScript.Echo "numproc              " & objElement.Integer

      if not objWBL.GetElement(BcdOSLoaderBoolean_UseBootProcessorOnly, objElement ) then
          WScript.Echo "ERROR WBL GetElement for " & Hex(BcdOSLoaderBoolean_UseBootProcessorOnly) & " failed."
          WScript.Quit(1)
      end if
      WScript.Echo "onecpu              " & objElement.Boolean

    end if
next

My partial q&d translation (caution, must be Admin to run it):
uses
  OleAuto,
  ActiveX;

function GetObject(const objectName: String): IDispatch;
var
  bindCtx: IBindCtx;
  moniker: IMoniker;
  chEaten: Integer;
begin
  OleCheck(CreateBindCtx(0, bindCtx));
  OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker));
  OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result));
end;

procedure TForm44.btnClick(Sender: TObject);
var
  colObjects   : OleVariant;
  objBcdStore  : OleVariant;
  objWMIService: OleVariant;
begin
  objWMIService := GetObject('winmgmts:{impersonationlevel=Impersonate,(Backup,Restore)}!root/wmi:BcdStore');
  if not objWMIService.OpenStore('', objBcdStore) then
    Caption := 'error'
  else begin
    objBcdStore.EnumerateObjects($10200003, colObjects);
    //???
  end;
end;

EnumerateObjects is defined as
boolean EnumerateObjects(
  [in]   uint32 Type,
  [out]  BcdObject Objects[]
);

I have no idea how to walk over the BcdObject array in Delphi.

A: you must use the VarArrayLowBound and VarArrayHighBound functions to get the bounds of the variant array returned by the EnumerateObjects function  and then you can use a for loop to iterate over the elements of the array.
check this sample
Uses
 ComObj,
 ActiveX;

function GetObject(const objectName: String): IDispatch;
var
  bindCtx: IBindCtx;
  moniker: IMoniker;
  chEaten: Integer;
begin
  OleCheck(CreateBindCtx(0, bindCtx));
  OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker));
  OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result));
end;

procedure TForm44.Button1Click(Sender: TObject);
var
  colObjects   : OleVariant;
  objBcdStore  : OleVariant;
  objWMIService: OleVariant;

  i : Integer;
  objWBL : OleVariant;
begin
  objWMIService := GetObject('winmgmts:{impersonationlevel=Impersonate,(Backup,Restore)}!root/wmi:BcdStore');
  if not objWMIService.OpenStore('', objBcdStore) then
    Caption := 'error'
  else
  begin
    objBcdStore.EnumerateObjects($10200003, colObjects);
       if not VarIsNull(colObjects) and VarIsArray(colObjects) then
       for i := VarArrayLowBound(colObjects, 1) to VarArrayHighBound(colObjects, 1) do
       begin
          objWBL:=colObjects[i];
          //do your stuff here

       end;
  end;
end;

A: Thanks to RRUZ for answer - I learned something new - but sadly the correct answer was "Don't do that" (how typical!).
It turned out that by enumerating the Windows Boot Loader objects, one can't find out which of the objects is the "current" one. As I finally found out (thanks to the Hey, Scripting Guy! article from the July 2008 issue of the TechNet Magazine), the correct way is to open the loader object directly by it's well-known ID. (Which is, again, well-hidden and not well-known. The only official documentation I managed to find on the well-known BCD GUIDs is Boot Configuration Data in Windows Vista document.)
The sample code below first opens BCD WMI object. Then it opens the default store and shows the information for the {current} boot entry object (accessed by the well-known ID).
Next it opens the Windows Boot Manager object (by using its well-known ID), reads its DefaultObject element to determine the GUID of the default boot entry, opens this object by its GUID and shows the information.
ShowLoaderInfo displays only ID (GUID), Description and NumberOfProcessors (which was an information I wanted to get from the BCD). A funny trick here is that the latter is of the BcdIntegerElement type, which returns its value through the Integer property, with a "feature" that the returned value is not an integer but a string. A note from the MSDN explains:

The integer value of the element. The value is passed as a string
  because Automation does not natively support 64-bit integers.

(Yeah, great! Why does it have to be 64-bit anyway? Are 2 billion processors not enough?)
For a full list of supported Windows Boot Loader elements see BcdOSLoaderElementTypes.
program ShowBCDInfo;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ComObj,
  ActiveX;

const
  Description                 = $12000004; //http://msdn.microsoft.com/en-us/aa362652(v=VS.85)
  UseBootProcessorOnly        = $26000060; //http://msdn.microsoft.com/en-us/aa362641(v=VS.85)
  NumberOfProcessors          = $25000061;
  ForceMaximumProcessors      = $26000062;
  ProcessorConfigurationFlags = $25000063;
  DefaultObject               = $23000003; //http://msdn.microsoft.com/en-us/aa362641(v=VS.85)

  CurrentGUID = '{fa926493-6f1c-4193-a414-58f0b2456d1e}'; //http://msdn.microsoft.com/en-us/windows/hardware/gg463059.aspx
  WBMGUID     = '{9dea862c-5cdd-4e70-acc1-f32b344d4795}';

function GetObject(const objectName: String): IDispatch;
var
  bindCtx: IBindCtx;
  moniker: IMoniker;
  chEaten: Integer;
begin
  OleCheck(CreateBindCtx(0, bindCtx));
  OleCheck(MkParseDisplayName(bindCtx, StringToOleStr(objectName), chEaten, moniker));
  OleCheck(moniker.BindToObject(bindCtx, nil, IDispatch, Result));
end;

procedure ShowLoaderInfo(const name: string; const obj: OleVariant);
var
  objElement: OleVariant;
begin
  Writeln(Format('%s ID: %s', [name, string(obj.id)]));
  if obj.GetElement(Description, objElement) then
    Writeln(Format('Description: %s', [objElement.String]));
  if obj.GetElement(NumberOfProcessors, objElement) then
    Writeln(Format('NumProc: %s', [objElement.Integer]));
end;

procedure ShowBcdInfo;
var
  objBcdStore  : OleVariant;
  objWBL       : OleVariant;
  objWBM       : OleVariant;
  objWMIService: OleVariant;
begin
  objWMIService := GetObject('winmgmts:{(Backup,Restore)}\\.\root\wmi:BcdStore');
  if not objWMIService.OpenStore('', objBcdStore) then
    Writeln('*** error opening store')
  else begin
    if objBcdStore.OpenObject(CurrentGUID, objWBL) then
      ShowLoaderInfo('{current}', objWBL);
    if objBcdStore.OpenObject(WBMGuid, objWBM) and
       objWBM.GetElement(DefaultObject, objWBL) and
       objBcdStore.OpenObject(string(objWBL.ID), objWBL)
    then
      ShowLoaderInfo('{default}', objWBL);
  end;
end;

begin
  try
    OleInitialize(nil);
    try
      ShowBCDInfo;
    finally OleUninitialize; end;
    Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.


text:
Q: Test WAN access to our local area network after opening the DMZ On our router we have recently opened a port. We want to test whether those outside our local area network are able to obtain access. How can we do this?
Unfortunately, we do not have a connection to anything other than our local area network. We thought that perhaps we website exists for this purpose.

A: It sounds like you're asking for a product or service recommendation, which we don't do. Additionally, I can't imagine a (legit) business model that would make money hosting a port scanner. Kidz, amirite?
Helpful answers : Take your laptop and go to Starbucks. Or log into a remote server at a hosting service like AWS or Azure. Or log into your home machine remotely using LogMeIn or Chrome Remote Desktop or one of dozens of other options and try it from there.


text:
Q: problems with lineargradient - overflow is overlapping with the adjacent text when I am using linear-gradient for background color as in the  fiddle:
http://jsfiddle.net/dkzn5/
where the html code is:

 1 sample arrow

 overflown text must be hidden and the visible text  must be in single line  2

the text is overlapping at the right end in variation2.
Can you please help me out with this?

A: .variation2 h2 {
    width:90%;
    margin-right:10%;
}

A: Decrease the font size or the heading
.variation2 h2{width:90%;}

A: Add another container with padding:

 overflown text must be hidden and the visible text  must be in single line  2

http://jsfiddle.net/dkzn5/3/


text:
Q: Limiting revealing of sprite sheet as text box background What I have
I have two text boxes, each with a background image that changes on focus. All background images are derived from the one sprite sheet.
What I need
I need the limit how much of the sprite sheet is revealed because the text box is larger than the amount of the background I wish to reveal.
Important
Editing the markup is not an option. I require a CSS-based solution.
My code

#foo,
#bar {
  background-position: left center;
  background-repeat: no-repeat;
  background-size: 100px 100px;
  background-image: url("http://s30.postimg.org/5huu7u8ip/test.png");
  padding: 0 1em;
  padding-left: 50px;
  font-size: 17px;
  height: 3em;
}
#foo {
  background-position: 0px 0px;
}
#bar {
  background-position: 0px -50px;
}
#foo:focus {
  background-position: -50px 0px;
}
#bar:focus {
  background-position: -50px -50px;
}

Click into and out of each box to toggle default and focus states:

    <input type="text" size="20" value="" class="input" id="foo" placeholder="foo" name="foo">

    <input type="text" size="20" value="" class="input" id="bar" placeholder="bar" name="bar">

Using the above live example, there should never be a case where more than one icon showing. On focus is fine, the problem occurs on the default state of the text boxes.

A: You can use some Javascript to toggleClass on the label when the input is on focused and unfocused. Note, I wrapped the p tags into a form and use nth-* selector to target the labels.
Jsfiddle Example

$('input').bind('focus blur', function () {
   $(this).parent('label').toggleClass('focus');
});
label:before {
  content: "";
  display: inline-block;
  background-position: left center;
  background-repeat: no-repeat;
  background-size: 100px 100px;
  background-image: url("http://s30.postimg.org/5huu7u8ip/test.png");
  width: 50px;
  height: 50px;
  vertical-align: top;
}
input[type="text"] {
  padding: 0 1em;
  font-size: 16px;
  height: 50px;
  box-sizing: border-box;
}
form p:nth-child(1) label:before {
  background-position: 0px 0px;
}
form p:nth-child(2) label:before {
  background-position: 0px -50px;
}
form p:nth-child(1) label.focus:before {
  background-position: -50px 0px;
}
form p:nth-child(2) label.focus:before {
  background-position: -50px -50px;
}

Click into and out of each box to toggle default and focus states:

<form>

      <input type="text" size="20" value="" class="input" id="foo" placeholder="foo">

      <input type="text" size="20" value="" class="input" id="bar" placeholder="bar">

</form>

If yo can move the label after the input tag, then you can use CSS sibling selector ~ or + to do it. No Javascript is needed, see the demo below.
Jsfiddle Example

label {
  content: "";
  display: inline-block;
  background-position: left center;
  background-repeat: no-repeat;
  background-size: 100px 100px;
  background-image: url("http://s30.postimg.org/5huu7u8ip/test.png");
  width: 50px;
  height: 50px;
  float: left;
  margin-right: 4px;
}
input[type="text"] {
  padding: 0 1em;
  font-size: 16px;
  height: 50px;
  box-sizing: border-box;
}
#foo + label {
  background-position: 0px 0px;
}
#bar + label {
  background-position: 0px -50px;
}
#foo:focus + label {
  background-position: -50px 0px;
}
#bar:focus + label {
  background-position: -50px -50px;
}

Click into and out of each box to toggle default and focus states:

  <input type="text" size="20" value="" class="input" id="foo" placeholder="foo">

  <input type="text" size="20" value="" class="input" id="bar" placeholder="bar">


text:
Q: How to handle dalvikvm VFY: unable to resolve virtual method on android? I write some code like this:
String focusMode = camera.getParameters().getFocusMode();

but the getFocusMode() function was api level 5, my app's android:minSdkVersion="3" and android:targetSdkVersion="10"
so when I call this method on a android used api 3 or 4 will crash.
How can I handle the exception, I have tried try {} catch(Execption e) {}, but it can't catch. It also crash, How can I do it?

A: startForeground method implemented from android docs is a good example how to implement functionality for different API levels. Basically you have to check for the method using reflection.


text:
Q: Как решить проблему разрешения типа generic без раскрытия скрытого типа? Для минимизации описания проблемы, расскажу как можно кратче.

*

*Публичный интерфейс : interface IComObject : IDisposable, IAsSupport {...}

*Внутренний интерфейс: interface IComObject<out TInterface> : IComObject {...}
Мне нельзя открывать IComObject<out TInterface>, но, нужно предоставить пользователю доступ к методу который реализует объект, а точнее:
public TInterface IAsSupport.As<TInterface> where TInterface : IComObject
{
...
}

По сути дела, мне этого достаточно, но при реализации этого метода встал вопрос о том, как мне определить что за тип содержится в типе:
IComObject<???> : IComObject

Это можно как-то определить?
Все что мне приходит в голову, это еще один слой, с типом object, от которого я уже получу необходимую информацию.

A: Можно между первым и вторым интерфейсом добавить еще один, доступный во внешнем мире, но ничего не содержащий, кроме самого дженерика, а скрытый наследовать от него. В этом случае у вас generic тип становиться доступным, а внутренний интерфейс вы не публикуете:
/// <summary>
/// Публичный интерфейс
/// </summary>
public interface IComObject : IDisposable, IAsSupport {...}

/// <summary>
/// Интерфейс без тела, доступный во вне
/// </summary>
/// <typeparam name="TInterface"></typeparam>
public interface IVisibleComObject<out TInterface> : IComObject where TInterface : IComObject { }

/// <summary>
/// Интерфейс не доступный во вне
/// </summary>
/// <typeparam name="TInterface"></typeparam>
private interface IComObject<out TInterface> : IVisibleComObject<TInterface>  {...}


text:
Q: Converting then matching date types in VBA I am creating a button macro in excel using VBA. The gist of it is that I have a date in Sheet1 of format yymmdd, and a row of dates in Sheet2 that I need to match it with.
Input date:

Date lookup:

At the moment, I have the following VBA code running when I click a button in Sheet1:
Sub Button3_Click()
    Dim dateInput As String
    Dim fmtDate As Date, yr As String, mo As String, da As String
    Dim dates As Range
    Dim dateMatch As Range
    ' Convert the date in B7 to dd/mm/yyyy format
    dateInput = Worksheets("22-23 AP2 report").Range("B7").Value

    yr = "20" & Left(dateInput, 2)
    mo = Mid(dateInput, 3, 2)
    da = Right(dateInput, 1)
    fmtDate = DateSerial(yr, mo, da)

    Debug.Print fmtDate

    ' Find the corresponding column to the date in Hrs comparison
    Set dates = Worksheets("Hrs comparison").Range("C2").End(xlToRight)
    Set dateMatch = dates.Find(fmtDate)

    If dateMatch Is Nothing Then
        MsgBox "The date could not be found in the Hrs comparison sheet"
    Else
        Dim leftmostColumn As Integer
        leftmostColumn = dateMatch.Column

        ' Reference the leftmost column in the Hrs comparison sheet
        Dim leftmostColumnRange As Range
        Set leftmostColumnRange = Worksheets("Hrs comparison").Columns(leftmostColumn)

        ' Do something with the leftmost column range, for example:
        Debug.Print leftmostColumnRange.Address
    End If
End Sub

Ideally, the code would return the leftmost column of the matching date in Sheet2 (notice the columns are merged), however, it cannot seem to find a direct match. The Debug.Print fmtDate line correctly prints 2/12/2022, and I have also tried wrapping it with CDate(), to no avail.


text:
Q: Determining if the result of adding (subtracting) two binary numbers is correct as NBC and 2's My task is to convert two numbers to binary, add them and determine if the result is correct as a NBC and 2's. Then I have to subtract B from A by converting by using 2's for calculating -B [that is A+(-B)].
The first number is 32723 -> 0111 1111 1101 0011
The second number is 5321 -> 0001 0100 1100 1001
The result of addition is 38044 -> 1001 0100 1001 1100
Now, I guess that this one above is correct as NBC, but what about 2's? Is this one considered as a negative value or is it positive?
For the second task -B is 1110 1011 0011 0111. Is it permitted to add two number whereas one is NBC and second is 2's?

A: Is this one considered as a negative value or is it positive?
Since the most significant bit (MSB) is $1$, the number is considered as a negative value in 2's complement integer encoding. When you added $32723$ and $5321$, there was a $1$ carried into the MSB but not out of it. That sets up an overflow condition in 2's complement arithmetic: just about any CPU will have a condition flag for that. So in 2's complement the answer is not legitimate: it could not be done in the 16 bit integer format.
Is it permitted to add two number[s] whereas one is NBC and second is 2's?
Strictly no, but if the MSB of the Natural Binary Code (unsigned) number is zero the 2's complement representation is the same, so you are adding two 2's complement numbers and the operation is fine. So in this particular case you can add $A$ and $-B$ to correctly get $A-B$. In that addition you will get carry both into and out of the MSB, so there is no 2's complement overflow.


text:
Q: OpenCL C/C++ dynamic binding library (win32 and more) I'm giving a try at OpenCL, and in order to put this in production I'd like to be able to bind dynamically to OpenCL.DLL (when under Windows), in order to handle 'gracefully' the case where no OpenCL is installed on the host computer.
Is there any available library (or code snippet) that takes care of this dynamic binding in C or C++, much like GLEW does for OpenGL ? I'd like to avoid the hassle to do it myself.
Thanks,

A: Here you go:
http://clcc.sourceforge.net/clew_8h.html

A: Since you're dealing with Win32, the easiest solution is delay loading. If you delay-load OpenCL, and the compiler-added stub fails to find it, it will call __pfnDliFailureHook2(dliFailLoadLib). You can handle the error there; if you don't provide a handler you'll get the default behavior (program aborts). In either case the program will not have a static dependency on OpenCL.

A: QtOpenCL http://labs.qt.nokia.com/2010/04/07/using-opencl-with-qt/


text:
Q: Быстрый алгоритм генерации ключей в схеме Шнорра Дано: тест на простоту, функция генерации простого числа.
Нужно найти такой алгоритм, который генерирует простое число-часть открытого ключа q такое, что:
(p - 1) % q = 0, где
p - простое число 1024 бит и также генерируемая часть ключа,
q - 160 бит.
Тест Миллера-Рабина:
def milrab(n, k):
    if n < 2 or n % 2 == 0:
        return 0
    d = n - 1
    r = 0
    while d % 2 == 0:
        d >>= 1
        r += 1
    for i in range(k):
        a = random.randint(2, n - 2)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for j in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                continue
        return False  # составное
    return True  # простое

Генерация простого числа размером bits битов:
def pgen(bits):
    prime = False
    a = 0
    while not prime:
        a = random.randint(2**(bits - 1), 2**bits - 1)
        prime = milrab(a, 7)
    return a

Части открытого ключа p и q:
def gen_p():
    return pgen(1024)

def gen_q(p):
    q = pgen(160)
    while (p - 1) % q != 0:
        q = pgen(160)
    return q

Проблема в том, что генерация q идет очень медленно. Есть быстрый способ посчитать q как множитель p - 1?

A: Пока что я пришел к тому, что можно генерировать простое число q (160 бит), затем генерировать еще одно число, назовем q_p, четное и длиной 1024-160=864 бит, которое мы умножаем на q и прибавляем единицу (если длина произведения получилась 1023 бита, переходим на следующую итерацию и заново генерируем q_p), таким образом получая p, простоту которого проверяем тестом.
Кроме того в тесте при генерации случайного числа (в моем случае оно называется a) я поставил диапазон 2:200 (вместо 2:n-2) для n > 202.
Время выполнения снизилось до 0-5 секунд.


text:
Q: pserve not working inside docker container I am trying to develop pyramid application with using docker-container.I build a docker images with below docker file.
FROM ubuntu
RUN  apt-get -y update
RUN  apt-get -y install python3.6 python3.6-dev libssl-dev wget git python3-pip libmysqlclient-dev
WORKDIR /application
COPY . /application
RUN pip3 install -e .
EXPOSE 6543

This is my docker-compose file
version: '3'
services:
  webserver:
    ports:
      - 6543:6543
    build:
      context: .
      dockerfile: Dockerfile-development
    volumes:
      - .:/application
    command: pserve development.ini --reload

The docker image is created successfully. But when i run the docker-compose up and browse the url localhost:6543 it is showing The site can't be reached now. But when i run it locally with pserve development.ini it is working fine. I tried to connect to the docker interactively and run the command pserve develpment.ini, It is showing as
Starting server in PID 18.
Serving on http://localhost:6543

But when i browse the url from chrome it is not working.

A: You need to listen in all network interfaces. In your development.ini file, use:
listen = *:6543

You should get a log which says:
Serving on http://0.0.0.0:6543

Then try to access it from your host machine using localhost:6543.


text:
Q: Homeomorphisms between infinite-dimensional Banach spaces and their spheres As I know Cz. Bessaga has proved that an infinite-dimensional Banach space is homeomorphic to its unit sphere.
Unfortunately I do not have his book but I want to know is this theorem true without dependence from that the space is separable or not, and it is real or complex.
That is, is it true that:

*

*a real separable infinite-dimensional Banach space is homeomorphic to its sphere;

*a complex separable infinite-dimensional Banach space is homeomorphic to its sphere;

*a real non-separable infinite-dimensional Banach space is homeomorphic to its sphere;

*a complex non-separable infinite-dimensional Banach space is homeomorphic to its sphere?

A: Bessaga showed something stronger, but only for Hilbert spaces. Generalization to certain Banach spaces (i.e., those which are linearly injectable into some $c_0(\Gamma)$) was given by Dobrowolski. The following paragraph is   from Diffeomorphisms between spheres and hyperplanes in infinite-dimensional Banach spaces by D. Azagra, Studia Math. 125 (1997), no. 2, 179–186.

In 1966 C. Bessaga [1] proved that every infinite-dimensional Hilbert space
  $H$ is $C^\infty$ diffeomorphic to its unit sphere. The key to prove this astonishing
  result was the construction of a diffeomorphism between $H$ and $H \smallsetminus \{0\}$ being
  the identity outside a ball, and this construction was possible thanks to
  the existence of a $C^\infty$ non-complete norm in $H$. In 1979 T. Dobrowolski [2] developed
  Bessaga's non-complete norm technique and proved that every infinite-dimensional
  Banach space $X$ which is linearly injectable into some $c_0(\Gamma)$ is
  $C^\infty$ diffeomorphic to $X \smallsetminus \{0\}$.

[1] Bessaga, C. Every infinite-dimensional Hilbert space is diffeomorphic with its unit sphere. Bull. Acad. Polon. Sci. Sér. Sci. Math. Astronom. Phys. 14 (1966), 27–31.
[2] Dobrowolski, T., Smooth and R-analytic negligibility of subsets and extension of homeomorphism in Banach spaces, Studia Math. 65 (1979), 115-139.


text:
Q: Background Image is not displaying in flask Here is my html template homepage.html in /home/saurabh/flask/templates
<!DOCTYPE>

<title>homepage</title>

Welcome to our Homepage

We will try to make u happy YOU

        LOGIN

        SIGNUP

        ABOUT US

and this is my python script to render above template in /home/saurabh/flask
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/')
def home():
    return render_template("homepage.html")
if __name__=="__main__":
    app.run(debug=True)

Everything is working fine but background-image.I have already tried using static directory but nothing worked.
Background-image is not displaying in web browser??

A: You need to create a directory called: /home/saurabh/flask/static
Move the background image file to that directory.
Then change the line in your template file to:
background-image: url("{{ url_for('static', filename='599783.jpg') }}");

A: You can call image from web server instead of flask default web server for your files.

http://www.yoursitename.com/images/image.jpg

Refer Flask Documentation to solve this image issue


text:
Q: How to test for the existence of a Class when I can't weak link against it I am writing a class that is designed to be re-usable but I have included calls to a class which may not always be available when compiled.
To be more specific I am using Flurry analytics and I want to included calls to that - but not every project that this module may be included in will have access to the Flurry library - I simply want it not compile in those bits of code in these situations. The module will be distributed as source code, so it only has to test at compile time.
So far I have tried:
if([Flurry class]){
    [Flurry logEvent:@"Blah"];
}

This fails "Use of undefined identifier" - Flurry is not defined anywhere, as there is no weak reference to the library
So next tried:
Class flurryClass = NSClassFromString(@"Flurry");
if(flurryClass){
  [flurryClass logEvent:@"Blah"];
}

This fails as "No known class method for selector logEvent"
So I seem to be stuck, as the first method relies on weak linking a library that may not be available to weak link against! The second method I assume fails as I'm calling a Class method on a Class that is currently has no definition so the compiler complains? Is there any solution to this that anyone can think of?

A: You have to use reflection the whole way through. Change your code to this:
Class flurryClass = NSClassFromString(@"Flurry");
if(flurryClass){
  [flurryClass performSelector:@selector(logEvent:) withObject:@"Blah"];
}

A: I would avoid having your library automatically log flurry events to someone else's account without their permission. I would recommend preprocessor checks and requiring implementers to explicitly enable Flurry.
#if MYLIB_ENABLE_FLURRY

    if([Flurry class]){
        [Flurry logEvent:@"Blah"];
    }

#endif //MYLIB_ENABLE_FLURRY

Now if someone wants to add logging from your library you can instruct them that Flurry is required and to compile your library using -DMYLIB_ENABLE_FLURRY=1 or add it to their Other C Flags if they include the source directly.


text:
Q: How to make square cells with collection view layout in swift I'm programming a game with a collection view with 121 buttons (11X11), how can I fix my Collection View cells to be a square? I want to increase or decrease the number of cells so the layout has to be dynamic
This is the code:
import UIKit

class GameViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    let reuseIdentifier="cell"
    @IBOutlet var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.collectionViewLayout = generateLayout()
    }

    @objc
    func animate(for sender:UIButton){
        UIView.animate(withDuration: 0.5, delay: 0, animations: {
            let rotate=CGAffineTransform(rotationAngle: .pi/2)
            let scale=CGAffineTransform(scaleX: 0.5, y: 0.5)
            sender.transform=rotate.concatenating(scale)
        },completion: {_ in
            UIView.animate(withDuration: 0.5, animations: {
                sender.transform=CGAffineTransform.identity
            })
        })
    }

    func generateLayout()->UICollectionViewCompositionalLayout{
        let padding:CGFloat=2
        let itemSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .fractionalHeight(1)
        )
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        item.contentInsets=NSDirectionalEdgeInsets(
            top: 0, leading: padding, bottom: 0, trailing: padding
        )

        let groupSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .absolute(40)
        )

        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: groupSize,
            subitem: item,
            count: 11
        )
        group.interItemSpacing = .fixed(padding)
        group.contentInsets=NSDirectionalEdgeInsets(top: 0, leading: padding, bottom: 0, trailing: padding)

        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing=padding
        section.contentInsets=NSDirectionalEdgeInsets(
            top: padding,
            leading: 0,
            bottom: padding,
            trailing: 0
        )

        let layout = UICollectionViewCompositionalLayout(section: section)

        return layout
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 11
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 11
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ButtonCollectionViewCell
        cell.layoutGridCells(at:indexPath)
        cell.delegate=self

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let size = collectionView.bounds.size.height

        return CGSize(width: size, height: size)
    }

}

A: It can be cumbersome to create exact grids with a collection view.
And, as I mentioned in my comments, if you're not utilizing the built-in advantages of a UICollectionView -- scrolling, memory management via cell reuse, etc -- a collection view may not be the ideal approach.
Without knowing exactly what you need to do, buttons may not be the best to use either...
Here's a quick example using buttons in stack views:
class ButtonGridVC: UIViewController {

    // vertical axis stack view to hold the "row" stack views
    let outerStack: UIStackView = {
        let v = UIStackView()
        v.axis = .vertical
        v.distribution = .fillEqually
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    let promptLabel = UILabel()

    // spacing between buttons
    let gridSpacing: CGFloat = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        // let's add a prompt label and a stepper
        //  for changing the grid size
        let stepperStack = UIStackView()
        stepperStack.spacing = 8
        stepperStack.translatesAutoresizingMaskIntoConstraints = false

        let stepper = UIStepper()
        stepper.minimumValue = 2
        stepper.maximumValue = 20
        stepper.addTarget(self, action: #selector(stepperChanged(_:)), for: .valueChanged)
        stepper.setContentCompressionResistancePriority(.required, for: .vertical)

        stepperStack.addArrangedSubview(promptLabel)
        stepperStack.addArrangedSubview(stepper)

        view.addSubview(stepperStack)
        view.addSubview(outerStack)

        let g = view.safeAreaLayoutGuide

        // these constraints at less-than-required priority
        //  will make teh outer stack view as large as will fit
        let cw = outerStack.widthAnchor.constraint(equalTo: g.widthAnchor)
        cw.priority = .required - 1
        let ch = outerStack.heightAnchor.constraint(equalTo: g.heightAnchor)
        ch.priority = .required - 1

        NSLayoutConstraint.activate([

            // prompt label and stepper at the top
            stepperStack.topAnchor.constraint(greaterThanOrEqualTo: g.topAnchor, constant: 8.0),
            stepperStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),

            // constrain outerStack
            //  square (1:1 ratio)
            outerStack.widthAnchor.constraint(equalTo: outerStack.heightAnchor),

            // don't make it larger than availble space
            outerStack.topAnchor.constraint(greaterThanOrEqualTo: stepperStack.bottomAnchor, constant: gridSpacing),
            outerStack.leadingAnchor.constraint(greaterThanOrEqualTo: g.leadingAnchor, constant: gridSpacing),
            outerStack.trailingAnchor.constraint(lessThanOrEqualTo: g.trailingAnchor, constant: -gridSpacing),
            outerStack.bottomAnchor.constraint(lessThanOrEqualTo: g.bottomAnchor, constant: -gridSpacing),

            // center horizontally and vertically
            outerStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            outerStack.centerYAnchor.constraint(equalTo: g.centerYAnchor),

            // active width/height constraints created above
            cw, ch,

        ])

        // spacing between buttons
        outerStack.spacing = gridSpacing

        // we'll start with an 11x11 grid
        stepper.value = 11
        makeGrid(11)
    }

    @objc func stepperChanged(_ stpr: UIStepper) {
        // stepper changed, so generate new grid
        makeGrid(Int(stpr.value))
    }

    func makeGrid(_ n: Int) {
        // grid must be between 2x2 and 20x20
        guard n < 21, n > 1 else {
            print("Invalid grid size: \(n)")
            return
        }

        // clear the existing buttons
        outerStack.arrangedSubviews.forEach {
            $0.removeFromSuperview()
        }

        // update the prompt label
        promptLabel.text = "Grid Size: \(n)"

        // for this example, we'll use a font size of 8 for a 20x20 grid
        //  adjusting it 1-pt larger for each smaller grid size
        let font: UIFont = .systemFont(ofSize: CGFloat(8 + (20 - n)), weight: .light)

        // generate grid of buttons
        for _ in 0..<n {
            // create a horizontal "row" stack view
            let rowStack = UIStackView()
            rowStack.spacing = gridSpacing
            rowStack.distribution = .fillEqually
            // add it to the outer stack view
            outerStack.addArrangedSubview(rowStack)
            // create buttons and add them to the row stack view
            for _ in 0..<n {
                let b = UIButton()
                b.backgroundColor = .systemBlue
                b.setTitleColor(.white, for: .normal)
                b.setTitleColor(.lightGray, for: .highlighted)
                b.setTitle("X", for: [])
                b.titleLabel?.font = font
                b.addTarget(self, action: #selector(gotTap(_:)), for: .touchUpInside)
                rowStack.addArrangedSubview(b)
            }
        }
    }

    @objc func gotTap(_ btn: UIButton) {
        // if we want a "row, column" reference to the tapped button
        if let rowStack = btn.superview as? UIStackView {
            if let colIdx = rowStack.arrangedSubviews.firstIndex(of: btn),
               let rowIdx = outerStack.arrangedSubviews.firstIndex(of: rowStack)
            {
                print("Tapped on row: \(rowIdx) column: \(colIdx)")
            }
        }

        // animate the tapped button
        UIView.animate(withDuration: 0.5, delay: 0, animations: {
            let rotate = CGAffineTransform(rotationAngle: .pi/2)
            let scale = CGAffineTransform(scaleX: 0.5, y: 0.5)
            btn.transform = rotate.concatenating(scale)
        }, completion: {_ in
            UIView.animate(withDuration: 0.5, animations: {
                btn.transform = CGAffineTransform.identity
            })
        })

    }

}

The output:

Tapping on any button will animate it (using the rotation/scale code from your post), and will print the "Row" and "Column" of the tapped button in the debug console.


text:
Q: How to set the mid element when doing a binary search? This may sound very naive question. Please excuse me for that. I was working on a problem that involved binary search. And the general way to do that I had learned is
 set low = 0, set high = array.Length - 1
 while(low < high)
   mid = (low+high)/2
   if (array[mid] == element) return mid
   if (array[mid] > element) set start = mid +1
   if array[mid] < element ) set high = mid

Please note the way i am setting the mid point. But some of example/solution that I saw sets the mid differently and I am not able to wrap my head around that. Please see the code snippet below. Any explanation what does setting the mid = l + (r-l)/2 mean would be greatly appreciated.
int BinarySearch(int A[], int l, int r, int key)
 {
   int m;

while( l <= r )
{
    m = l + (r-l)/2;

    if( A[m] == key ) // first comparison
        return m;

    if( A[m] < key ) // second comparison
        l = m + 1;
    else
        r = m - 1;
}

return -1;
}

A: The goal in both cases is to find the middle element.
(low + high) / 2: The sum of the left and right indices is divided by 2 to get the mid point. The problem with this is that the sum could overflow.
If the sum is an even number, we pick the lower one. Example - With left and right as [2, 5] - We pick mid as 3
l + (r - l) / 2:  The difference between the right and the left index is found and is divided by 2. It is then added to the left index to find the midpoint. It might be easier to visualize this with an example.
Example : [5, 11] -> (11 - 5) / 2 = 3 The middle in this interval is now 3 places or hops from the left index. So, add the left index to find the index of the mid element which is 5 + 3 = 8

A: This trick is done to avoid integer overflow problem .
(i)use unsinged right shift operator
int mid=(high+low)>>>1

or
(ii)  int mid=low +(high-low)/2
(low+high)/2 will overflow if the sum exceeds Integer.MAX_VALUE and you will get wrong results or an RuntimeException
You can read this article by Josh Bloch:
https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html

A: Middle is equal to the starting index of the left value plus the range between right and left divided by two.
Say our range is 5 to 10.
5 + (10-5)/2 == 5 + 5/2 == 5 + 2.5 == 7.5, the middle of our range


text:
Q: full screen layout in Scroll View I want to have 2 layouts inside ScrollView. First layout should be on the full screen and second layout below first one. When activity starts it is not possible see second layout. Second layout is possible see after scroll screen. Please take a look on my image for better understand.

A: Layout code: `
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout2"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="vertical" >

        <!-- this layout can be any height you want -->

    </LinearLayout>
</LinearLayout>

</ScrollView>`

Get the device screen height:

        Point size = new Point();
        getWindowManager().getDefaultDisplay().getSize(size);
        int screenHeight = size.y;
Find the LinearLayout:

        LinearLayout layout = (LinearLayout)findViewById(R.id.layout1);

Set the height of the layout based on the screen height you got earlier:

        LayoutParams params = layout.getLayoutParams();
        params.height = screenHeight - getStatusBarHeight();

Done. Be sure to call all of those methods in your onCreate method.
Hope this helps!


text:
Q: Uploading all folder content including subfolders using Spring MVC My problem is I want to select a folder using a web page and upload all the content of the folder to S3 using Spring.
I have tried the Spring MVC multipartresolver to upload files and it works fine. I have used JetS3t as well to upload folders and files to S3. But how can I select a folder using my web app and tell it to upload all files and subfolders to S3.
I am using Spring MVC 3.

A: Not using a "normal" HTML form-based file upload. And this is nothing to do with Spring or amazon, it's just a limitation in HTML. It's been suggested in the WHAT working group that this functionality be added, but that's a while ago and I don't think anything ever came of it.
The closes you have is the "multiple" file selector ("<input type="file" multiple>") selector that allows you to select multiple files. Together with the new FileReader API in HTML5 (example), this gets you somewhat closer to what you want. Unfortunately, "multiple" is not supported in IE.
For true directory-select and upload, you'll have to look to Java Applets or similar technologies. To be allowed to interact with the file system, an applet would have to be properly signed.


text:
Q: How to get work range selector with Highcharts with a function? I don't see the range selector, but I have written that in the code.
I have initialized the chart using variable, like:
var chart = Highcharts.chart('chartContainer', {
    xAxis: {
        type: 'datetime',
        tickPixelInterval: 150
    },
    yAxis: {
        title: {
            text: 'Érték'
        },
        plotLines: [{
            value: 0,
            width: 20,
            color: '#FFFFFF'
        }]
    },
    //animation: Highcharts.svg,
    boost: {
        seGPUTranslations: true
    },
    rangeSelector: {
        buttonTheme: { // styles for the buttons
            fill: 'none',
            stroke: 'none',
            'stroke-width': 0,
            r: 8,
            style: {
                color: '#039',
                fontWeight: 'bold'
            },
            allButtonsEnabled: true,
            states: {
                hover: {},
                select: {
                    fill: '#039',
                    style: {
                        color: 'white'
                    }
                }
                // disabled: { ... }
            }
        }
    },
    title: {
        text: 'Prociszenzor'
    },
    series: []
});

As you see it doesn't contain any series, I do add it from an another code:
chart.addSeries({
    type: 'line',
    name: dataaa.ertekek[i].neve + " " + dataaa.ertekek[i].mertek,
    data: [{
        y: dataaa.ertekek[i].ertek / 100,
        x: time
    }]
});

Dataaa is from a JSON file.
I do push this array to the main chart array, and I add points to this using addPoint function. I want to make a rangeselector, but I don't have idea how to do this.

A: As you have posted no example of what you are expecting I am assuming.
I made the following jsfiddle based on your code.
Note that I did the following changes from what I can see you have posted.
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/highcharts-more.js"></script>

I am note sure if you are using the highstock library, but if you want a range selctor, you should. See highcharts.com/docs/chart-concepts/range-selector
var chart = Highcharts.stockChart('container', {

I changed chart to be a stockChart.


text:
Q: Water well fluid dynamics In my home village everyone has their own water well at the foot of the mountain (limestone) . The wells are over 100 feet deep but they are not cemented or have the area between the hole and the casing (PVC) sealed with bentonite or anything like it. Even though the well is 100+ feet deep, inside the well deep the water comes up to within 15 feet of the surface. I suppose the stone is fractured even though during the drilling they have reached meters and meters of solid limestone.
I assume that deeper wells are safer to drink /use and cleaner since the bad things (remains of cow manure, plain old dirt or septic waste) rarely reach say 100+ feet. However, since the casing is not sealed and the water inside the well reaches within 15-20 feet of the surface, is it safe to assume that that the water sometimes is as clean as it would be in a 15-20 feet well? The casing on top is solid, only the last few meters at the bottom of the well have it with holes for the water to come in.
Now the question is this: Suppose "dirt" leaches down from the surface, moves through cracks in stone and at 10 feet deep touches the PVC casing and....does it go down 100+ feet or does pressure stop it from doing so. What happens what the submersible pump (100+ feet down) turns on, does the water mix up and down?
Thanks guys,

A: As posed there is no definite answer to your question.
It is certainly possible for water to enter the well at a depth of 100 feet, and have sufficient pressure that it eventually rises to within 15 feet of the top. That just means that the "water table" in that area is 15 feet below the surface.
If the sides of your well are reasonably well sealed so only water that had to seep through many feet of rock/soil enter the well, this will improve filtration - but it does not guarantee there is no mixing.
The physical principle here is that if you connect two vessels, and a steady state is allowed to be reached, then the water level in them will equalize:


text:
Q: Any way to have CPU temperature in the menu bar? I tried SMC fan control and Temperature Monitor but it does not update the temperature and I do not wish to change the fan speed.

A: I know that this is an old question, but by the end of 2020 there is a really nice open source utility — iGlance. Just tried it and it seems to work really fine. There are some minor issues with appearance under some circumstances, but otherwise it is very solid.

A: Temperature Monitor was last updated in 2009. So maybe it is not compatible with your OS.
I recently abandoned the fantastic MenuMeters (free) for iStat Menus 5, since the later provides even more info on practically all Mac sensors. Hardware Monitor and System Monitor are also capable of showing sensor information in the menu bar.

A: iStatMenu will give you what you need. And a whole lot more besides - all in a nice tightly integrated package that sits in your menu bar.

A: It is best achieved by installing CleanMyMac X and have it in the menu bar. It will update you with CPU temp., Memory, battery too


text:
Q: Unicode escape sequence I transfered data from a JSON Source to a MySQL database. Some data sets cotain the following string "\u0001". When I look in phpmyadmin this string gets translated in the corresponding unicode character. Is it possible to change the data so that it gets not translated or is there some option to turn off translation?

A: To avoid \u thingies in PHP:
json_encode($str, JSON_UNESCAPED_UNICODE)
                  ^^^^^^^^^^^^^^^^^^^^^^


text:
Q: Nodejs Express + Nuxt - Session Cookies I am using an Express App for the backend and VueJs with Nuxt (Server Side Rendering). My problem is that the cookies are not getting saved when the session is getting refreshed.
Server:
const express = require('express')
const cookieParser = require('cookie-parser')
const { loadNuxt } = require('nuxt')

const app = express()

app.use(cookieParser())

// Middleware
app.use(async (req, res, next) => {
  // ...

  if (sessionExpired && refreshTokenIsValid) {
    // Generate new session
    // ...
    res.cookie('sessionToken', token, { maxAge: 86400000, path: '/' })
    res.cookie('sessionId', id, { maxAge: 86400000, path: '/' })
    res.cookie('refreshToken', refreshToken, { maxAge: 86400000, path: '/' })

    return next()
  }
})

...

Login route
router.get('/login', async (req, res, next) => {
  // ...
  res.cookie('sessionToken', token, { maxAge: 86400000, path: '/' })
  res.cookie('sessionId', id, { maxAge: 86400000, path: '/' })
  res.cookie('refreshToken', refreshToken, { maxAge: 86400000, path: '/' })

  res.status(200).redirect('/')
})

Client:
async asyncData({ $axios }) {
   const data = await $axios.get('/something')
},
methods: {
  async someMethod() {
    let data = await this.$axios.$get('/something')
  }
}

A: The cookies are not getting saved when sending a request from asyncData().
I solved the problem by using an axios helper.
Solution source: proxy cookies
// plugins/ssr-cookie-proxy.js
import { parse as parseCookie } from 'cookie';

function parseSetCookies(cookies) {
  return cookies
    .map(cookie => cookie.split(';')[0])
    .reduce((obj, cookie) => ({
      ...obj,
      ...parseCookie(cookie),
    }), {});
}

function serializeCookies(cookies) {
  return Object
    .entries(cookies)
    .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)
    .join('; ');
}

function mergeSetCookies(oldCookies, newCookies) {
  const cookies = new Map();

  function add(setCookie) {
    const cookie = setCookie.split(';')[0];
    const name = Object.keys(parseCookie(cookie))[0];

    cookies.set(name, cookie);
  }

  oldCookies.forEach(add);
  newCookies.forEach(add);

  return [...cookies.values()];
}

export default function ({ $axios, res }) {
  $axios.onResponse((response) => {
    const setCookies = response.headers['set-cookie'];

    if (setCookies) {
      // Combine the cookies set on axios with the new cookies and serialize them
      const cookie = serializeCookies({
        ...parseCookie($axios.defaults.headers.common.cookie),
        ...parseSetCookies(setCookies),
      });

      $axios.defaults.headers.common.cookie = cookie; // eslint-disable-line no-param-reassign

      // If the res already has a Set-Cookie header it should be merged
      if (res.getHeader('Set-Cookie')) {
        const newCookies = mergeSetCookies(
          res.getHeader('Set-Cookie'),
          setCookies,
        );

        res.setHeader('Set-Cookie', newCookies);
      } else {
        res.setHeader('Set-Cookie', setCookies);
      }
    }
  });
}


text:
Q: get the id of the image from another html file using javascript I using iframe for displaying a image. Here is my code.
index.html

    <title>Center</title

test.html

    <title>Center</title>

I want the id of the image in index.html. Is it possible to get? Any one can help? Please!

A: document.getElementById('ifrm').contentWindow.document.getElementById('img1');

this should work
img = document.getElementById('ifrm').contentWindow.document.getElementsByTagName('img');

img[0].id to get the dinamically id

A: First get iframe.
var iframe = document.getElementById('ifrm');

Get access to elements of iframe.
var frameDoc = iframe.contentDocument || iframe.contentWindow.document;

Then, get id by tagname. In our case img.
var el = frameDoc.getElementsByTagName('img')[0].id;

Here is an example without iframe, to give you an idea how to get id of element after:
http://jsfiddle.net/nukec/eymq2/

A: Insted of id use name and try this..

A: You should use jQuery
var imageObj= $('#myiframe').contents().find('img');
var imgId=$(imageObj).attr("id");


text:
Q: How to Specify an Ajax update ID when using a Programatic Model in Primefaces Problem: Using a dynamic model to create a Primefaces component, such as a Menubar removes the ability to specify what components to be updated via Ajax within the JSF/XHTML page. It seems poor practice to hard code it in the Java back bean.
Example:
JSF:
<h:panelGroup id="updateDiv">
    <!-- components -->
</h:panelGroup>

<p:menubar model="#{backBean.model}" />

Back Bean:
@ManagedBean
@ViewScoped
public class BackBean {
    private MenuModel model;

    public BackBean() {
        model = new DefaultMenuModel();
        MenuItem item = new MenuItem();
        item.setUpdate("updateDiv");  // Here: hardcoded dependency on JSF page.
        item.setValue("Click Me.");
        model.addMenuItem(item);
    }

    public getModel() {
        return model;
    }
}

Specifying the updateDiv in the BackBean couples it to the JSF page. This seems bad? Is it? And if so, what alternatives are there? Maybe using <f:param/> or something similar might help.

A: Personally, I wouldn't have much trouble with that. Code on backing beans are usually coupled to the JSF pages anyway.
I'd put it in a constant with a meaningful name, though, something like:
private static final String CONTENT_PANEL_ID = "updateDiv";

There have been some discussion  here on SO already about how much coupling is to be allowed in the backing beans, specially regarding properties and methods.
I recommend reading through these, and making up your own mind:

*

*Proper use of backing beans

*What components are MVC in JSF MVC framework?

*Making Distinctions Between Different Kinds of JSF Managed-Beans

*JSF backing bean structure (best practices)

*Understanding JSF as a MVC framework


text:
Q: Parse.com Project Hosting I am new to Parse.com and trying to create a Project Directory using "Parse new". Whenever I do I get the following.
Anyone know what Errno 22 is and why it is thrown?
Thanks
Traceback (most recent call last):
  File "<string>", line 6, in <module>
  File ".\build\pyi.win32\parse\out00-PYZ.pyz\main", line 719, in main
  File ".\build\pyi.win32\parse\out00-PYZ.pyz\main", line 438, in handle_add
  File ".\build\pyi.win32\parse\out00-PYZ.pyz\config_handler", line 225, in add_
alias
IOError: [Errno 22] invalid mode ('w') or filename: 'C:\\Users\\mwalker\\Gerhart
TS\\config\\global.json'

A: Most likely the problem is in your escaping, if the compiler outputs c:\\ the string is s = "c:\\\\\\\\";
Other problem could be premission (try to run as admin), and please check that 'C:\Users\mwalker\Gerhart
TS\config\' exists.


text:
Q: Array null given in footer Page says: Warning: array_search() expects parameter 2 to be array, null given in xxxx/footer.php on line 44
<?php $i++;?>
<?php if(array_search('next_column',$bottom_menu[$i]->classes)!==false) break;>
<?php endwhile;?>

A: check if $bottom_menu[$i]->classes empty also
<?php $i++;?>
** <?php if(!empty($bottom_menu[$i]->classes)) { ?> **
<?php if(array_search('next_column',$bottom_menu[$i]->classes)!==false) break;>
** <?php } ?> **
<?php endwhile;?>


text:
Q: Is it possible to use another transition for showing a dialog than for hiding When using showGeneralDialog - is it possible to use a different transition and duration for displaying a dialog than for hiding the dialog again?
E.g. a Curves.elasticOut for showing and a shorter Curve.linear transition for hiding?

A: The showGeneralDialog method has the following signature:
Future<T?> showGeneralDialog<T extends Object?>(
{required BuildContext context,
required RoutePageBuilder pageBuilder,
bool barrierDismissible = false,
String? barrierLabel,
Color barrierColor = const Color(0x80000000),
Duration transitionDuration = const Duration(milliseconds: 200),
RouteTransitionsBuilder? transitionBuilder,
bool useRootNavigator = true,
RouteSettings? routeSettings,
Offset? anchorPoint}
)

Per the documentation, the RouteTransitionBuilder object :

"...is used to define how the route arrives on and leaves off the screen.
By default, the transition is a linear fade of the page's contents."

The RouteTransitionBuilder has the following signature:
RouteTransitionsBuilder = Widget Function(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child
)

The two Animation objects are used for:

animation: When the Navigator pushes a route on the top of its stack,
the new route's primary animation runs from 0.0 to 1.0. When the
Navigator pops the topmost route this animation runs from 1.0 to 0.0.
secondaryAnimation: When the Navigator pushes a new route on the top
of its stack, the old topmost route's secondaryAnimation runs from 0.0
to 1.0. When the Navigator pops the topmost route, the
secondaryAnimation for the route below it runs from 1.0 to 0.0.

If you want to have a different animation and duration, you can create your own RouteTransitionBuilder with its own animations and attach an animationController to it with a specific duration.


text:
Q: How to store multiple variables returned from a SELECT in arrays of their own - PDO I'm rewriting all my old mysql code as PDO code but I can't think of a way to store multiple variables returned from a SELECT in arrays of their own.
I can put ONE set of values in a new array as follows:
$stmt1 = $db->prepare("SELECT P_ID
    FROM personal
    WHERE personal.firstname=:firstname
    AND personal.lastname=:lastname");

// Bind
// Execute
// Fetch

// Store
    if ($row)
      {
            foreach ($row as $key)
            {
              $PIDs[] = $key;
            }
      }

But in this query I want to put firstnames and secondnames in different arrays:
$stmt2 = $db->prepare("SELECT FirstName, LastName
FROM personal");

In mysql I was doing:
while ($row = mysql_fetch_array($result))
     {
        $firstnames[] = $row[0];
        $lastnames[] = $row[1];
     }

Can someone please help? Every sample PDO SELECT I can find only handles one returned field.

A: Assuming you fetch data from your statement $stmt:
$stmt2 = $db->prepare("SELECT FirstName, LastName FROM personal");
$stmt2->execute();

while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
    $firstnames[] = $row['FirstName'];
    $lastnames[] = $row['LastName'];
}

A: You want to set the PDO fetch mode so you can reference the 2D array by name and then fetch all of the rows.
$stmt = $dbh->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();

More information can be found here.
And then you can use array_column, more information can be found here;
$firstNames = array_column($result, 'FirstName');
$lastNames = array_column($result, 'LastName');