jsReport not rendering custom font

Question: I've been rendering jsreport PDFs succesfully on my development machine. However, when running jsreport on the test server PhantomJS is falling back the use the default font. Any idea how to solve or troubleshoot?
I'm using Handlebars and PhantomJS. Dev machine spec: jsReport 1.0.7 on Node v4.4.5 on 64 bit Win10. Test server spec: jsReport 1.0.7 on Node vx.x.x on 64 bit Win2012 R2 Server
Steps to reproduce:
1)  Upload fonts to jsReport
fonts uploaded to jsreport
When selected, jsReport suggests using it as below:
{#image MavenPro-Black @encoding=base64}
2)  Add the "Shortcut" to the data file
{
    "assets": {
   "MavenPro-Black": "{#image MavenPro-Black}",
   "MavenPro-Bold": "{#image MavenPro-Bold}",
   "MavenPro-Medium": "{#image MavenPro-Medium}",
   "MavenPro-Regular": "{#image MavenPro-Regular}",
   "jquery": "{#image jquery}"
 },
  ……
}

3)  Use the asset in the Report

jsReport not rendering custom font


How do I see Alamofire Request?

Question: I am trying to use Alamofire for an Api that has a Json body and a header requirement that needs Basic Authentication. When I test the call in Postman it works fine, however with AlamoFire I am getting a server error.
I am trying to see what the call is that's going out from Alamofire - but I can't seem to see it:  (this is the code I am using)
edit:
Error is below

["errors": { }, "errorMessages": <__NSSingleObjectArrayI 0x6000000035c0>( Internal server error ) ]

Request is below
  Alamofire.request(endpoint, method: .post, parameters: paramsEncoded, encoding: JSONEncoding.default, headers: headers)
        .responseJSON(completionHandler: { (response) in
            print(response.request) // This returns just the url eg "http://api.com
            print(response.request?.httpBody) // This returns `Optional(85 bytes)`
        })

I assume the request is not being created properly, but would be useful to understand what I should be seeing.
Edit: this line helped from the other question :
NSLog("Request: \(request!.httpMethod!) - \(request!.url!.absoluteString)\n\(request!.httpBody.map { body in String(data: body, encoding: .utf8) ?? "" } ?? "")")
Thanks to the question I have linked to as a duplicate for the help.
Comment: Can you show me your error?
Comment: added the error, thanks
Comment: Have you try to print `response.result.value` ?
Comment: This other question helped me to see that Alamofire was changing the order of the json body. link: http://stackoverflow.com/questions/32595517/url-encode-alamofire-get-params-with-swiftyjson/32649785?noredirect=1#comment67440290_32649785 suggest we mark this as duplicate.
Comment: Done. - is that what you meant Ekta?
Comment: But it was none of the answers below.. it was on another question. Can you clarify?
Answer: Print the whole request like this :
let request = Alamofire.request(endpoint, method: .post, parameters: paramsEncoded, encoding: JSONEncoding.default, headers: headers)
    .responseJSON(completionHandler: { (response) in
        print(response.request)
        print(response.request?.httpBody)
    })

print("REQUEST = \(request)")

I'm not sure you can get any more info than that though.
Answer: You need to add headers with your request.
let urlString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]

Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: headers).responseJSON { response in
    print(response.result.value)
}

Comment: Hi - thanks - but I did add headers already if you look above - I have included the header details to help

How do I see Alamofire Request?


A question about Dirichlet Test for converge $- f(x)=\sin x/x^{\alpha}$

Question: I know how to solve and prove that
$$\int_{0}^{\infty} \frac{\sin(x)}{x^\alpha} \, dx$$ converge for $ 0 < \alpha < 2 $
 with regular tests and integration by parts.
But with the Dirichlet test, I just see that I have one function which is monotonic decreasing to $0$ for any given $\alpha$ and the integral on the $\sin(x)$ is bounded for $ [0,\infty]$ because so it should converge. so it should converge for any $\alpha$.
Clearly I don't understand the Dirichlet test, but I've read its definition many times and still I don't understand where I got it wrong.
Comment: Does the behaviour of $1/x^\alpha$ near 0 play well with Dirichlet?
Comment: Don't abuse the display style! Use them appropriately. Thanks to Nunoxic for his substantial edit and I have as well edited the post substantially. There is a gap: `because so`. I don't think they ever go together.
Comment: thanks. I just dont know how to add Latex in the same line, everytime i am inserting Latex code its just jumps to the next line without any \n newline character. and regarding 1/x^\alpha - isnt it monotonic decreasing for any given alpha? or that i am looking it wrong and because its not "proper" integrable in [0,infinity] i cant use it?
Answer: Dirichlet Test
Let $f$, $g :[a,\infty)\rightarrow\Bbb R $ be such that:
1) $f$ is decreasing and $f(x)\rightarrow0$ as $x\rightarrow\infty$.
2) $g$ is continuous and there is an $M$ such that $\Bigl|\int_a^x g(t)\,dt\Bigr|\le M$ for all $x>a$.
Then $\int_a^\infty f(t)g(t)\,dt$ converges.

Now, is $f(x)={1\over x^\alpha}$ defined on all of $[0,\infty)$? Could you even define an extension of $f$ to $[0,\infty)$ so that it remains monotone?
Comment: you' the man...thank you! that part seemed to have vanished from my notebook


DbContext is Disposed When Using Unity Dependency Injection on WebApi project

Question: I'm fairly new at using dependency injection and I think I must be overlooking something really simple.
I have a Web API project where I'm registering generic repositories. The repositories take a dbContext as a parameter in their constructor.
The behavior I find strange is that I can make one successfull call to the service but any subsequent calls tell me that the dbcontext has been disposed. I do have a using statement in there but that shouldn't be a problem since DI is supposed to be creating new instances of my dependencies for each web request(although I could be wrong).
Here is my generic repository:
 public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    internal DbContext _context;
    internal DbSet<T> _dbSet;
    private bool disposed;

    public GenericRepository(DbContext context)
    {
        _context = context;
        _dbSet = _context.Set<T>();
    }

    ///
    /// This constructor will set the database of the repository
    /// to the one indicated by the "database" parameter
    ///
    /// <param name="context"></param>
    /// <param name="database"></param>
    public GenericRepository(string database = null)
    {
        SetDatabase(database);
    }

    public void SetDatabase(string database)
    {
        var dbConnection = _context.Database.Connection;
        if (string.IsNullOrEmpty(database) || dbConnection.Database == database)
            return;

        if (dbConnection.State == ConnectionState.Closed)
            dbConnection.Open();

        _context.Database.Connection.ChangeDatabase(database);
    }

    public virtual IQueryable<T> Get()
    {
        return _dbSet;
    }

    public virtual T GetById(object id)
    {
        return _dbSet.Find(id);
    }

    public virtual void Insert(T entity)
    {
        _dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        T entityToDelete = _dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(T entityToDelete)
    {
        if (_context.Entry(entityToDelete).State == EntityState.Detached)
        {
            _dbSet.Attach(entityToDelete);
        }

        _dbSet.Remove(entityToDelete);
    }

    public virtual void Update(T entityToUpdate)
    {
        _dbSet.Attach(entityToUpdate);
        _context.Entry(entityToUpdate).State = EntityState.Modified;
    }

    public virtual void Save()
    {
        _context.SaveChanges();
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            //free managed objects here
            _context.Dispose();
        }

        //free any unmanaged objects here
        disposed = true;
    }

    ~GenericRepository()
    {
        Dispose(false);
    }
}

Here is my generic repository interface:
 public interface IGenericRepository<T> : IDisposable where T : class
{
    void SetDatabase(string database);
    IQueryable<T> Get();
    T GetById(object id);
    void Insert(T entity);
    void Delete(object id);
    void Delete(T entityToDelete);
    void Update(T entityToUpdate);
    void Save();
}

This is my WebApiConfig:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();

        container.RegisterType<IGenericRepository<Cat>, GenericRepository<Cat>>(new HierarchicalLifetimeManager(), new InjectionConstructor(new AnimalEntities()));
        container.RegisterType<IGenericRepository<Dog>, GenericRepository<Dog>>(new HierarchicalLifetimeManager(), new InjectionConstructor(new AnimalEntities()));

        config.DependencyResolver = new UnityResolver(container);

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

This is my DependencyResolver(which is pretty standard):
public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        this.container = container ?? throw new ArgumentNullException(nameof(container));
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        container.Dispose();
    }
}

And finally this is part of the controller that's giving me trouble:
public class AnimalController : ApiController
{
    private readonly IGenericRepository<Cat> _catRepo;
    private readonly IGenericRepository<Dog> _dogPackRepo;

    public AnimalController(IGenericRepository<Cat> catRepository,
        IGenericRepository<Dog> dogRepository)
    {
        _catRepo = catRepository;
        _dogRepo = dogRepository;
    }

    [HttpGet]
    public AnimalDetails GetAnimalDetails(int tagId)
    {
        var animalDetails = new animalDetails();

        try
        {
            var dbName = getAnimalName(tagId);

            if (dbName == null)
            {
                animalDetails.ErrorMessage = $"Could not find animal name for tag Id {tagId}";
                return animalDetails;
            }

        }
        catch (Exception ex)
        {
            //todo: add logging
            Console.WriteLine(ex.Message);
            animalDetails.ErrorMessage = ex.Message;
            return animalDetails;
        }

        return animalDetails;
    }

    private string getAnimalName(int tagId)
    {
        try
        {
            //todo: fix DI so dbcontext is created on each call to the controller
            using (_catRepo)
            {
                return _catRepo.Get().Where(s => s.TagId == tagId.ToString()).SingleOrDefault();
            }
        }
        catch (Exception e)
        {
            //todo: add logging
            Console.WriteLine(e);
            throw;
        }
    }
}

The using statement around the _catRepo object is not behaving as expected. After I make the first service call the _catRepo is disposed of. On a subsequent call I'm expecting to have a new _catRepo instantiated. However, this is not the case since the error I'm getting talks about the dbcontext being disposed.
I've tried changing the LifeTimeManager to some of the other ones available but that didn't help.
I also started going down a different route where the generic repository would take a second generic class and instantiate its own dbcontext from it. However, when I did that Unity couldn't find my controller's single-parameter constructor.
I guess what I really need, per the comments below, is a way to instantiate the DbContext on a per-request basis. I don't know how to go about doing that though.
Any hints would be greatly appreciated.
Comment: The DI container is supposed to dispose of resources for you.  You shouldn't have to do it manually.
Comment: When you do `using (_catRepo)`, at the end of the call the repo is disposed, which disposes the db context. Don't put a `using` block there. Your DI container should be able to configure db contexts to be per-request (not sure how this works in Unity), but you don't need to call `repo.Dispose()` if this is set up correctly
Comment: You are creating your context only when the application starts, so if the first request happens and you dispose the db, the next request not has more a db to use. Try change it to create and dispose db per request.
Comment: Also, I went down this rabbit hole before: I would not recommend generic repositories. Use specific repositories. you'll thank me later when you need domain-specific actions/transactions etc that are not CRUD
Comment: Isn't a subsequent call to the web service supposed to instantiate a new _catRepo? I guess I must be missing something in the setup...
Comment: You should read [this](https://stackoverflow.com/questions/17943870/decorators-and-idisposable) and [this](https://stackoverflow.com/questions/30283564/dependency-injection-and-idisposable).
Comment: Not sure why IRepository implements IDisposable. The container will dispose itself due to HierarchicalLifetimeManager.  Remove the disposable and your issue should go away. My reference is the current API I have designed that has 3M hits a month.
Answer: Let's take a look at your registration:
container.RegisterType<IGenericRepository<Cat>, GenericRepository<Cat>>(
    new HierarchicalLifetimeManager(),
    new InjectionConstructor(new AnimalEntities()));

container.RegisterType<IGenericRepository<Dog>, GenericRepository<Dog>>(
    new HierarchicalLifetimeManager(),
    new InjectionConstructor(new AnimalEntities()));

You are creating two instances of AnimalEntities at startup, but those instances are reused for the duration of the whole application. This is a terrible idea. You probably intend to have one DbContext per request, but the instance wrapped by the InjectionConstructor is a constant.
You should change your configuration to the following:
container.RegisterType<IGenericRepository<Cat>, GenericRepository<Cat>>(
    new HierarchicalLifetimeManager());

container.RegisterType<IGenericRepository<Dog>, GenericRepository<Dog>>(
    new HierarchicalLifetimeManager());

// Separate 'scoped' registration for AnimalEntities.
container.Register<AnimalEntities>(
    new HierarchicalLifetimeManager()
    new InjectionFactory(c => new AnimalEntities()));

This is much simpler and now the AnimalEntities is registered as 'scoped' as well.
What's nice about this is that Unity will now dispose your AnimalEntities once the scope (the web request) ends. This prevents you from having to implement IDisposable on consumers of AnimalEntities, as explained here and here.
Comment: thanks for giving such a detailed answer. You are correct in that my intention was to have one DbContext per request. Unfortunately, your suggestion is not working for me. It looks like my controller's constructor cannot be found since I'm getting this error msg: "An error occurred when trying to create a controller of type 'AnimalController'. Make sure that the controller has a parameterless public constructor.". Was I supposed to change my controller's signature?
Comment: parameterless ctor is because your registration is not correctly bound. you should be able to dig into the registrations container  to see the error messages within the Unity container. I would recommend putting this new registration code into a TEST before attempting to resolve in a multi-parameter controller..
Answer: I figured out what was going on. As several people have indicated, my repository doesn't need to inherit from IDisposable since the Unity container will dispose of these repositories when the time is right. However, that wasn't the root of my problems.
The main challenge to overcome was getting one dbContext per request. My IGenericRepository interface has stayed the same but my GenericRepository implemenation now looks like this:
public class GenericRepository<TDbSet, TDbContext> :
    IGenericRepository<TDbSet> where TDbSet : class
    where TDbContext : DbContext, new()
{
    internal DbContext _context;
    internal DbSet<TDbSet> _dbSet;

    public GenericRepository(DbContext context)
    {
        _context = context;
        _dbSet = _context.Set<TDbSet>();
    }

    public GenericRepository() : this(new TDbContext())
    {
    }

    ///
    /// This constructor will set the database of the repository
    /// to the one indicated by the "database" parameter
    ///
    /// <param name="context"></param>
    /// <param name="database"></param>
    public GenericRepository(string database = null)
    {
        SetDatabase(database);
    }

    public void SetDatabase(string database)
    {
        var dbConnection = _context.Database.Connection;
        if (string.IsNullOrEmpty(database) || dbConnection.Database == database)
            return;

        if (dbConnection.State == ConnectionState.Closed)
            dbConnection.Open();

        _context.Database.Connection.ChangeDatabase(database);
    }

    public virtual IQueryable<TDbSet> Get()
    {
        return _dbSet;
    }

    public virtual TDbSet GetById(object id)
    {
        return _dbSet.Find(id);
    }

    public virtual void Insert(TDbSet entity)
    {
        _dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TDbSet entityToDelete = _dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TDbSet entityToDelete)
    {
        if (_context.Entry(entityToDelete).State == EntityState.Detached)
        {
            _dbSet.Attach(entityToDelete);
        }

        _dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TDbSet entityToUpdate)
    {
        _dbSet.Attach(entityToUpdate);
        _context.Entry(entityToUpdate).State = EntityState.Modified;
    }

    public virtual void Save()
    {
        _context.SaveChanges();
    }
}

The default constructor is now responsible for creating a new DbContext of the type specified when the class is instantiated(I actually have more than one type of DbContext in my application). This allows for a new DbContext to be created for every web request. I tested this by using the using statement in my original repository implementation. I was able to verify that I no longer get the exception about the DbContext being disposed on subsequent requests.
My WebApiConfig now looks like this:
 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();

        container.RegisterType<IGenericRepository<Cat>, GenericRepository<Cat, AnimalEntities>>(new HierarchicalLifetimeManager(), new InjectionConstructor());
        container.RegisterType<IGenericRepository<Dog>, GenericRepository<Dog, AnimalEntities>>(new HierarchicalLifetimeManager(), new InjectionConstructor());

        config.DependencyResolver = new UnityResolver(container);

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

One thing that was causing me a lot of pain here is that I didn't realize I still had to call the InjectionConstructor in order to use the parameterless constructor of the repository class. Not including the InjectionConstructor was causing me to get the error about my controller's constructor not being found.
Once I got over that hurdle I was able to change my controller what I have below. The main difference here is that I'm no longer using using statments:
public class IntegrationController : ApiController
{
    private readonly IGenericRepository<Cat> _catRepo;
    private readonly IGenericRepository<Dog> _dogPackRepo;

    public IntegrationController(IGenericRepository<Cat> catRepository,
        IGenericRepository<Dog> dogRepository)
    {
        _catRepo = catRepository;
        _dogRepo = dogRepository;
    }

[HttpGet]
public AnimalDetails GetAnimalDetails(int tagId)
{
    var animalDetails = new animalDetails();

    try
    {
        var dbName = getAnimalName(tagId);

        if (dbName == null)
        {
            animalDetails.ErrorMessage = $"Could not find animal name for tag Id {tagId}";
            return animalDetails;
        }
    }
    catch (Exception ex)
    {
        //todo: add logging
        Console.WriteLine(ex.Message);
        animalDetails.ErrorMessage = ex.Message;
        return animalDetails;
    }

    return animalDetails;
}

private string getAnimalName(int tagId)
{
    try
    {
         return _catRepo.Get().Where(s => s.TagId ==
           tagId.ToString()).SingleOrDefault();
    }
    catch (Exception e)
    {
        //todo: add logging
        Console.WriteLine(e);
        throw;
    }
}
}

Answer: The way I solved my problem is a little different than what these answers suggest.
I'm in an MVC app but the logic should be similar for this.
As others have stated, creating an instance of an object inside and InjectionContructor essentially creates a static copy of that instance that is used for all future instances of the resolving type.  To fix this, I simply register the context as a type and then let Unity resolve the context when it resolves the service.  By default, it creates a new instance each time:
UnityConfig:
public static void RegisterComponents()
{
    var container = new UnityContainer();

    container.RegisterType<PrimaryContext>(new InjectionConstructor());
    container.RegisterType<LocationService>();

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

PrimaryContext:
//Allows for a default value if none is passed
public PrimaryContext() : base(Settings.Default.db) { }
public PrimaryContext(string connection) : base(connection)
{
}

LocationService:
PrimaryContext _context;
public LocationService(PrimaryContext context)
{
    _context = context;
}

I can't give a ton of specifics about exactly how it works, but this appears to have fixed the problem I was having (I was getting the same error message) and it's super simple.


Scrapy - Comparing Data

Question: I am very new to scrapy and am at a point in my project where I am unsure how to proceed. My idea is that I want to scrape the first 2 pages of hackernews and print out all articles / titles with points above 300. Based on my limited knowledge the following code is the best way I could figure out how to get the information I want. My end goal is I need to compare the id with the post id to match them, add the points to the corresponding matches and then filter out points less than 300. I am not sure how I can compare the dictionary values that I have been able to scrape. The code is as follows:
import scrapy

class ArticlesSpider(scrapy.Spider):
    name = 'articles'
    start_urls = [
        'https://news.ycombinator.com',
        # 'https://news.ycombinator.com/news?p=2'
    ]

    def parse(self, response):
        link = response.css('tr.athing')
        score = response.css('td.subtext')
        for website in link:
            yield {
                'title': website.css('tr.athing td.title a.storylink::text').get(),
                'link':  website.css('tr.athing td.title a::attr(href)').get(),
                'id': website.css('tr::attr(id)').get(),
            }
        for points in score:
            yield {
                'post_id': points.css('span::attr(id)').get(),
                'points': points.css('span.score::text').get()
            }

Is there a better way to achieve what I want to do?
Answer: The posts and scores lists have same length and order.
In each iteration, check the score point of the corresponding post is >= 300.
import scrapy

class ArticlesSpider(scrapy.Spider):
    name = 'articles'
    start_urls = [
        'https://news.ycombinator.com',
        #'https://news.ycombinator.com/news?p=2'
    ]

    def parse(self, response):
        posts = response.css('tr.athing')
        scores = response.css('td.subtext')

        for i in range(len(posts)):
            # get the post
            post = posts[i]

            # get the score point of the corresponding post
            score = scores[i]
            score_point = score.css('span.score::text').get()
            # handle some post has no score point
            score_point = int(score_point.split(' ')[0]) if score_point else 0

            if score_point >= 300:
                yield {
                    'title': post.css('tr.athing td.title a.storylink::text').get(),
                    'link':  post.css('tr.athing td.title a::attr(href)').get(),
                    'id': post.css('tr::attr(id)').get(),
                    'points': score_point
                }

Posts with score >= 300 are printed:
{'title': 'One man's fight for the right to repair broken MacBooks', 'link': 'https://columbianewsse
rvice.com/2021/05/21/one-mans-fight-for-the-right-to-repair-broken-macbooks/', 'id': '27254719', 'po
ints': 1138}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'Why I prefer making useless stuff', 'link': 'https://web.eecs.utk.edu/~azh/blog/makinguse
lessstuff.html', 'id': '27256867', 'points': 604}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'Why Decentralised Applications Don't Work', 'link': 'https://ingrids.space/posts/why-dist
ributed-systems-dont-work/', 'id': '27259321', 'points': 320}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'Freesound just reached 500K Creative Commons sounds', 'link': 'https://blog.freesound.org
/?p=1340', 'id': '27232297', 'points': 696}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'The Limits to Blockchain Scalability', 'link': 'https://vitalik.ca/general/2021/05/23/sca
ling.html', 'id': '27257641', 'points': 378}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'Teardown of a PC Power Supply', 'link': 'https://www.righto.com/2021/05/teardown-of-pc-po
wer-supply.html', 'id': '27256515', 'points': 351}
2021-05-24 18:14:28 [scrapy.core.scraper] DEBUG: Scraped from <200 https://news.ycombinator.com>
{'title': 'Dorodango: the Japanese art of making shiny mud balls (2019)', 'link': 'https://www.laure
nceking.com/blog/2019/09/26/dorodango-blog/', 'id': '27255755', 'points': 313}

Scrapy - Comparing Data


In JavaScript, is there a way to retrieve the object a function was bound to?

Question: Specifically, I'm interested in how to get the code below to work, logging as per the comments.
function someWeirdness(func) {
    var funcThis = undefined; // Instead of undefined, access to what,
                             // if anything, func is bound to
                             // (func.this doesn't work, but that would be
                             // it if it did).
    console.log(funcThis);
}
function greet(greeting) {
    console.log([greeting || "Hello", this.name].join(" "));
}
var obj = {
    name: "object"
};
greetObj = greet.bind(obj);
someWeirdness(greetObj); // logs obj

The application would be something more along the lines of:
function compositionalMagic(func, params) {
    params = Array.isArray(params) ?
                params : Array.prototype.slice.call(arguments, 1);
    // Additional processing and hooplah
    func.apply(func.this, params);
}

Comment: Duplicate of http://stackoverflow.com/questions/14307264/what-object-javascript-function-is-bound-to-what-is-its-this
Comment: Do you want to know what object a function is bound to, or do you want to log "obj"? because there is no relationship between the two.
Comment: [You're using `bind` wrong](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
Comment: As I explained in my previous content, if the `this` of the function you receive is bound, and you use `apply()` to call that function, the `this` value you provide will be ignored and the bound one will be used. So if you want to honor the bound value, then you have no issue. ...[Here's a demo](http://jsfiddle.net/0rytr25q/1/)
Comment: Yeah... sorry guys... typo! (Or rather brain fart stringifying the param for bind).
Comment: There's a few ways you could do this, but not as you have written here. Can you give context for practical application of what you're trying to accomplish?
Comment: Ah, now I see what you're hoping for. sorry, it's not possible. The bound value of `this` is only available within the scope of each function. You'd have to expose it from within `greet`.
Comment: maybe modify your greet to keep trace of bind
Comment: @Will is correct. My search-fu wasn't good enough to let me find it.
Comment: `func.apply(func.this, params);` I don't understand why you'd need anything special there. If `this` is bound, then you can't change it anyway. Just do `func.apply(null, params);`
Comment: I'm actually just interested in being able to correctly (i.e., with the right ```this``` value) apply the function to an arbitrary list of parameters.
Comment: @jameslafferty: But what is the right value? If you're saying that you want to leave a bound `this` as is, but otherwise set your own value, then you're good to go. Just do `func.apply(my_this, params)`, and `my_this` will be ignored if `this` is already bound.
Comment: @squint But... let's say I don't know what (or even whether) ```func``` already is bound to something. I'm looking to provide an API where I accept a function, bound or not, and a list or array of parameters, and then return a new function that invokes the original function with the expected context and parameters later.
Comment: ...though you're using terms like *"right"* and *"expected"* without defining them. I assume you mean you do want to honor the bound value instead of replacing it.
Answer: this is only available inside of a given function scope — unless you intentionally leak the reference.
function foo( arg ) {
  arg.this = this;
}

var obj = { foo: 'bar' };
var obj2 = {};

foo.call( obj, obj2 );

console.log( obj2.this ); // logs { foo: 'bar' }

You could monkeypatch Function.prototype.bind to do something like the above every time you invoke bind, but probably not ideal.


Aplicativo é fechado depois de um tempo, mesmo com serviço

Question: Olá tenho um serviço que roda em background, esse serviço não deveria ser finalizado pelo sistema do Android, porém acontece isso depois de um tempo de execução.
public class VerificaCorridas extends Service {

private Timer timerAskServer;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    verifyServer();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    super.onDestroy();
    timerAskServer.cancel();
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void verifyServer() {
    timerAskServer = new Timer();
    TimerTask askServer = new TimerTask() {
        public void run() {
            // Aqui é feito uma consulta ao servidor para ver se tem algo novo
        };

    };
    timerAskServer.schedule(askServer, 0, 10000); //repete a cada 10 Seg
}

}
Comment: Sem conhecer o código do serviço fica difícil.
Comment: Irei tentar reduzir o código para postar, mas pode acontecer isso? Um serviço ele ser finalizado pelo sistema?
Comment: Pode, depende da forma como ele é declarado.
Comment: Pronto postei o código
Comment: Para esse caso especifico e se não quiser usar o *Google cloud messaging (GCM)* use um *AlarmManager* com um *BroadcastReceiver*. Veja [aqui](http://pt.stackoverflow.com/a/26275/2541) um exemplo.
Comment: @MateusCarvalho este APP que você está elaborando é para Entregas Rápidas?
Comment: Não @AndréBaill
Comment: @ramaral eu uso o parse.com, nele já está incluído o serviço do GCM, porém há um delay de tempo ás vezes na entrega da mensagem... Isso não pode acontecer, sabe dizer se é normal?
Comment: Não sei, nunca utilizei o *Parse*.
Answer: Falando muito genericamente, qualquer serviço do Android pode ser interrompido a qualquer momento, em particular se o celular tiver pouca memória. É assim que a plataforma funciona.
Uma alternativa para garantir que ele volte depois de uma interrupção, é reiniciá-lo periodicamente com um Alarm.
Outra alternativa, bastante intrusiva, é iniciar o serviço com startForeground. Nesta modalidade uma notificação fica permanentemente na área de notificações (ela não pode ser "dismissed" pelo usuário) o que "segura" o serviço na memória.
Serviços que gastem recursos e rodam o tempo todo devem usar esta solução, segundo as UI Guidelines do Android. Por exemplo: um aplicativo de música, que está usando áudio o tempo todo e não deveria ser interrompido.
Dito isto, um serviço com notificação permanente AINDA pode ser parado em caso de absoluta falta de memória. Então o Alarm ainda é necessário se você quer garantir que ele vai rodar 24x7.
Answer: Como desenvolvedor Android é importante ter em mente que você não possui controle sobre o ciclo de vida de uma aplicação. A qualquer momento o seu dispositivo pode ficar sem recursos (acabar a memória, por exemplo) e o sistema irá finalizar o aplicativo para dar manter o OS rodando corretamente.
Esse comportamento é valido para qualquer parte de sua aplicação. Dessa forma, você precisa utilizar um AlarmManager (http://developer.android.com/reference/android/app/AlarmManager.html) para disparar periodicamente o seu serviço e fazer a verificação. Não é legal manter um serviço rodando eternamente, para não ser intrusivo e consumir recursos desnecessário do usuário.


How to use Route53 Domain commandlets in AWS Lambda?

Question: I get an error when running route 53 domain commandlets in lambda, they run fine locally and I can successfully run other commandlets in lambda, for example, s3.
I already gave the IAM user full administrative permissions, tested locally and with other commandlets, and even tried running the command with an alias, and googled the error I get.
This is the basic script:
<code>#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.563.1'}
# Uncomment to send the input event to CloudWatch Logs
Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)
$r53domains = Get-R53DDomainList -AccessKey "xxxx" -SecretKey "xxx"
foreach ($domain in $r53domains){write-host "Domainlist = $($domain.DomainName)"}
</code>
I would expect output like:
Domainlist = xxxx.com
Domainlist = xxxxxx.nl
However, in Lambda I get the following error:
<code>[Error] - No such device or address
No such device or address: InvalidOperationException
   at Amazon.Lambda.PowerShellHost.PowerShellFunctionHost.ExecuteFunction(Stream inputStream, ILambdaContext context)
   at lambda_method(Closure , Stream , Stream , LambdaContextInternal )

   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)
   at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.PowerShell.Cmdlets.R53D.GetR53DDomainListCmdlet.CallAWSServiceOperation(IAmazonRoute53Domains client, ListDomainsRequest request)
   at Amazon.PowerShell.Cmdlets.R53D.GetR53DDomainListCmdlet.Execute(ExecutorContext context)
No such device or address: SocketException
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
</code>
Answer: I finally found the answer.
My Lambda is running in region eu-west-1 (Ireland) but route 53 should be regionless, as can also be found here: https://aws.amazon.com/blogs/developer/aws-regions-and-windows-powershell/
However, when I ran the commands locally using the -Verbose switch it showed that the command was run in region us-east-1. After adding the -Region us-east-1 to the powershell command in Lambda it ran fine.


Differentiable $f\colon I\to\mathbb{C}$ with bounded derivative is Lipschitz continuous

Question: Prove that a differentiable function $f\colon I\to\mathbb{C}$ on an interval $I$ with bounded derivative is Lipschitz continuous, i.e. If $\lvert f'\rvert\leq L $ for some $L\in\mathbb{R}$, then for any $x_1,x_2\in I$ we have
$$
\lvert f(x_1)-f(x_2)\rvert\leqslant L\lvert x_1-x_2\rvert.
$$
Despite two little things, I think the proof should work as follows:
I think, we can choose some $c\in\mathbb{C}$ with $\lvert c\rvert =1$ such that
$$
\lvert f(x_2)-f(x_1)\rvert = c\cdot (f(x_2)-f(x_1))~~(*)
$$
since for
$$
\frac{f(x_2)-f(x_1)}{\lvert f(x_2)-f(x_1)\rvert}=:v
$$
we have $\lvert v\rvert =1$ and then we can define $c:=v^{-1}$.
Next, in order to have equation $(*)$, the LHS has to be the real part of the RHS, i.e.
$$
\lvert f(x_2)-f(x_1)\rvert =\Re(c\cdot (f(x_2)-f(x_1)))=\varphi(x_2)-\varphi(x_1),
$$
where
$$
\varphi:=\Re(cf).
$$
Now, since $f$ is differentiable on $I$, it is, in particular, continuous on $[x_1,x_2]$, hence $\varphi$ is also continuous on $[x_1,x_2]$.
I am not sure about the following question:

Do we also have that $\varphi$ is differentiable on $(x_1,x_2)$? (Q)

Assuming that we can answer question (Q) with YES, we could apply the mean value Theorem on $\varphi$, telling us that
$$
\varphi(x_2)-\varphi(x_1)=(x_2-x_1)\varphi'(\xi)
$$
for some $\xi\in (x_1,x_2)$.
By assumption, $\varphi'(\xi)=\Re(cf'(\xi))\leq\lvert cf'(\xi)\rvert\leq L$ and hence
$$
\lvert f(x_2)-f(x_1)\rvert = \varphi(x_2)-\varphi(x_1)=(x_2-x_1)\varphi'(\xi)\leqslant L\lvert x_2-x_1\rvert.
$$

I am also not completely sure if
    $$
\varphi' = \Re(cf')
$$
    is correct.

Despite the two things in the two yellow boxes, I am pretty sure the proof should work. It would be nice if you could give me some hints.
Comment: You need to complex conjugate $c$. $\varphi$ is in general not differentiable if $0\in f((x_1, x_2))$. You could consider the squared absolute value.
Comment: You mean $\lvert f(x_2)-f(x_1)\rvert = \bar{v} (f(x_2)-f(x_1))$?
Comment: yes, or to circumvent the differentiability issue just set $c = \overline{f(x_2) - f(x_1)}$.
Comment: Here is a related answer that does something similar http://math.stackexchange.com/a/2078872/27978. Essentially the idea is that if $\operatorname{re} (cz) \le K |c|$ for all $c$, then $|z| \le K$. In the above case, $K=L|x_1-x_2|$, $|c|=1$ and $z=f(x_1)-f(x_2)$. The answer to both of your yellow boxes is yes.
Comment: @user251257 Sorry, but did not get why $\varphi$ isn't differentiable if $0\in f((x_1,x_2))$. Could you explain that, please?
Comment: @copper.hat May you give me explanations why both yellow box questions can be answered yes? Unfortunately, I do not see that.
Comment: @Rhjg: I added an answer below.
Answer: Since $\operatorname{re}$ is continuous we have
$\lim_{h \to 0} \operatorname{re} {cf(z+h)-cf(x) \over h} = \lim_{h \to 0}  {\operatorname{re}(cf(z+h))-\operatorname{re}(cf(x)) \over h} =  \operatorname{re} (cf'(x))$. That is, if
$\phi(x) = \operatorname{re}(cf(x))$, then $\phi'(x) = \operatorname{re} (cf'(x))$.
Comment: Why can we write the Re in front of the whole fraction, i.e. do not see the first equation.
Comment: If $b$ is real, then $\operatorname{re} ({a \over b}) = {\operatorname{re} a \over b}$.
Comment: Ah, of course!! h is real here... i thought it is complex but we are dealing with an interval.


iOS Unable to use Books API on google

Question: I am scanning ISBN code and searching the book on the basis of that code on google in my iOS app. I created the app on google.I have keys for browser apps and I also created keys for iOS app.
Now here is the API I am using:-
<code>https://www.googleapis.com/books/v1/volumes?q=isbn=9783161484100&key={API Key}
</code>
When I am passing browser app key its giving fine results in my iOS app also.
But when I am passing iOS API Key , then its giving response like this:-
<code>{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured"
   }
  ],
  "code": 403,
  "message": "Access Not Configured"
 }
}
</code>
I knows that there are 1,000 request limit in a day. But I did only 18 request till now. Then why this response is coming from iOS API Key. Is there some other way to implement book search functionality in iOS.
Comment: http://stackoverflow.com/questions/15703916/getting-start-with-aws-ios-sdk-to-search-books-with-their-isbn-from-iphone this link may helps you out. check it
Answer: Is your bundle identifier in google api console and bundle id in Xcode project are same?
Answer: There have been some issues w/ Google's API and Bundle IDs in their other apps.
As such - (in the Youtube API as well), Google suggested creating an API Key for "any app".
To do this -
In the Google Developer Console under your project's API & Auth:
Create New Key -> iOS Key, just click create with the bundle ID field left empty.

iOS Unable to use Books API on google


How to determine if a Lua error has been thrown?

Question: I've embedded a Lua interpreter into my C program, and I've got a simple question that I can't seem to find a clear answer to.
Suppose I have a C function that I expose to Lua as follows:
static int calculate_value(lua_State *L)
{
    double x = luaL_checknumber(L, 1);
    return 0;
}

How can I determine (in C, after this function was called) that Lua threw an error when calling luaL_checknumber? Is there an error message just sitting on the top of the stack? Is there some other indicator that an error has been thrown?
Answer: In general, you don't. Lua functions that throw errors use setjmp/longjmp (or exceptions if compiled as C++) to return control to the calling Lua runtime. The error will be presented to the Lua function that called your calculate_value function.
If you want to handle parameter errors differently, you cannot use Lua's luaL_check* functions.
Answer: If that function is called via Lua, you can use pall. Or use lua_pcall before running the Lua script that called that function.


Is this $ \lim_{n\to \infty} [(n+1) f(n+1) - nf(n) ]$ reimann summable? Here, $f(n) = e^{{1 \over n} (\sum_{r=1}^{n}\ln({r\over n}))}$.

Question: So while trying to solve a limit problem I ran into this expression  $$  \lim_{n\to \infty} [(n+1) e^{{1 \over n+1} (\sum_{r=1}^{n+1}\ln({r\over n+1}))} - (n) e^{{1 \over n} (\sum_{r=1}^{n}\ln({r\over n}))}  ].$$
What I want to know is that if this is reimann summable or solvable in any way?
It would help if you could justify your answer rigorously.
Answer: Let's observe that $$f(n) \to\exp\left(\int_{0}^{1}\log x\, dx\right) =\frac{1}{e}$$ and expression under limit in question can be written as $$f(n+1)+n\{f(n+1)-f(n)\}$$ whose limit is same as that of $$\frac{1}{e}+nf(n)\frac{x_n-1}{\log x_n} \cdot\log x_n\tag{1}$$ where $$x_n=\frac{f(n+1)}{f(n)}\to 1$$ Thus the desired limit crucially depends on the limit of $$n\{\log f(n+1)-\log f(n)\} \tag{2}$$ and one can prove that the above tends to $0$ so that the desired limit is $1/e$.
We can write $(2)$ as $$\left(1-\frac{1}{n+1}\right)\sum_{k=1}^{n+1}\log\frac{k}{n+1}-\sum_{k=1}^{n}\log\frac{k}{n}$$ or $$\log\frac{(n+1)!}{(n+1)^{n+1}}-\log\frac{n!}{n^n}-\frac{1}{n+1}\sum_{k=1}^{n+1}\log\frac{k}{n+1}$$ which equals $$n\log\frac{n}{n+1}-\log f(n+1)$$ The above clearly tends to $-1-(-1)=0$ and our job is done.

On the other hand if we look closely at your $f(n) $ we see that $$nf(n) =\sqrt[n] {n!} $$ and thus your question is essentially the same as this one. Why do ask the same question twice in two seemingly different forms? At the same time I don't think my answer is fundamentally different from the answer given there by user medicu.
Comment: I asked the question there but I could not get answers that would either build up on my approach or would prove it wrong. So I asked a different question on my approach. Is this against site rules?
Comment: @HrishabhNayal: no, it's not against the rules, but I don't see anything extra gained here. Also I am not annoyed, just wanted to know the reason you asked. You should put a link of the older question in your current question.
Answer: Considering
$$a_p=p\, e^{{1 \over p} \sum_{r=1}^{p}\log\left({r\over p}\right)}$$ we have, using Pochhammer symbols
$$\sum_{r=1}^{p}\log\left({r\over p}\right)=\log \left(\left(\frac{1}{p}\right)^p (1)_p\right)$$ which makes
$$a_p=\left((1)_p\right){}^{\frac{1}{p}}\implies \log(a_p)={\frac{1}{p}}\log\left((1)_p\right)$$ Using Stirling approximations for large $p$
$$\log\left((1)_p\right)=p (\log (p)-1)+\frac{1}{2} \log (2 \pi  p)+\frac{1}{12
   p}+O\left(\frac{1}{p^3}\right)$$
$$\log(a_p)=\log (p)-1+\frac{\log (2 \pi  p)}{2 p}+\frac{1}{12
   p^2}+O\left(\frac{1}{p^4}\right)$$
$$a_p=e^{\log(a_p)}=\frac{p}{e}+\frac{\log (2 \pi  p)}{2 e}+\frac{3 \log ^2(2 \pi  p)+2}{24 e   p}+O\left(\frac{1}{p^2}\right)$$ Apply it twice and continue with Taylor expansions
$$a_{n+1}-a_n=\frac{1}{e}+\frac{1}{2 e n}+O\left(\frac{1}{n^2}\right)$$
You could do the same with factorials since
$$\sum_{r=1}^{p}\log\left({r\over p}\right)=\sum_{r=1}^{p}\log(r)-\sum_{r=1}^{p}\log(p)=\log(p!)-p\log(p)$$
Comment: Is it formally wrong if I do something like $(n+1)(e^{-1})-(n)(e^{-1})$ (by evaluating reimann sum in exponent) then cancel out $n$ and give answer as $e^{-1}$. It matches with the more rigorously derived result.
Comment: Sorry, if I am being silly.
Comment: @HrishabhNayal: you can't replace an expression like $f(n) $ by its limit $1/e$ while evaluating the limit of a bigger expression which contains $f(n) $.
Comment: @HrishabhNayal: see this answer https://math.stackexchange.com/a/1783818/72031 for details.


Método get do http sendo invocado automaticamente

Question: Bom dia pessoal, estou implementando o método get um servlet aqui com uma lógica muito simples.
Caso o usuário passe uma url no padrão: ".../entidades/id", deverá ser aberto o formulário de edição já com a entidade correspondente à id digitada após a barra. Porém se o padrão da url for: ".../entidades" será carregada a lista de todas as entidades e aberta a página de listagem de entidades.
Já está tudo funcionando, porém com um problema. Após a execução da última linha está voltado para o início do método get, como se algo estivesse reinvocando o método get, então fica em loop infinito.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String requestUri = req.getRequestURI();
    Long id = RegexUtil.matchId(requestUri);

    if (id != null) {
        // Informou um id
        Entidade entidade = entidadeService.getEntidadeById(id);

        if (entidade != null) {

            req.setAttribute("objEntidade", entidade);
            req.getRequestDispatcher("paginas/cadastroentidades.jsp").forward(req, resp);
            // Após executar esta linha, volta automaticamente para a primeira linha do método
        } else {
            resp.sendError(404, "Entidade não encontrada");
        }

    } else {

        List<Entidade> lstEntidades = entidadeService.getEntidades();

        req.setAttribute("lstEntidades", lstEntidades);
        req.getRequestDispatcher("paginas/listaentidades.jsp").forward(req, resp);
        // Após executar esta linha, volta automaticamente para a primeira linha do método
    }
}

Qualquer ajuda é bem vinda.
Answer: Olá, minha suspeita é que você utilizando o caminho relativo esta sendo redirecionado para a mesma servlet, tente usar o caminho absoluto para essa sua pagina jsp, segue um exemplo:
req.getRequestDispatcher("/WEB-INF/paginas/listaentidades.jsp").forward(req, resp);

Comment: Olá Leonardo Villela, obrigado pela dica, vou testar hoje a noite e posto aqui se for resolvido.
Comment: Olá de nada, se ajudar não esqueça de marcar a pergunta como respodida e avalidar a resposta, bons estudos :)
Comment: Valeu, Leonardo Villela, resolvi aqui seguindo sua dica.


setting IP address from different subnet to virtual machines

Question: I have only 1 NIC on my server and the IP address of it is 62.X.X.107. And the gateway I've received from the datacenter is 62.X.X.1. I have bought 2 more IP addresses from the datacenter to use them for my virtual machines, but the IP addresses starts with 5! I mean they are 5.X.X.X. I'm really confused how to get it work!
Note: The virtual machines have Windows Server 2008 R2 installed on them.
Comment: Actually, how can I give an IP adddress like 5.X.X.X to a VM with the default gateway of 62.X.X.1? How can I route that!?
Comment: I used 255.255.255.255 as mask to route all the trrafic to the gateway, but it didn't work! :(
Answer: If the 5.X.X.X IPs are on-net (on the same switched network as your 62.X.X.107 IP), then the network your server is connected to has multiple subnets on it and your hosting provider should have given you a subnet mask and gateway to use with those. In that case, your server will bridge (not route) the packets to your VM; the server will act as a virtual network switch.
If the 5.X.X.X IPs are routed, then your hosting provider has created a static route that delivers those packets via your server's 62.X.X.107 IP and you need your server to route those packets into an internal VM network. The subnet mask of the 5.X.X.X network that is routed to you would have been provided.
Your hosting provider should be providing you support; they should be able to answer whether those IPs are routed or on-net and may be able to give you directions.
Comment: I enabled promiscuous mode on VMWare networking to make it bridged and used 255.255.255.255 mask and it worked!


Como enviar emails entre usuários sem limites?

Question: Boas Pessoal. Tenho uma aplicação em PHP que administra certos tipos de reunião.
Resumindo, uma pessoa cria uma reunião e isso faz com que a aplicação envie emails convidando outros usuários para essa reunião. Funcionava bem quando tinha poucas pessoas, mas agora o servidor de hospedagem está a limitar esses emails, ou seja, uns recebem e outros não (e a aplicação deixa de enviar qualquer email por um determinado período).
Isso tem feito com que eu perca usuários!!!
Como resolver isso? É possível ter um serviço externo em que eu possa somente mudar os dados do SMTP sem mexer na aplicação? No fundo o que eu gostaria era enviar quantos emails fossem necessários. Alguém tem uma ideia melhor? Obrigado.
Comment: Acredito que pode te ajudar: https://www.google.com/intx/pt-BR/work/apps/business/ Como nunca fiz nada desse tipo ainda, posso estar enganado... mas acredito que um e-mail corporativo pode ajudar....
Comment: http://mailchimp.com/, mas você terá que pagar e alterar a parte de envio de emails da sua aplicação.
Comment: Obrigado pessoal pelas informações.
O que mais se enquadra no que eu preciso é o https://mandrillapp.com

Ele fornece o SMTP que eu preciso para inserir na aplicação sem que eu tenha que programar nada. E funciona muito bem até na versão free. :)
Answer: Tive o mesmo problema a algum tempo atrás, meu servidor me limitava a apenas 100 emails/hora. Resolvi contratando um dedicado no exterior, que é mais barato e não te limita.
Cuidado com os apps free. Pro meio corporativo pode ser perigoso.


Could not resolve this reference error

Question: I have been writing a program and within the program I had to zip some files, so I used a addon called Ionic.Zip.
When I run my program its perfectly fine with no errors, but now when I try to build my program as i have finished writing it I get the following error.
<code>Code:
Warning 1   Could not resolve this reference. Could not locate the assembly "Ionic.Zip". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
and the same error for each form where I use the code to zip the files.
</code>
Any ideas what would cause this?
Comment: Please add a screenshot of your references window. May be an issue with "Copy local" setting.
Comment: Yes. Remove bin/Debug reference, copy Ionic.zip dll into your project folder, and reference from there. Leave copy local = true, otherwise it will build, but won't start.
Comment: http://i59.tinypic.com/wrjcza.png Sorry i dont know how to embed it
Comment: No, not the "Add reference", but the actual references dialog that shows which references have already been added. Check my recent answer for how it looks in VS - http://stackoverflow.com/a/27326163/897326.
Comment: http://i62.tinypic.com/f0dtvp.png sorry now i got it, here it is.
Comment: `When I run ... no errors, but now when I try to build ... get the following error` <-- How do you run without building it first? If you are running without building, you are running something else, not the program you are looking at.
Comment: Sorry, what i meant to say is when I click on the start debugging button it works, my program runs, there is no error or warning at the bottom when i am compiling, but when i right click on my project on the right hand side and click on build i get the above error.  All i am trying to do is create an exe of my program, I'm sure it should be build or should i be selecting publish?
Comment: Ok, I think I know where the problem is. You are referencing Ionic.zip from the bin\Debug folder. You shouldn't do that. bin\Debug is volatile and its contents may get deleted any time. Instead, place a DLL inside your project's folder and reference from there. This way you will be building using a reference from your project's folder, but the executing application will make a copy for itself, since copy local is set to True.
Comment: Sorry, could you please elaborate on what I should do? The DLL file which I added to the project, by clicking on add reference do you want me to remove? and then do you want me to copy and paste the dll file in my project folder and then add it again?
Answer: You are referencing Ionic.zip from the bin\Debug folder. You shouldn't do that. bin\Debug is volatile and its contents may get deleted any time. Instead, place a DLL inside your project's folder and reference from there. This way you will be building using a reference from your project's folder, but the executing application will make a copy for itself, since copy local is set to True.

Could not resolve this reference error


Prove that $2\sqrt{\frac{a}{a+c}}-\frac{9\sqrt{c^2+1}}{8c}<1$ with $a;c>0$

Question: Let $a;c>0$ such that $a^2+2ac=1$. Prove that $$2\sqrt{\frac{a}{a+c}}-\frac{9\sqrt{c^2+1}}{8c}<1$$

My proof:
$\Leftrightarrow 2\sqrt{\frac{a}{a+c}}-\frac{9\sqrt{c^2+a^2+2ac}}{8c}<1$
$\Leftrightarrow 2\sqrt{\frac{a}{a+c}}<1+\frac{9\left(a+c\right)}{8c}$
$\Leftrightarrow \frac{4a}{a+c}<\frac{81a^2+306ac+289c^2}{64c^2}$
$\Leftrightarrow \frac{81a^3+387a^2c+339ac^2+289c^3}{64c^2\left(a+c\right)}>0$
The last inequality is true by $a;c>0$. I want some other way and a inequality is rigider than original inequality. Tks
Answer: $2\sqrt{\frac{a}{a+c}}-\frac{9\sqrt{c^2+1}}{8c}=2\sqrt{\frac{a+c-c}{a+c}}-\frac{9\sqrt{a^2+c^2+2ac}}{8c}=2\sqrt{1-\frac c{a+c}}-\frac{9(a+c)}{8c}<2-\frac{9c}{8c}=2-\frac98=\frac78<1$
Comment: Do you have some suggest about a rigid inequality like maximize ?
Comment: I used the inequalities $\sqrt{1-\frac c{a+c}}<1, a+c>c$ which are natural implications of $a,c>0$. What do you mean by rigid inequality? Does it mean an inequality that is true in general?
Comment: It means i want to know the maximize of this inequality.


Centering a line of lyrics on a staff?

Question: I would like to center a line of lyrics on a staff so that the lyrics go inside of the empty space.  Right now I have this:
<<
    \new Lyrics \lyricmode {
        1
        \markup \column {
            "Vertically"
            "center"
            "on staff"
        }1
        1
    }

    \new Staff {
        c1 | \stopStaff s1 \startStaff | c1
    }
>>

But it just prints the lyrics above the staff.  What can I do to put the lyrics inside so that they push the next measure horizontally instead of vertically?
I would also be fine with adding markup, as long as I can put the markup inside of a staff too.
Comment: If I understand your question correctly, check out https://music.stackexchange.com/q/124776/21766. It asks a different question, but the premise of the question (that of using a `\dynamics` staff) may explain what you're looking for.
Answer: Theoretically you can to that by using 0 distance and negative padding:
<<
    \new Lyrics \with {
      \override VerticalAxisGroup.nonstaff-unrelatedstaff-spacing.basic-distance = 0
      \override VerticalAxisGroup.nonstaff-unrelatedstaff-spacing.padding = #-inf.0
    } \lyricmode {
        1
        \markup \vcenter \column {
            "Vertically"
            "center"
            "on staff"
        }1
        1
    }

    \new Staff {
        c1 | \stopStaff s1 \startStaff | c1
    }
>>

which would probably not be the best way to get what you want. Rather the least esoteric way to do it if you do not strictly need lyrics is to use a markup
\new Staff {
    c1 |
    \stopStaff
    \once\textLengthOn
    s1-\tweak outside-staff-priority ##f -\tweak Y-offset 0 -\markup \vcenter \column {
        "Vertically"
        "center"
        "on staff"
    } \startStaff | c1
}

If you do for some reason need this to be Lyrics you could simply make the staff handle lyrics events:
\new Staff \with {
  \consists Lyric_engraver
} {
    c1 |
    \stopStaff
    \lyricmode {
        \markup \vcenter \column {
            "Vertically"
            "center"
            "on staff"
        }1
        These4 are ac -- tu -- |
        al ly -- rics2
    }
    \startStaff | c1
}

Comment: These are all great!  Any thoughts on how I might be able to use \wordwrap instead of \column?  I couldn't get it to work for some reason.
Comment: @DWW256 You probably forgot to override the `linewidth-property` to something that makes sense. The default would be the whole line, so you only wrap after filling the line. Use e.g. `\override #'(line-width . 10) \wordwrap ...`.

Centering a line of lyrics on a staff?


creating a configurable permissions system in django

Question: I am using django to create a web based app. This app will be used as a service by multiple clients.
It has several models / tables that represent a hierarchical relationship. Users are given access based on this hierarchical relationship - ex County -> Schools -> Divisions -> Classrooms.
So a user having access to a division has access to all classrooms within it etc
My question is how do I make this permissions system configurable across clients. The application should a new client to define arbitrary levels - ex country -> state -> city -> schools -> class.
Any ideas on what are good approaches ?
Answer: What about storing the new levels in a prefix tree? you could use each level as a node of a branch of the tree.
When a new user wants do define a new level, the prefix tree will be updated starting from the level where the user belongs. If your problem is just about giving visibility to the user of the sub-branch of the level where he belongs, this should work.
A similar approach, maybe less intuitive, is to give to each level a number (or alpha-numeric value), so that in the end a user associated to the level "state" in your example, has a level code of 23 (let's say: "ex-country": 2 and "state": 3), so that he can add sub-levels starting with the prefix 23.


A problem in vectors with a pyramid whose base is a parallelogram

Question: In the drawing, $ABCDS$ is a pyramid whose base is a parallelogram. $O$ is the intersection of the parallelogram diagonals. The following holds:

$\overrightarrow{SF} = k \cdot \overrightarrow{SD}$
$\overrightarrow{SE} = t \cdot \overrightarrow{SO}$

The problem is to express $t$ using $k$.
Comment: What are $E$ and $F$? Is $SO$ perpendicular to the base? Are the lengths of the edges known?
Comment: $E$ and $F$ are points. It's unkown whether $SO$ is perpendicular to the base, as well as what the lengths of the edges are.
Answer: Hint.
Draw $M$ on $SD$ such that $EM\parallel BD$. Then you have $SM=t\cdot SD$ and $FM=(t/2)FD$. From $SM=SF+FM$ you can then find $t=2k/(k+1)$.
Comment: Why is $FM=(t/2)FD$?
Comment: $FM/FD=EM/BD$, but $EM=t\cdot OD$ and $BD=2OD$.
Comment: Ok, I got it, thanx! Meanwhile I've found in the internet another solution, which involves writing $\overrightarrow{BF}=c\overrightarrow{EF}$ for some real number $c$.


replace last delimeter with "and" in a string in SSRS

Question: I want to replace last delimeter (comma) with and  in a string in SSRS 2008 R2.
if there are more than one product, and the cost of products are different, then the product of each must must be listed separated by commas and 'and' before the last one.
i.e.,
Input string- Hi,Hello,HRU,
Desired output- Hi,Hello and  HRU..
how can I achieve this (and before last word) ?
(suggest in SSRS or even in SQL)
Rgds/-
Comment: Your input ends in a comma, is this intentional? Also, the output ends in two full stops... Is this the intended output?
Answer: I would put a code element to the report as follows:
lblSomething=Code.DoSomething(string)
And your custom code, Code.DoSomething ,code could check for the conditions you have listed above.
ThANKS


C++ alternative for macro pasting

Question: Let's say i have a series of classes:
class Port8Bit{
    void Write(uint8_t data);
    uint8_t Read();
};

class Port16Bit{
    void Write(uint16_t data);
    uint16_t Read();
};
//and so on for 32Bit and 64Bit

when i want to initiate the classes, instead of writing the code again for each class, i can use a macro:
#define intiatePort(portSize) { \
Port##portSize##Bit::Port##portSize##Bit(){ \
} \
  \
void Port##portSize##Bit::Write(uint##portSize##_t data){ \
  \  //write data
} \
uint##portSize##_t Port##portSize##Bit::Read(){ \
    uint##portSize##_t result; \
    \    //read data
    return result;  \

}

I'm quite new to CPP, but I've read that using macros in most cases is not a good practice. I would like to know, is there a better, more CPP-ish way of doing this?
Comment: Yes, use template
Comment: In a few years I hope we can answer this with Metaclasses/Templates completely, but for now templates are the closest you're going to get.
Answer: That's what templates are for:
template<class DataType>
class Port{
    void Write(DataType data);
    DataType Read();
};

using Port8Bit = Port<uint8_t>;
using Port16Bit = Port<uint16_t>;
// etc...

Answer: The C++ answer here is to use templates:
template<Data> class Port {
  void Write(Data data);
  Data Read();
};

Then if you want an 8-bit version:
Port<uint8_t> port8bit;

C++ alternative for macro pasting


Sections of pullback bundle are generated by pullback of sections

Question: Let $M,N$ be smooth manifolds, $\pi:E\to M$ a smooth rank $r$ vector bundle, $f:N\to M$ a smooth map. We define
$$
f^*E=\{(p,v)\in N\times E: f(p)=\pi(v)\},
$$
which has a natural structure of a vector bundle over $N$. Consider a section $\sigma\in\Gamma(E)$. Then
$$
f^*\sigma:p\mapsto (p,\sigma\circ f(p))
$$
defines a smooth section of $f^*E$. I want to show that $\Gamma(f^*E)$, the space of smooth sections of $f^*$E, is generated as a $C^\infty(M)$-module by sections of the form $f^*\sigma$ with $\sigma\in\Gamma(E)$ (in other words: $\Gamma(f^*E)=f^*\Gamma(E)\otimes_{f^*C^\infty(M)}C^\infty(N)$).
Let's first show this locally. Consider a local trivilisation $\phi:E\vert_U\tilde\to U\times\mathbb R^r$. Let $\sigma_i\in\Gamma(E\vert_U)$ correspond to the constant section $p\mapsto (p,e_i)$ of $U\times\mathbb R^n$, where $e_i$ is the $i$-th standard basis vector of $\mathbb R^r$. In other words: $\sigma_i:p\mapsto\phi^{-1}(p,e_i)$. Since $f^*E\vert_{f^{-1}(U)}\cong f^{-1}(U)\times\mathbb R^k$, we see that $f^*\sigma_i$ corresponds under that identification to $p\mapsto (p,e_i)$. It's clear that any section of $f^*E\vert_{f^{-1}(U)}$ is a linear combination of $f^*\sigma_i$.
For the global case, I am thinking of invoking the result that there exists a finite cover $\{U_\alpha\}$ of $M$ and trivialisations $\phi_\alpha: E\vert_{U_\alpha}\tilde\to U_\alpha\times\mathbb R^r$. However, what I would like to do first is extend the previously defined $f^*\sigma_i$ to a global pull-back of a section. I do know it's possible to extend sections locally using a partition of unity argument, but I don't know how to achieve this in such a way that the global extension is still the pull-back of a finite number of sections...
So my question is: given a local section $\sigma\in\Gamma(E\vert_U)$ ($U\subset M$ open), we have a section $f^*\sigma\in\Gamma(f^*E\vert_{f^{-1}(U)})$; how can this section be extended to a section of the form $\sum_{i=1}^k f_i f^*\sigma_i$, $f_i\in C^\infty(M),\sigma_i\in\Gamma(E)$?
Could someone help me out?
I've been given the following hint in the chat: if $U_i$ is an open cover, then there exists(*) an open cover $V_i$ over the same index set such that $\overline{V_i}\subset U_i$. I think I can work it out with this result; I'll post my solution tomorrow.
(*) Existence of a specific refinement of an open cover on a manifold
See Ng Chikeung's answer for a nice short argument.
Answer: Before I write my answer, I want to point out that of course my initial question whether a local section can be extended globally is not true (for the trivial bundle $M\times\mathbb R$ this is equivalent to whether any smooth function defined on $U\subset M$ can be extended globally, and we know this is not true, e.g. $1/x$ on $(0,1)$ can't be extended to $[0,1)$). However, we are not in this situation; we are in the situation where we have a local section that only needs to be extended on a closed subset (closed w.r.t. $M$) of $U$, and this can be done.
Using the same notation as in the question post, let $\sigma\in\Gamma(E)$ and let $U_\alpha$ be a finite trivialising cover for $E$. As already remarked, we have a finite sum $\sigma\vert_{f^{-1}(U_\alpha)}=\sum_i f_i f^*\sigma_i$ with $f_i\in C^\infty(f^{-1}(U_\alpha))$, $\sigma_i\in\Gamma(E\vert_{U_\alpha})$. Following the hint, we know that there exists an open cover $V_\alpha$ of $M$ (with the same index set as $U_\alpha$) such that $\overline{V_\alpha}\subset U_\alpha$. By the Extension Lemma for Vector Bundle (Lemma 10.12 in Lee's Smooth Manifolds) we can extend $\sigma_i\vert_{\overline{V_\alpha}}$ to a global section $\tilde\sigma_i\in\Gamma(E)$. We now choose a partition of unity $\psi_\alpha$ subordinate to the cover $f^{-1}(V_\alpha)$ of $N$. Then we have a finite sum $\sigma=\sum_{\alpha}\psi_\alpha\sigma$. Note that $\psi_\alpha\sigma\vert_{f^{-1}(U_\alpha)}=\sum_i\psi_\alpha f_i f^*\sigma_i$. We can extend $f_i\vert_{\text{supp}(\psi_\alpha)}$ to $\tilde f_i\in C^\infty(N)$. Then $\psi_\alpha\sigma=\sum_i \psi_\alpha\tilde f_i f^*\tilde\sigma_i$.


How do I find the ideals in the ring $\mathbb F_3[x]/(x^2+2)$?

Question: Clearly $\{0\}$ and $\mathbb F_3[x]/(x^2+2)$ will be ideals. How would I find the others?
Comment: Good! You can then use the factors to find ideals much like you would use factors of $6$ to find ideals of $\Bbb{Z}_6$. BTW, have you heard of the Chinese Remainder Theorem?
Comment: Can you factor $x^2+2$?
Comment: The same way you do in any polynomial ring over a field: you find the divisors of $x^2+2$.
Comment: @JyrkiLahtonen $x^2 +2 \equiv (x+1)(x+2)$ mod $3$
Comment: Or the variant of correspondence theorem involving rings and ideals?
Answer: Hint: $x^2+2=x^2-1=(x-1)(x+1)$
Now recall that $F_3[x]$ is a principal ideal domain.


merge array with same keys

Question: I have a array with x array in it with always same keys in these arrays .
Array
(
    [foo] => Array
        (
            [q] => "12r3"
            [w] => "3r45"
            [e] => "67e8"
        )
    [foo1] => Array
        (
            [q] => "féEt"
            [w] => "Ptmf"
            [e] => "4323"
        )
    [foo2] => Array
        (
            [q] => "axa"
            [w] => "dfvd"
            [e] => "hjh"
        )
)

and I need to merge all these arrays in one like:
[foo] => Array
(
     [q] => Array
       (
          [0] => "12r3",
          [1] => "féEt",
          [2] => "axa",
       )
     [w] => Array
       (
          [0] => "3r45",
          [1] => "Ptmf",
          [2] => "dfvd",
       )
    ...

How can I do that?
Thanks.
Answer: This should work for you:
(Here I just go through the first array and grab all columns with array_column() from the entire array with the keys from the first array.)
<?php

    $arr = [

        "foo" => [
            "q" => "12r3",
            "w" => "3r45",
            "e" => "67e8"
        ],
        "foo1" => [
            "q" => "féEt",
            "w" => "Ptmf",
            "e" => "4323"
        ],
        "foo2" => [
            "q" => "axa",
            "w" => "dfvd",
            "e" => "hjh"
        ]
    ];

foreach($arr["foo"] as $k => $v) {
    $results[$k] = array_column($arr, $k);
}

print_r($results);

?>

Output:
Array
(
    [q] => Array
        (
            [0] => 12r3
            [1] => féEt
            [2] => axa
        )

    [w] => Array
        (
            [0] => 3r45
            [1] => Ptmf
            [2] => dfvd
        )

    [e] => Array
        (
            [0] => 67e8
            [1] => 4323
            [2] => hjh
        )

)

Comment: @Smashou But as you can see it works and the output is correct
Comment: When I run you code I just have Array
(
    [q] => Array
        (
            [0] => 12r3
        ),
    [w] => Array
        (
            [0] => 3r45
        ),
    [e] => Array
        (
            [0] => 67e8
        )
Comment: @Smashou php under 5.5?
Comment: Yeah it works! thanks
I didn't know the function array_column() .
Answer: $newArray = [];
foreach($array as $value) {
    foreach($value as $key => $data) {
        $newArray[$key][] = $data;
    }
}
var_dump($newArray);

or
$newArray = [];
foreach($array as $value) {
    $newArray = $newArray + $data;
}
var_dump($newArray);

Answer: If you are using PHP 5.5+ then use array_column, otherwise array_map.
Using array_map:
<?php

$a = Array
(
    0 => Array
        (
            'q' => "12r3",
            'w' => "3r45",
            'e' => "67e8",
        ),
    1 => Array
        (
            'q' => "féEt",
            'w' => "Ptmf",
            'e' => "4323",
        ),
    2 => Array
        (
            'q' => "axa",
            'w' => "dfvd",
            'e' => "hjh",
        )
);

$b = array (
'q'=>array_map(function($element){return $element['q'];}, $a),
'w'=>array_map(function($element){return $element['q'];}, $a),
'e'=>array_map(function($element){return $element['q'];}, $a),
);

print_r($b);
?>

Using array_column:

<?php

$a = Array
(
    0 => Array
        (
            'q' => "12r3",
            'w' => "3r45",
            'e' => "67e8",
        ),
    1 => Array
        (
            'q' => "féEt",
            'w' => "Ptmf",
            'e' => "4323",
        ),
    2 => Array
        (
            'q' => "axa",
            'w' => "dfvd",
            'e' => "hjh",
        )
);

$b = array (
'q'=>array_column('q', $a),
'w'=>array_column('w', $a),
'e'=>array_column('e', $a),
);

print_r($b);
?>

Output:
Array
(
[q] => Array
    (
        [0] => 12r3
        [1] => fÚEt
        [2] => axa
    )

[w] => Array
    (
        [0] => 12r3
        [1] => fÚEt
        [2] => axa
    )

[e] => Array
    (
        [0] => 12r3
        [1] => fÚEt
        [2] => axa
    )

)

merge array with same keys


linux pipe: capture output from forked child

Question: I am having a simple program to send numbers 0 to 2 into a pipe, then function fork_child receive number from this pipe and print out the 1st number it receive and send following number into another pipe connecting to the next child created by fork_child:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

void fork_child(int port_in, int generation) {
    int number;
    int receive_first_number = 0;
    int pid = -1;
    int fd[2];

    while (read(port_in, &number, sizeof(number)) != 0) {
        if (receive_first_number == 0) {
            receive_first_number = 1;
            printf("child-%d (pid %d) receives: %d\n", generation, getpid(), number);
            continue;
        }

        if (pid == -1) {
            // execute only once to create child
            pipe(fd);
            pid = fork();
            if (pid == 0) {
                // child process
                close(fd[1]);
                fork_child(fd[0], generation + 1);
                close(fd[0]);
                exit(0);
            } else {
                // parent process
                close(fd[0]);
            }
        }
        // send number to next child
        write(fd[1], &number, sizeof(number));
    }

    close(fd[1]);
    wait(&pid);
}

int main() {
    int fd[2];
    pipe(fd);

    int pid = fork();
    if (pid == 0) {
        // child process
        close(fd[1]);
        fork_child(fd[0], 0);
        close(fd[0]);
        exit(0);
    } else {
        // parent process
        close(fd[0]);
        for (int number = 0; number < 3; number++) {
            write(fd[1], &number, sizeof(number));
        }
        close(fd[1]);
        wait(&pid);
    }

    return 0;
}

It works as expected when running:
$ ./pipe
child-0 (pid 149437) receives: 0
child-1 (pid 149438) receives: 1
child-2 (pid 149439) receives: 2

execept capturing the output and redirect into a file:
$ ./pipe > out
$ cat out
child-0 (pid 151246) receives: 0
child-1 (pid 151247) receives: 1
child-2 (pid 151248) receives: 2
child-0 (pid 151246) receives: 0
child-1 (pid 151247) receives: 1
child-0 (pid 151246) receives: 0

Why is captured output different from what it was without pipe and redirecting?
Answer: This is a concurrency bug that depends on buffering:
$ stdbuf -o 0 ./pipe
child-0 (pid 864370) receives: 0
child-1 (pid 864371) receives: 1
child-2 (pid 864372) receives: 2
$ stdbuf -o 0 ./pipe > out && cat out
child-0 (pid 864355) receives: 0
child-1 (pid 864356) receives: 1
child-2 (pid 864357) receives: 2
$ stdbuf -o L ./pipe
child-0 (pid 866493) receives: 0
child-1 (pid 866494) receives: 1
child-2 (pid 866495) receives: 2
$ stdbuf -o L ./pipe > out && cat out
child-0 (pid 866501) receives: 0
child-1 (pid 866502) receives: 1
child-2 (pid 866503) receives: 2
$ stdbuf -o 4096 ./pipe
child-0 (pid 864399) receives: 0
child-1 (pid 864400) receives: 1
child-2 (pid 864401) receives: 2
child-0 (pid 864399) receives: 0
child-1 (pid 864400) receives: 1
child-0 (pid 864399) receives: 0
$ stdbuf -o 4096 ./pipe > out && cat out
child-0 (pid 864385) receives: 0
child-1 (pid 864386) receives: 1
child-2 (pid 864387) receives: 2
child-0 (pid 864385) receives: 0
child-1 (pid 864386) receives: 1
child-0 (pid 864385) receives: 0

Note that this type of buffering only affects printf(), not read() or write().
When there's no buffering (stdbuf -o 0), or when buffering is done every line (stdbuf -o L), printf() will flush its write buffer immediately after printing.
When redirecting to a file, the buffer is much bigger (e.g. 4k bytes), and printf() will not flush that buffer.
And then you fork(). But printf()'s buffer is a userspace thing, and the kernel isn't aware of it, so after fork() both the parent and child have a copy of the buffer.
After 2 such forks, the buffer contains all 3 prints, which the 3rd child will print.
But the 2nd child isn't aware that the 3rd child already printed everything, and it will print its buffer, which contains the first 2 prints.
Similarly, the 1st child will print its buffer, which legitimately contains only its own print.
That's how you get 0, 1, 2 (from 3rd child), 0, 1 (from 2nd child), 0 (from first child).
You can see that with strace(1) by checking the amount of bytes written:
$ strace -o /tmp/trace -f ./x && grep 'write.*child-' /tmp/trace
child-0 (pid 867548) receives: 0
child-1 (pid 867549) receives: 1
child-2 (pid 867550) receives: 2
867548 write(1, "child-0 (pid 867548) receives: 0"..., 33) = 33
867549 write(1, "child-1 (pid 867549) receives: 1"..., 33) = 33
867550 write(1, "child-2 (pid 867550) receives: 2"..., 33) = 33
$ strace -o /tmp/trace -f ./x > out && cat out && grep 'write.*child-' /tmp/trace
child-0 (pid 867515) receives: 0
child-1 (pid 867516) receives: 1
child-2 (pid 867517) receives: 2
child-0 (pid 867515) receives: 0
child-1 (pid 867516) receives: 1
child-0 (pid 867515) receives: 0
867517 write(1, "child-0 (pid 867515) receives: 0"..., 99) = 99
867516 write(1, "child-0 (pid 867515) receives: 0"..., 66) = 66
867515 write(1, "child-0 (pid 867515) receives: 0"..., 33) = 33

Possible solutions:

Be explicit about buffer size
fflush() after printf()

See also this question.


How can I project a data set into lower dimension space?

Question: I am new in dimensionality reduction. for iris dataset, with n=150 points, in 3 dimensional space (Sepal-length, Sepal-width,Petal-length) . how can i project them to 2d??
Comment: Principal components analysis would be a good starting point. Enjoy, this is a classic!
Answer: Projection to a lower dimension (or same dimension) can be achieved by matrix multiplication. In your example, the original data matrix $X$ is $150 \times 3$ (in the definition of "data matrix", each row is one data point, and number of columns are number of features.). If we want to project all the data into 2D space, we will use a $3 \times 2$ matrix $P$. The result of $XP$ is $150 \times 2$ matrix.
Here is an example of using PCA to do dimension reduction. Please note how the projection matrix $P$ ($3 \times 2$) is defined.
> d=iris[,1:3]
> pr.out=prcomp(d, scale=T)

> # reduce to 2D
> P=pr.out$rotation[,1:2]

> P
                    PC1         PC2
Sepal.Length  0.6290662 -0.43339843
Sepal.Width  -0.3611443 -0.89806788
Petal.Length  0.6883680 -0.07509912

> head(as.matrix(scale(d)) %*% P)
           PC1        PC2
[1,] -1.850964 -0.4227153
[2,] -1.588617  0.7121722
[3,] -1.945261  0.4090196
[4,] -1.860383  0.6588919
[5,] -2.009789 -0.5764188
[6,] -1.837503 -1.4166620

We can check our manual projection $XP$ and PCA output. They are the same. (Comparing to the first two column / 2D of pr.out$x)
> head(pr.out$x)
           PC1        PC2         PC3
[1,] -1.850964 -0.4227153 -0.12939389
[2,] -1.588617  0.7121722 -0.26157290
[3,] -1.945261  0.4090196 -0.03136284
[4,] -1.860383  0.6588919  0.07069857
[5,] -2.009789 -0.5764188  0.00614575
[6,] -1.837503 -1.4166620 -0.01014686


Como utilizar um índice específico numa consulta em SQL Server?

Question: Tenho uma tabela não normalizada no SQL Server instalado em meu PC a qual é alimentada mensalmente pelo Integration Services (SSIS) a partir de um relatório numa planilha do Excel. Ou seja, estou mantendo o histórico de um certo relatório.
Esta tabela possui vários campos chave. Dependendo da consulta que quero fazer nesta tabela, quero que o SQL Server utilize um index específico.
Por exemplo, a tabela abaixo possui vários campos de identificação.
+---------------+---------+-------+
| Campo         | Tipo    | Index |
+---------------+---------+-------+
| DataID        | date    |   *   |
| NumFolhaID    | int     |   *   |
| LotacaoID     | int     |   *   |
| LotacaoNome   | varchar |       |
| LotacaoZona   | varchar |       |
| FuncMatricID  | int     |   *   |
| FuncVincID    | varchar |   *   |
| FuncNome      | varchar |       |
| FuncCpf       | varchar |       |
| CargoCarreira | varchar |       |
| CargoNome     | varchar |       |
| FuncaoNome    | varchar |       |
| Remuneracao   | money   |       |
| DataAdm       | date    |       |
+---------------+---------+-------+

Eu criei três índices:

INDEX_FUNC - composto pelos campos (FuncMatricID, FuncVincID, DataID) nesta ordem;
INDEX_LOTA - composto pelos campos (LotacaoID, DataID, FuncVincID) nesta ordem;
INDEX_FOLH - composto pelos campos (DataID, NumFolhaID) nesta ordem;

Ao utilizar um SELECT gostaria de utilizar um índice específico para a consulta.
Comment: Desculpe, não sei se trata-se de uma particularidade do SQL Server, mas não consegui entender exatamente em que ponto você está precisando de ajuda.
Comment: Para mim também não ficou muito claro...
Comment: Ao utilizar um SELECT gostaria de utilizar um índice específico, com o intuito de otimizar a busca. Pois, se o índice está na ordem do INDEX_FUNC, quando eu uso uma consulta que some o total do campo `Remuneracao` por `LotacaoID`, a consulta simplesmente fica lenta, pois os campos estão indexados por outros campos que não fazem parte da estratégia da consulta.
Comment: Forçar determinado índice nunca é bom...
Comment: Geralmente o compilador de consulta do sql server seleciona o melhor índice para acessar cada tabela, bem como qual o método de acesso. Para isso considera várias informações que ele mantém sobre as tabelas.
Answer: Você pode executar a consulta como abaixo:
SELECT CAMPO
FROM TABELA WITH (INDEX(INDEX_LOTA))

E também é possível adicionar INDEX em um join
SELECT CAMPO
FROM TABELA T WITH (INDEX(INDEX_LOTA))
INNER JOIN OUTRA_TABELA OT
WITH (INDEX(OUTRO_INDICE))
ON OT.ID = T.ID

Comment: Opa, estou quebrando a cabeça aqui com mysql, preciso selecionar vários registros sem que o script passe mais de 1 vez pelo mesmo nome de usuário ou ID, estou usando Index na query porém me retorna 1 registro só, preciso que a cada f5 ele me retorne outro diferente.


PowerBroker (PBIS) Restricted login list - couldn't resolve srv\DomainUsers [40071]

Question: I want to join a domain with Ubuntu 16.04 machine. The server is Windows Server 2012 R2. I have installed PowerBroker Identity Services (PBIS) 188.8.131.525
I get this error in /var/log/syslog:
Restricted login list - couldn't resolve srv\DomainUsers [40071]

A couple of erros here: /var/log/auth:
Dec 30 08:56:47 srv3 login[1713]: PAM (login) illegal module type: sessions
Dec 30 08:56:47 srv3 login[1713]: PAM (other) illegal module type: sessions
Dec 30 08:56:50 srv3 login[1713]: [lsass-pam] [module:pam_lsass]User user12 is denied access because they are not in the 'require membership of' list
Dec 30 08:56:50 srv3 login[1713]: [lsass-pam] [module:pam_lsass]pam_sm_authenticate error [login:user12][error code:40158]
Dec 30 08:56:50 srv3 login[1713]: pam_unix(login:auth): authentication failure; logname=LOGIN uid=0 euid=0 tty=/dev/tty1 ruser= rhost=  user=user12
Dec 30 08:56:50 srv3 login[1713]: pam_sss(login:auth): Request to sssd failed. Connection refused
Dec 30 08:56:53 srv3 login[1713]: FAILED LOGIN (1) on '/dev/tty1' FOR 'user12', Authentication failure

/opt/pbis/bin/config --dump:
 root@srv3:~# /opt/pbis/bin/config --dump
AllowDeleteTo ""
AllowReadTo ""
AllowWriteTo ""
MaxDiskUsage 104857600
MaxEventLifespan 90
MaxNumEvents 100000
DomainSeparator "\\"
SpaceReplacement "^"
EnableEventlog false
SaslMaxBufSize 16777215
Providers "ActiveDirectory"
DisplayMotd false
PAMLogLevel "verbose"
UserNotAllowedError "Access denied"
AssumeDefaultDomain true
CreateHomeDir true
CreateK5Login true
SyncSystemTime true
TrimUserMembership true
LdapSignAndSeal false
LogADNetworkConnectionEvents true
NssEnumerationEnabled true
NssGroupMembersQueryCacheOnly true
NssUserMembershipQueryCacheOnly false
RefreshUserCredentials true
CacheEntryExpiry 14400
DomainManagerCheckDomainOnlineInterval 300
DomainManagerUnknownDomainCacheTimeout 3600
MachinePasswordLifespan 2592000
MemoryCacheSizeCap 0
HomeDirPrefix "/home"
HomeDirTemplate "%H/%U"
RemoteHomeDirTemplate ""
HomeDirUmask "022"
LoginShellTemplate "/bin/bash"
SkeletonDirs "/etc/skel"
UserDomainPrefix "srv"
DomainManagerIgnoreAllTrusts false
DomainManagerIncludeTrustsList
DomainManagerExcludeTrustsList
RequireMembershipOf "srv\\DomainUsers"
Local_AcceptNTLMv1 true
Local_HomeDirTemplate "%H/local/%D/%U"
Local_HomeDirUmask "022"
Local_LoginShellTemplate "/bin/sh"
Local_SkeletonDirs "/etc/skel"
UserMonitorCheckInterval 1800
LsassAutostart true
EventlogAutostart true
BlacklistDC

root@srv3:~# /opt/pbis/bin/get-status
LSA Server Status:

Compiled daemon version: 22.214.171.1245
Packaged product version: 8.5.265.1
Uptime:        0 days 0 hours 14 minutes 5 seconds

[Authentication provider: lsa-activedirectory-provider]

        Status:        Online
        Mode:          Un-provisioned
        Domain:        SRV.LOCAL
        Domain SID:    S-1-5-21-2727847642-148432537-1030246457
        Forest:        srv.local
        Site:          Default-First-Site-Name
        Online check interval:  300 seconds
        [Trusted Domains: 1]

        [Domain: SRV]

                DNS Domain:       srv.local
                Netbios name:     SRV
                Forest name:      srv.local
                Trustee DNS name:
                Client site name: Default-First-Site-Name
                Domain SID:       S-1-5-21-2727847642-148432537-1030246457
                Domain GUID:      8ac2ba85-7313-6746-abfe-d44f9856708e
                Trust Flags:      [0x001d]
                                  [0x0001 - In forest]
                                  [0x0004 - Tree root]
                                  [0x0008 - Primary]
                                  [0x0010 - Native]
                Trust type:       Up Level
                Trust Attributes: [0x0000]
                Trust Direction:  Primary Domain
                Trust Mode:       In my forest Trust (MFT)
                Domain flags:     [0x0001]
                                  [0x0001 - Primary]

                [Domain Controller (DC) Information]

                        DC Name:              dc1.srv.local
                        DC Address:           192.168.253.200
                        DC Site:              Default-First-Site-Name
                        DC Flags:             [0x0000f1fd]
                        DC Is PDC:            yes
                        DC is time server:    yes
                        DC has writeable DS:  yes
                        DC is Global Catalog: yes
                        DC is running KDC:    yes

                [Global Catalog (GC) Information]

                        GC Name:              dc1.srv.local
                        GC Address:           192.168.253.200
                        GC Site:              Default-First-Site-Name
                        GC Flags:             [0x0000f1fd]
                        GC Is PDC:            yes
                        GC is time server:    yes
                        GC has writeable DS:  yes
                        GC is running KDC:    yes

/opt/pbis/share/pbis.pam-auth-update
Name: PowerBroker Identity Services (PBIS)
Default: yes
Priority: 260
Conflicts: winbind
Auth-Type: Primary
Auth:
        [success=end default=ignore]    pam_lsass.so try_first_pass
Auth-Initial:
        [success=end default=ignore]    pam_lsass.so
Account-Type: Primary
Account:
        [success=ok new_authtok_reqd=ok default=ignore]         pam_lsass.so unknown_ok
        [success=end new_authtok_reqd=done default=ignore]      pam_lsass.so
Session-Type: Additional
Session:
        optional        pam_lsass.so
Password-Type: Primary
Password:
        [success=end default=ignore]    pam_lsass.so use_authtok try_first_pass
Password-Initial:
        [success=end default=ignore]    pam_lsass.so

/etc/pam.d/common-account
#
# /etc/pam.d/common-account - authorization settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authorization modules that define
# the central access policy for use on the system.  The default is to
# only deny service to users whose accounts are expired in /etc/shadow.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.
#

# here are the per-package modules (the "Primary" block)
account [success=ok new_authtok_reqd=ok default=ignore]     pam_lsass.so unknown_ok
account [success=2 new_authtok_reqd=done default=ignore]    pam_lsass.so
account [success=1 new_authtok_reqd=done default=ignore]    pam_unix.so
# here's the fallback if no module succeeds
account requisite           pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
account required            pam_permit.so
# and here are more per-package modules (the "Additional" block)
account sufficient          pam_localuser.so
account [default=bad success=ok user_unknown=ignore]    pam_sss.so
# end of pam-auth-update config

/etc/pam.d/common-session:
#
# /etc/pam.d/common-session - session-related modules common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of modules that define tasks to be performed
# at the start and end of sessions of *any* kind (both interactive and
# non-interactive).
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.

# here are the per-package modules (the "Primary" block)
session [default=1]         pam_permit.so
# here's the fallback if no module succeeds
session requisite           pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
session required            pam_permit.so
# The pam_umask module will set the umask according to the system default in
# /etc/login.defs and user settings, solving the problem of different
# umask settings with different shells, display managers, remote sessions etc.
# See "man pam_umask".
session optional            pam_umask.so
# and here are more per-package modules (the "Additional" block)
#session    optional    pam_lsass.so
sessions [success=ok default=ignore] pam_lsass.so
session required    pam_unix.so
session optional            pam_sss.so
session optional    pam_systemd.so
# end of pam-auth-update config
session    required    pam_mkhomedir.so skel=/etc/skel/ umask=0022

/etc/pam.d/common-auth:
#
# /etc/pam.d/common-auth - authentication settings common to all services
#
# This file is included from other service-specific PAM config files,
# and should contain a list of the authentication modules that define
# the central authentication scheme for use on the system
# (e.g., /etc/shadow, LDAP, Kerberos, etc.).  The default is to use the
# traditional Unix authentication mechanisms.
#
# As of pam 1.0.1-6, this file is managed by pam-auth-update by default.
# To take advantage of this, it is recommended that you configure any
# local modules either before or after the default block, and use
# pam-auth-update to manage selection of other modules.  See
# pam-auth-update(8) for details.

# here are the per-package modules (the "Primary" block)
auth    [success=3 default=ignore]      pam_lsass.so
auth    [success=2 default=ignore]      pam_unix.so nullok_secure try_first_pass
auth    [success=1 default=ignore]      pam_sss.so use_first_pass
# here's the fallback if no module succeeds
auth    requisite                       pam_deny.so
# prime the stack with a positive return value if there isn't one already;
# this avoids us returning an error just because nothing sets a success code
# since the modules above will each just jump around
auth    required                        pam_permit.so
# and here are more per-package modules (the "Additional" block)
# end of pam-auth-update config
~
~

/etc/pbis/pbis-krb5-ad.conf:
[libdefaults]
    default_tgs_enctypes = AES256-CTS AES128-CTS RC4-HMAC DES-CBC-MD5 DES-CBC-CRC
    default_tkt_enctypes = AES256-CTS AES128-CTS RC4-HMAC DES-CBC-MD5 DES-CBC-CRC
    preferred_enctypes = AES256-CTS AES128-CTS RC4-HMAC DES-CBC-MD5 DES-CBC-CRC
    dns_lookup_kdc = true
    pkinit_kdc_hostname = <DNS>
    pkinit_anchors = DIR:/var/lib/pbis/trusted_certs
    pkinit_cert_match = &&<EKU>msScLogin<PRINCIPAL>
    pkinit_eku_checking = kpServerAuth
    pkinit_win2k_require_binding = false
    pkinit_identities = PKCS11:/opt/pbis/lib/libpkcs11.so

Answer:
Restricted login list - couldn't resolve srv\DomainUsers [40071]

You should check that the naming of the group Domain Users in the settings PBIS corresponds to how it sees PBIS.
To do this, run the following command:
/opt/pbis/bin/enum-groups | grep -i Domain

Find you Domain Users group name as it displayed and put name of the group to configuration in the same form.
Comment: I have changed the config option. But I still can not login to console.
Comment: @xenioz New or same error?
Comment: The error that i had before is gone but i get this:

Dec 30 09:56:14 srv3 login[1736]: pam_sss(login:account): Request to sssd failed. Connection refused
Dec 30 09:56:14 srv3 login[1736]: Authentication service cannot retrieve authentication info
Dec 30 09:56:15 srv3 login[1742]: PAM (login) illegal module type: sessions
Dec 30 09:56:15 srv3 login[1742]: PAM (other) illegal module type: sessions


Verificar se data e hora/minuto já expiraram

Question: Estou com um problema, ao subir meu site para o PHP 5.6 o código que eu utilizo para verificar se tal data e tal hora/minuto expirou simplesmente não está respeitando a hora, se for a data já fala que expirou sem verificar a hora/minuto. Alguém tem alguma solução?
<code>$sql = "SELECT * FROM noticias WHERE programada = 'sim'";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
$row = mysql_fetch_array($res);

function NoticiasProgramadas($data){
    $dt_expira = str_replace("/", "-", $data);
    $dateInicio = date('Y/m/d G:i:s', strtotime($dt_expira));
    $timestamp_dt_expira = strtotime($dt_expira);
    $dt_atual = date("Y/m/d G:i:s");
    $timestamp_dt_atual = strtotime($dt_atual);

        $ret = '';
        if ($timestamp_dt_atual >= $timestamp_dt_expira) {
            $ret = "exp";
        }
    return $ret;
}
$d = NoticiasProgramadas("$row[postdate] $row[posthora]");
if ($d == "exp"){

//executa um código mysql

}
</code>
Comment: Dê um echo nas variaveis `$timestamp_dt_atual` e `$timestamp_dt_expira` para ver como elas estão antes do if;
Comment: 11-04-2018, 18:19 2018/04/11 23:19:01
Comment: Não, o timestamp mesmo, antes do `if ($timestamp_dt_atual >= $timestamp_dt_expira) `
Comment: Desculpe, eles estão assim 1523440560  1523483518
Comment: Voce pode simplificar nossa vida editando sua pergunta com os dados que esta usando para testar? Tipo o que é o `$data`, pois assim podemos testar seu codigo e ajudar
Comment: O $data não tem nada
Comment: Perdao, isso: `$row[postdate] $row[posthora]`
Comment: Vem do primeiro código lá em cima do **$sql = "SELECT * FROM noticias WHERE programada = 'sim'";**
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/75863/discussion-between-david-dias-and-carlos-g).
Answer: Amigo,
Verifica como está a timezone do seu servidor on-line, em alguns casos antes de fazer qualquer coisa no PHP, você deve setar sua timezone para que dali em diante seu PHP trabalhe apenas com data e hora exatas, por exemplo:
<code><?php
date_default_timezone_set('America/Sao_Paulo');

// daqui em diante tu bota o seu código...
</code>
Comment: Já está definido no mesmo arquivo *Brazil/East*