How to use Entity Framework 7 in class library?

Question: I want to make the work with data in a class library with asp.net core 1. I created MyDbContext in a class library:
public class MyDbContext: DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<UserProfile> Profiles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
            base.OnModelCreating(modelBuilder);

            // maybe need to add foreign key
            modelBuilder.Entity<User>()
                .HasOne(p => p.Profile)
                .WithOne(u => u.User)
                .HasForeignKey<UserProfile>(p => p.UserId);
    }
}

My project.json in class library:
{
  "version": "1.0.0-*",
  "description": "DatabaseCore Class Library",
  "authors": [ "alex-pc" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",
  "frameworks": {
    "net451": {
      "dependencies": {
        "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
        "EntityFramework.Commands": "7.0.0-rc1-final"
      },
      "frameworkAssemblies": {
        "System.Runtime": "184.108.40.206",
        "System.Data.Entity": "220.127.116.11",
        "System.Data": "126.96.36.199",
        "System.ComponentModel.DataAnnotations": "18.104.22.168"
      }
    }
  },

  "dependencies": {

  }
}

And updated startup.cs in web application:
 public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {

            builder.AddApplicationInsightsSettings(developerMode: true);
        }
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<MyDbContext>(options =>
            {
                options.UseSqlServer(Configuration["Data:ConnectionString"]);
            });
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        //services.AddAuthorization(options =>
        //{
        //    options.AddPolicy("API", policy =>
        //    {
        //        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        //        policy.RequireAuthenticatedUser();
        //    });
        //});
        services.AddAuthentication();
        services.AddCaching();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseIISPlatformHandler();

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();
        app.UseJwtBearerAuthentication(options =>
        {
            options.AutomaticAuthenticate = true;
            options.Audience = "resource_server_1";
            options.Authority = "http://localhost:4871/";
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters.ValidateLifetime = true;
        });

        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer(options =>
        {
            options.AllowInsecureHttp = true;
            options.AuthorizationEndpointPath = PathString.Empty;
            options.TokenEndpointPath = "/connect/token";

            options.Provider = new AuthorizationProvider();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    // Entry point for the application.
    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

My appsettings.json:
{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "ConnectionString": "Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

Now I want to make the migration to create the database. Using commands in cmd
 dnvm use 1.0.0-rc1-final
 dnx ef migrations add MyFirstMigration
 dnx ef database update

First, all performed well, the database was created, but does not create a table, database is empty. If i added this code:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(
                @"Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
            base.OnConfiguring(optionsBuilder);
        }

error - instance crashes,
Result:
Comment: What error? That's an important detail to leave out.
Comment: instance crashes in cmd red error=(
Comment: That's not specific enough. What exactly does the error say?
Comment: I added screen in my post, i'm deleted method  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  and error missing, migration added database, but doesn't tables =(, db is empty
Comment: Generally you wouldn't get an InvalidOperationException alone without anything else. I suspect this is a bug and that you might consider opening an issue on GitHub.
Comment: Looks like your database is not reachable or the system cannot access it.
Is it configured for windows auth? What user are you using to connect to that database? Does it have permissions to create tables?
Comment: Thanks for answer ). I'm using local database and user have default permission. Database is created, but the tables are not created...IF using MVC 5, all works fine...I'm renewed my full startup.cs...
Comment: I think the instance failure is occurring because the connection string is incorrect:

    @"Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;...

Should actually be

    @"Data Source=DESKTOP-R3AP4AT\SQLEXPRESS;...

Or

    "Data Source=DESKTOP-R3AP4AT\\SQLEXPRESS;...

I.e. don't use both a verbatim string (prefixed with @) and double backslash.

I am adding this as a comment because I am not sure this answers your main question.
Answer: I think you missed
"commands": {
    "ef": "EntityFramework.Commands"
},

in the project.json of your library.
When I moved my EF model into a library I followed the instructions from here: http://www.jerriepelser.com/blog/moving-entity-framework-7-models-to-external-project
Meanwhile I moved from RC1 to RC2 nightly and my project.json of the library looks like this.
{
    "version": "1.0.0-*",
    "description": "DhrData Class Library",
    "authors": [ "noox" ],
    "tags": [ "" ],
    "projectUrl": "",
    "licenseUrl": "",

    "dependencies": {
        "Microsoft.EntityFrameworkCore.Commands": "1.0.0-rc2-20270",
        "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-20270"
    },

    "commands": {
        "ef": "EntityFramework.Commands"
    },

    "frameworks": {
        "dnx451": {
            "frameworkAssemblies": {
                "System.Reflection": ""
            }
        },
        "dnxcore50": {
            "dependencies": {           }
        }
    }
}

Lately I did not use migration because I had too much changes while playing around with EF Core. Instead I created a console application which recreates the database and fills it with some data. This is already for RC2 (and you probably do not need the custom Appsettings).
using System;
using DhrData.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace DhrConsoleApp
{
    public class Program
    {
        private IServiceProvider serviceProvider;
        public IConfiguration Configuration { get; set; }
        public AppSettings AppSettings { get; set; }  // object for custom configuration

        private void ConfigureServices(IServiceCollection serviceCollection)
        {
            // Add framework services.
            serviceCollection
                //.AddEntityFramework()   // RC1
                .AddEntityFrameworkSqlServer()  // RC2
                .AddDbContext<DhrDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            serviceCollection
                .AddScoped(p => new DhrDbContext(p.GetService<DbContextOptions<DhrDbContext>>()));

            serviceCollection.Configure<AppSettings>(s => Configuration.GetSection("AppSettings"));
        }

        public static void Main(string[] args)
        {
            var applicationEnvironment = PlatformServices.Default.Application;

            new Program(applicationEnvironment);
        }

        public Program(IApplicationEnvironment env)
        {
            //var loggerFactory = new LoggerFactory();
            //loggerFactory.AddConsole(LogLevel.Debug);

            // Set up configuration sources.
            var configurationBuilder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile("config.{env.EnvironmentName.ToLower()}.json", optional: true)
                .AddEnvironmentVariables();

            Configuration = configurationBuilder.Build();

            // custom application settings
            AppSettings = new AppSettings();
            Configuration.GetSection("AppSettings").Bind(AppSettings);

            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            serviceProvider = serviceCollection.BuildServiceProvider();

            using (var dbContext = serviceProvider.GetService<DhrDbContext>())
            {
                RecreateDb(dbContext);
            }
        }

        private void RecreateDb(DhrDbContext dbContext)
        {
            Console.WriteLine("EnsureDeleted ...");
            dbContext.Database.EnsureDeleted();
            Console.WriteLine("EnsureDeleted ... Done!");
            Console.WriteLine("EnsureCreated ...");
            dbContext.Database.EnsureCreated();
            Console.WriteLine("EnsureCreated ... Done!");
            Console.WriteLine("");
        }
    }
}

If not necessary I would not recommend to update to RC2 as long as it is not final. It's a pain. But there are quite some bugs in EF RC1 which have already been fixed in RC2 nightly builds.
Answer: The recommended approach is to leave the connection string in the AddDbContext<TContext>() call in the application's Startup.cs and to use  MigrationsAssembly() to tell EF where the migrations will be located (which should probably be alongside the DbContext). E.g.:
services.AddEntityFramework().AddDbContext<MyDbContext>(options => options
    .UseSqlServer(connectionString)
    .MigrationsAssembly(assemblyName));


MVC4: Export an .xlsx file to excel through mvc using chrome. It works for .xls but not .xlsx

Question: How can I export an .xlsx file to excel through mvc using chrome. It works for .xls but not .xlsx
Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename= Estimate1.xlsx");
    Response.ContentType = "application/excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    Response.Write(sw.ToString());
    Response.End();

and when i open excel file. it show like this. "Excel cannot open file 'FileName.xlsx' because the file format or file extension is not valid."
so much appreciated your help! :)
Comment: possible duplicate of [What is a correct mime type for docx, pptx etc?](http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc)
Comment: sorry if i late to say i using MVC4 and when i rendercontrol : grid.RenderControl(htw);  Excel file cant open because file have HTML Tag is in :(
Comment: @LorenzoDematté I wouldn't say that is a duplicate. But it does contain the answer
Answer: Try changing content type for .xlsx
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

Answer: You should use the correct MIME type. For DOCX is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
See this blog post and this answer for more details


Laravel hasmanythrough where statement

Question: I want to get the projects by the Auth::user() and company_id. I created the following:
Database:
projects:
    - id
    - name
    - company_id
project_users:
    - id
    - project_id
    - user_id
users:
    - id
    - name
    - email
companies:
    - id
    - name

So I want to get the current user projects which belongs to company_id.
I tried the following with User Modal -> return $this->hasManyThrough('App\ProjectUsers', 'App\Project'). $user->projects->where('company_id', 1) but it returns all the data (also with company_id 2,3,4 etc).
I'm looking for a solution which can filter the projects with company_id 1 out of the query.
Comment: Is the hasManyThrough returned from your User model's projects method?
Comment: The hasManyThrough is returned from the User model.
Comment: You should just post your User model code.
Answer: You have to create function in model of user
public function projectusers() {
        return $this->hasMany('App\Models\project_users', 'projectID')->with('companies');
    }

now create function in model projects
public function companies() {
    return $this->hasMany('App\Models\companies','id', 'company_id');
}

Comment: How do I get the projects only where `company = 1`?
Comment: return $this->hasMany('App\Models\companies','id', 'company_id')->where('company', 1);
Answer: If you are trying to limit a relation based on the results of another relation, then you need to use whereHas.
Also if you want to get the projects by some condition, I find its often most helpful to start there, with the projects.
$projects = App\Project::whereHas('company', function($q) use ($company_id) {
    $q->where('id', $company_id);
})->with('users')->get();

This will grab only the projects belonging to a certain company and also eager load the users.
As you are looping, then you can get the count of the users using the relation.
foreach ($projects as $project) {
    echo 'Num User: '.$project->users->count();
}

Comment: Okay that makes more sense, you just want to load the users along with the projects after you've already limited the projects based on the company id.  I've updated the code.
Comment: The user(s) that are linked to the projects are in a separate table, project_users. The project can have 0 or more users.
Comment: Oh I see what you are saying, I think this is close to what you want but how do you get a project by the users if there can be 0, 1, or many users?
Comment: I want a page where the system admin can see how many projects a user has. So for example `user1 is assigned to 6 projects` and `user2 is assigned to 1 project`. That's the reason for this. But the system admin from company 1 is not allowed to see if the user is linked to another company and how many projects they have.

Laravel hasmanythrough where statement


How to calculate points on a line relative to their rectangular containers?

Question:
Given 2 rectangles with known widths and heights of w1, h1 and w2, h2, and a connecting straight line from the centers of each rectangle, with known starting point x1,y1, and known ending point x2,y2, how can I calculate the points on the line where it passes the edge of each rectangle (as defined by x1a,y1a, and x2a,y2a)?
EDIT:
Adding some simple Javascript code to render the 2 rectangles, the line, and plot the point for (x1a, y1a).
<code>let x1 = 75;
let y1 = 40;

let x2 = 375;
let y2 = 340;

let w1 = 150;
let h1 = 80;

let w2 = 150;
let h2 = 80;

// Create objects
let objects = document.getElementById("objects");

let rect1 = document.createElement("div");
rect1.classList.add("rect");
rect1.style.top = "0px";
rect1.style.left = "0px";
rect1.style.width = `${w1}px`;
rect1.style.height = `${h1}px`;

objects.appendChild(rect1);

let rect2 = document.createElement("div");
rect2.classList.add("rect");
rect2.style.width = `${w2}px`;
rect2.style.height = `${h2}px`;
rect2.style.top = "300px";
rect2.style.left = "300px";

objects.appendChild(rect2);

// Insert the path
let line = document.createElementNS(
  "http://www.w3.org/2000/svg",
  "path"
);

line.setAttribute("stroke", "#000");
line.setAttribute("fill", "none");
line.setAttribute("stroke-width", "2");
line.setAttribute("d", `M${x1},${y1} ${x2},${y2}`);

document.getElementById("svg").appendChild(line);

// Update the point

let x1a = x1 - ((h1 / 2) * (x2 - x1)) / (y2 - y1);

let point1 = document.createElement("div");
point1.classList.add("point");

// y coordinate of the point is just the height of the rectangle given it crosses
// the bottom edge of the rectangle
point1.style.top = `${h1}px`;

point1.style.left = `${x1a}px`;
objects.appendChild(point1);
</code>
The point does not show up in the right position, as it has the wrong x1a co-ordinate.
Screenshot of rendering (blue dot is the x1a, y1a point):
Comment: Take one point to be the origin and then write equations of lines, points etc.
Comment: What are the correct equations to write to get x1a,y1a and x2a,y2a? That's what I'm trying to figure out.
Comment: As you have two points' coordinates, you must also know where the origin is?
Answer: The equation of the line connecting the two centers is
$$(x_2-x_1) y-(y_2-y_1)x=y_1x_2-x_1y_2$$
Then, for the case in the diagram, substitute $y=y_{1a}= y_1-\frac{h_1}2$ and $y=y_{2a}=y_2+\frac{h_2}2$ to obtain the respective
$$x_{1a}=x_1 -\frac{h_1}2 \frac{x_2-x_1}{y_2-y_1}, \>\>\>\>\>
 x_{2a}=x_2 +\frac{h_2}2 \frac{x_2-x_1}{y_2-y_1} $$
(Note that there are four cases to consider depending on the relative sizes of the widths and heights.)
Comment: I can't seem to get that equation for x1a to work. Here is an example showing the attempt to plot the x1a, y1a point using that equation: https://codepen.io/theericanderson/pen/MWjvzMy

I must be getting something wrong here.
Comment: @Eric - I am unable to read your codes in the link. Could provide the update in the post
Comment: @ quanto I just updated the main post with my implementation.


Nginx tries to run on port 80 but the configs have been removed

Question: I have a server that runs nginx with varnish.
I cannot run nginx and varnish at the same time as the they are both trying to listen on port 80.
nginx is configured to listen on port 8080
        upstream www {
        server 127.0.0.1:9001;
    }
    server {
        listen 8080 default_server;
        server_name server.com;
        root /var/www/html/;
    location /docs/index.php {
            fastcgi_pass www;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param  HTTPS off;
            fastcgi_param  SERVER_PORT 8888;
        }
}

Varnish then listens on port 80
NFILES=131072
MEMLOCK=82000
NPROCS="unlimited"
RELOAD_VCL=1
VARNISH_VCL_CONF=/etc/varnish/default.vcl
VARNISH_LISTEN_PORT=80
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1
VARNISH_ADMIN_LISTEN_PORT=6082
VARNISH_SECRET_FILE=/etc/varnish/secret
VARNISH_MIN_THREADS=50
VARNISH_MAX_THREADS=1000
VARNISH_THREAD_TIMEOUT=120
VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin
VARNISH_STORAGE_SIZE=1G
VARNISH_STORAGE="file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}"
VARNISH_TTL=120
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
             -f ${VARNISH_VCL_CONF} \
             -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
             -t ${VARNISH_TTL} \
             -w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
             -u varnish -g varnish \
             -S ${VARNISH_SECRET_FILE} \
             -s ${VARNISH_STORAGE}"

When I try and restart nginx now I get an error
service nginx restart
Stopping nginx:                                            [FAILED]
Starting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()

If I stop varnish and run netstat I can see that nginx runs on port 8080 and 80
netstat -tulpn | grep nginx
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      95831/nginx
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      95831/nginx

Checking the nginx config directory, I cannot see anywhere that port is defined
grep -rnw '/etc/nginx/' -e '80'

grep -rnw '/etc/nginx/' -e 'server'
/etc/nginx/nginx.conf.rpmnew:40:    server {
/etc/nginx/nginx.conf.rpmnew:46:        # Load configuration files for the default server block.
/etc/nginx/nginx.conf.rpmnew:52:        # redirect server error pages to the static page /40x.html
/etc/nginx/nginx.conf.rpmnew:58:        # redirect server error pages to the static page /50x.html
/etc/nginx/nginx.conf.rpmnew:70:        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
/etc/nginx/nginx.conf.rpmnew:88:# Settings for a TLS enabled server.
/etc/nginx/nginx.conf.rpmnew:90:#    server {
/etc/nginx/nginx.conf.rpmnew:96:#        ssl_certificate "/etc/pki/nginx/server.crt";
/etc/nginx/nginx.conf.rpmnew:97:#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
/etc/nginx/nginx.conf.rpmnew:107:#        # Load configuration files for the default server block.
/etc/nginx/nginx.conf:40:#    server {
/etc/nginx/nginx.conf:46:#        # Load configuration files for the default server block.
/etc/nginx/nginx.conf:52:        # redirect server error pages to the static page /40x.html
/etc/nginx/nginx.conf:58:        # redirect server error pages to the static page /50x.html
/etc/nginx/nginx.conf:70:        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
/etc/nginx/nginx.conf:88:# Settings for a TLS enabled server.
/etc/nginx/nginx.conf:90:#    server {
/etc/nginx/nginx.conf:96:#        ssl_certificate "/etc/pki/nginx/server.crt";
/etc/nginx/nginx.conf:97:#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
/etc/nginx/nginx.conf:107:#        # Load configuration files for the default server block.
/etc/nginx/conf.d/virtual.conf:5:#server {
/etc/nginx/conf.d/server.conf:2:    server 127.0.0.1:9001;
/etc/nginx/conf.d/server.conf:4:server {
/etc/nginx/conf.d/server.conf:170:server {
/etc/nginx/nginx.conf.default:35:    server {
/etc/nginx/nginx.conf.default:50:        # redirect server error pages to the static page /50x.html
/etc/nginx/nginx.conf.default:63:        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
/etc/nginx/nginx.conf.default:84:    #server {
/etc/nginx/nginx.conf.default:96:    # HTTPS server
/etc/nginx/nginx.conf.default:98:    #server {

Comment: Can you please post the output of `grep -rnw '/etc/nginx/' -e 'server'` ?
Comment: You may have more than one `server` location (apart from what's mentioned in the question). When Nginx see a `server` without a `listen` directive, it starts to listen on port 80.
Comment: I see another server block at `/etc/nginx/conf.d/server.conf:170:server {`. Does this contain a listen directive?
Comment: How did you solve it please ? I face same problem and I'm desperate to find where this 80 port comes from !
Comment: If you are getting the same error as me. Then something is running on port 80. Use netstat -tulpn to see what is using that port. If it is nginx. Then run grep -rnw /etc/nginx/ -e '80'
Answer: Check that all the Server blocks have listen directives, otherwise nginx will default to 80 for that block.


How to remove/hide vertical and horizontal scrollbars from eclipse editor?

Question: I'm using Eclipse and I would like to remove scrollbars from the editor.
(I usually partition my screen with multiple opened editors. I want to save space.).
Is there an easy way?
I'm using Windows 7.
Comment: I too would LOVE to know the answer to this.  Scrollbars are such a waste of precious screen space on a small laptop screen. I'm using Juno on Ubuntu 12.04.  At least Jeeeyul's Chrome Theme helps to make the sash narrow... but still can't get rid of that gd scrollbar! >_<
Answer: That an oldie:

bug 27096 mentions the presence of scrollbar for StyleText since 2003, and is a duplicate for:
bug 34928 - Editors show scrollbars even when source has just 1 line with 1 char (also 2003)

Simply put, the StyledText widget has no API to show scrollbars only when necessary.
This is a SWT limitation.
Answer: For all mac users:
Apple menu > System Preferences, then click General > Show scroll bars
Select "Automatically based on mouse or trackpad." i voila :)
Comment: I had to change it to 'When scrolling', but this answer still helped me get rid of the unnecessary horizontal scrollbar, so thanks :)


Tkinter - How to display image when clicking a button?

Question: First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.
Image does show if I run it separately.
My code:
from Tkinter import *

root = Tk()

class PokemonClass(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
                                  bg="Black", fg="White")
        self.WelcomeLabel.pack(fill=X)

        self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
                                 command=self.CharClick)
        self.CharButton.pack(side=LEFT, fill=X)

        self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
        self.SquirtButton.pack(side=LEFT, fill=X)

        self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
                                 fg="White")
        self.BulbButton.pack(side=LEFT, fill=X)

    def CharClick(self):
        print "You like Charmander!"
        global CharSwitch
        CharSwitch = 'Yes'

CharSwitch = 'No'

if CharSwitch == 'Yes':
    CharPhoto = PhotoImage(file="Charmander.gif")
    ChLabel = Label(root, image=CharPhoto)
    ChLabel.pack()

k = PokemonClass(root)
root.mainloop()

Comment: Is this the correct indentation? Strikes me that you didn't intend the part that sets the image to be run straight away. It will never run as you just set the value to `no`. You should move that code to be within the button callback.
Answer: This works, but the actual image no longer shows, if I keep the PhotoImage OUT of the class it will print but I want to have it print IF they click the specific button:
from Tkinter import *

root = Tk()

class PokemonClass(object):

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.WelcomeLabel = Label(root, text = "Welcome! Pick your Pokemon!", bg = "Black", fg = "White")
        self.WelcomeLabel.pack(fill = X)

        self.CharButton = Button(root, text = "Charmander", bg = "RED", fg = "White", command = CharClick)
        self.CharButton.pack(side = LEFT, fill = X)

        self.SquirtButton = Button(root, text = "Squirtle", bg = "Blue", fg = "White")
        self.SquirtButton.pack(side = LEFT, fill = X)

        self.BulbButton = Button(root, text = "Bulbasaur", bg = "Dark Green", fg = "White")
        self.BulbButton.pack(side = LEFT, fill = X)

    def CharClick():
    print "You like Charmander!"
    CharPhoto = PhotoImage(file = "Charmander.gif")
    ChLabel = Label(root, image = CharPhoto)
    ChLabel.pack()

k = PokemonClass(root)
root.mainloop()

Comment: This should be an edit to your question, rather than an answer. I think your issue is explained here http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm or a potentially more up to date source http://tkinter.unpythonic.net/wiki/PhotoImage
Answer: You need to maintain a reference to your PhotoImage object. Unfortunately there is an inconsistency in tkinter in that attaching a Button to a parent widget increments the reference count, but adding an image to a widget does not increment the reference count. As a consequence at the moment the CharPhoto variable goes out of scope at the end of the function CharClick, the number of reference to the PhotoImage falls to zero and the object is made available for garbage collection.
If you keep a reference to the image somewhere, it will appear. When you kept it globally it remained in scope for the entire script and hence appeared.
You can keep a reference to it in the PokemonClass object or in the Label widget.
Below is the later of those options
from Tkinter import *

root = Tk()

class PokemonClass(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
                                  bg="Black", fg="White")
        self.WelcomeLabel.pack(fill=X)

        self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
                                 command=self.CharClick)
        self.CharButton.pack(side=LEFT, fill=X)

        self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
        self.SquirtButton.pack(side=LEFT, fill=X)

        self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
                                 fg="White")
        self.BulbButton.pack(side=LEFT, fill=X)

    def CharClick(self):
        print "You like Charmander!"
        global CharSwitch
        CharSwitch = 'Yes'
        CharPhoto = PhotoImage(file="Charmander.gif")
        ChLabel = Label(root, image=CharPhoto)
        ChLabel.img = CharPhoto
        ChLabel.pack()

CharSwitch = 'No'

k = PokemonClass(root)
root.mainloop()

Answer: The solution which helped me is just simply declaring all the image variables on the next line after 'root = Tk()'. Doing so won't spoil your code or anything.


Saving a field of type 'text_format' as a theme settings variable

Question: I try to add a text area with wysiwyg editor in the theme setting.
If i use '#type' => 'textfield', it works :

If I use '#type' => 'text_format', the text is saved but i don't see it as default value :

If I revert back to '#type' => 'textfield', i can see this :

I guess it is related to the text_format form which is stored as an array ?
How can I use text_format in theme settings ?
Full code in mytheme.theme
function MYTHEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {

  $form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => theme_get_setting('mytheme_texte_presentation'),
    '#description'   => t("lorem ipsum"),
  );
}

Answer: Text format fields are considered to be a compound field (meaning that multiple values are stored for the one field -- the value and the format).
If you inspect the value of mytheme_texte_presentation, you'll find an array that looks something like this array => ['value' => '<val>', 'format' => 'html_restreint'].
If you look at the docs for text_format, you'll see that there is a #format attribute.
Your code should look something like this:
$texte_presentation = theme_get_setting('mytheme_texte_presentation');
$form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => $texte_presentation['value'],
    '#format'        => $texte_presentation['format'],
    '#description'   => t("lorem ipsum"),
  );

Note: This is untested code. You may need to tweak this a bit to make it functional.
Comment: It shouldn't be necessary. Drupal will automatically render all of the form elements. Manually rendering it via the template is just asking for trouble.
Comment: Thank you. I understand how it works now. I should have dumped all the variables before asking. The array `theme_get_setting('mytheme_texte_presentation')` was correct but i had a PHP error and `$texte_presentation['value']` was null.
Comment: Awesome! Glad you got things sorted. If you provide the correct format, I'll update my answer for anyone who finds this in the future.
Comment: How do you then display this in your twig template?


Hosting IIS on multiple disjoint IP addresses

Question: I have two seperate Internet connections coming into the office here that are currently being used for different purposes, but I want to be able to use the second connection as a fallback for our web-based application.
I currently have a Windows machine with IIS that has one NIC connected to the outside world, and another NIC connected to the local network 192.168...  There is a default gateway specified only on the external NIC.  If I try to wire the other internet connection to another NIC I cannot set a second default gateway without throwing Windows completely out of whack and if I don't do so, response packets try to go back on the other connection.
Is there any way to accomplish this short of another machine dedicated to the task (or at least a virtual machine instance)?
Answer: First of all - this sounds like a bit of a security issue. The machine could begin acting as a router if it was compromised, which would then compromise the 192.168 network.  Hopefully this is not your office LAN environment.  It would be better to establish a firewall connected to both Internet connections (as untrusted connections) - with your web server in a DMZ network.  Something like... (pardon the ASCII art):
<code>ISP A  ->  firewall  < -  ISP B
             |     |
             V     V
           DMZ     LAN
    web server     everything else
</code>
You could set up port forwarding on the firewall so that connections to port 80 of either ISP's IP forward to your web server, which is on a physically separate DMZ network.  Now, your budget / network architecture etc. might prohibit this.
If that's the case; a simple route add should do the trick.  The help file from route print:
<code>> route ADD 18.104.22.168 MASK 255.0.0.0  126.96.36.199 METRIC 3 IF 2
         destination^      ^mask      ^gateway     metric^    ^
                                                     Interface^
  If IF is not given, it tries to find the best interface for a given
  gateway.
</code>
Is less than terse, but correct. Assuming you want this to be a second route to the outside world, the syntax for the destination would be 0.0.0.0 mask 0.0.0.0.  For the gateway, this is the IP of the machine that gives you access to the second ISP.  I usually skip the metric and IF part, but I think you probably want to set the metric of your "main" ISP to 1 and the metric of the "backup" to 2.
That being said, I'm not totally sure what Windows will do if you enter this.  It will be able to use both gateways, and I think what it will do is prefer the one with metric 1, but if that fails use the one with metric 2.
More info available here: http://technet.microsoft.com/en-us/library/cc779696.aspx
Answer: add a route for that interface. do "route print" to show what the current is and "route add" to add one.


Could you please help me to highlight the selected HTML table row created dynamically through java script

Question: Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
    var table = document.getElementById("NotesFinancialSummary");
    var finSumArr1 = msg.split("^");
    var length = finSumArr1.length-1;
    alert("length"+ length);
    for(var i=1; i<finSumArr1.length; i++)
    {

        var rowValues1 = finSumArr1[i].split("|");
        tb=document.createElement("tbody");
        var tbody=document.createElement("tbody");
        table.appendChild(tbody);
        var tr=document.createElement("tr");
        tbody.appendChild(tr);
        for(var k=0;k<=10;k++)//adding data to table dynamically
        {

            var td=document.createElement("td");
            tr.appendChild(td);
            var element1=rowValues1[k];
            td.innerHTML =element1;
            tr.onclick=function(){

            rowhighlight(this);//calling the rowhighlight function
            }

        }

       }

}

     function rowhighlight(x)
    {

        var index = x.rowIndex;
        document.getElementById("NotesFinancialSummary").rows     [index].style.backgroundColor = "red";

    }

Comment: what is it exactly you want? A function to highlight a row? Why not just add a class, or set the style attribute directly?
Comment: @PeterVR : that is what i have did by setting the style attribute but it is not working...suggest me some other way please...
Comment: Can you give us a demo page, or a fiddle. I suspect there is some other styling interfering with your highlight class. Does it work in other browsers? Have you inspected the live code to see what styling gets applied? Any console.log left in your js, that might prevent it from running in ie8...
Answer: One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
    var selectedRows = document.getElementsByClassName('selected');

    for (var n = 0; n < selectedRows.length; n++) {
        selectedRows[n].className = '';
    }
    this.className = 'selected'
}

And here's a working example of it, though very simple: fiddle time!
Comment: unfortunately the above said one is not working , am in IE8 dat might be the reason...Any other way ....please...


Given line $g$ is parallel to line $h$, how to show that the quadrilateral $PQRS$ is a parallelogram

Question: how to show that the quadrilateral $PQRS$ is a parallelogram if Q is the composition of two reflections $M_g.M_h(P)=Q$ and $M_g.M_h(S)=R$, providing that both $P$ and $S$ are not in $g$ and $h$.
I know that to show a quadrilateral is a parallelogram, one must show each of the opposite side parallel. However, I am stuck in showing $PS$ is parallel to $QR$
Answer:
You are basically reflecting line PS first over line g then line h. The isosceles trapezoids $SS_1P_1P$ and $RS_1P_!Q$ have the same angles hence PS is parallel to QR, and RS is parallel to QP both being perpendicular to h and g.


Line Integral (Absolute value Function)

Question: I'm suppose to calculate the line integral of following:
$\int_C (x^2+y^2)dx + (x^2-y^2)dy$,
where C : y = 1- |1-x|, $0 \leq x \leq 2$
I tried to solve this problem by assuming,
x = t  $=>$ dx =dt
then,
y = 1 - |1 - t| $=>$ dy = -sign|1 - t| dt = $ \left\{
\begin{array}{ll}
      1 & t > 1 \\
      0 & t = 1 \\
      - 1 & t <1 \\
\end{array}
\right.$
on plugging these value in my original integral, I would get,
$\int_0^2 [t^2 + (1-|1-t|^2 )]dt - [t^2-(1-|1-t|^2)sign|1-t|]dt$
Now, how would I integrate such a function? Or did I do something wrong already?
Thanks.
Answer: Well, Consider $0\le x\le 1$ then $y=x$ and $1\lt x\le 2$ then $y=2-x$.
A path $C$ is not a loop. You just evaluate the integral with two intervals.
It will be helpful that drawing the graph of the path(domain).
Comment: That makes so much of sense and much simpler way.. thanks...
Comment: :D You're welcome.

Line Integral (Absolute value Function)


How do I know whether to use linear or nonlinear dimension reduction method given a high dimensional data set

Question: I want to use dimension reduction method for a high dimensional data set
Is there any possible way to assess the "non-linearity" of the data first to give me the insight of whether I should use linear method (e.g. PCA) or nonlinear method (e.g. NLPCA)?
I read several literatures and neither of them could provide a justification of when should I use linear of nonlinear method. They always use examples of "swiss roll" to indicate a data set which I should use nonlinear method. But for practical case, I cannot visualize a high dimensional data set first before I choose the method.
To put it more straightforward, I want to have a test of the data set first and the result will tell me whether the nonlinear method is more suitable for this data set or vice versus.
Thank you!
Comment: "But for practical case, I cannot visualize a high dimensional data set first before I choose the method." -

I don't get this part. What do you mean you can't visualize the data first? For visualization purposes 2 or 3-dimensional reduction is used, so if you can't run this, you won't be able to run anything using more dimensions.
Comment: The problem with this question is that there is no such single thing as 'nonlinear structure'. Different manifold learning algorithms optimize for different things, and it seems like there is no single one to outperform the others.
Comment: I often do both and make a comparison between the two.
Comment: @JakubBartczuk Hi Jakub, in my opinion, using dimension reduction will change the original form of the data. Some data will look linearly after dimension reduction but it is nonlinear in the original space, thats what I am saying here.
Comment: I've had this question for years and still cannot find a clear answer which is general. I always get over simplified examples which do not reflect most real world cases...
Comment: When its going to be unsupervised, the problem is more arduous to comprehend the whether the reduced dimension is linear or non-linear or is it similar to high dimensional space. The co-Ranking R package provides a better way to assess the quality of dimensionality reduction algorithm(i.e linear and non-linear algorithms)
Answer: An example in sklearn.manifold documentation that compares the methods on MNIST digits dataset. It seems that nonlinear methods give more meaningful reduction - you can see clusters corresponding to digits.
As for when to use nonlinear methods - it depends what you want to use.  Using PCA or something similar first is a good idea, as it's more scalable than manifold learning methods. If you're unsatisfied with PCA's results, you can try running nonlinear methods, if they can be actually used (they are not as scalable as basic matrix decomposition methods).
For dimensionality reduction there is also another alternative to PCA - some of its generalizations can incorporate prior knowledge (or, in other words, use regularization). Some methods are even designed to work with mixed data (both categorical and continuous) - see PCA on a Data Frame and Generalized Low Rank Models.
Comment: This answer has nothing to do with the question


Display multiple values from query with formating

Question: This is my current code
$goalquery = "SELECT goal FROM Goals";

if ($result = $mysqli->query($goalquery))
$goal = $result->fetch_row();

foreach($goal as $value){
   ?> My goal is <?php echo $value;
 }

and it displays

But it should return at least 3 values for $goal
It should say...
My goal is to hang my clothing
My goal is to drink less coffee
My goal is to go to the gym everyday

Answer: Instead of fetching a row i think you might want to fetch associations
$goal = $result->fetch_assoc();

From documentation

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

fecth_row() function you used will only return one row

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.


Deleting Python modules

Question: Can you delete Python modules? I've installed one that I would like to remove, and can't seem to figure out how.
Thanks
Comment: How did you install it in the first place?  And which specific module/package was it?  And what platform are you on (if that's not going to be obvious after you update your question)?
Answer: To find where the module is, just do a:
 $ python
 >> import module
 >> print module.__file__
 '/some/directory'

or if it is a package:
 >> import package
 >> print package.__path__

and delete it.
Comment: With python3 don't forget the brackets: print(module.__file__)
Comment: Even easier: I've never seen "print module" fail to properly display it's location, whether module, package, inside zip file, etc.
Comment: A python library may also install standalone scripts which would be placed in other directories.
Comment: i really needed this to uninstall `subprocess.run` , thanks al lot
Answer: If you are using python under windows, the following command is what you need
pip uninstall module

In some cases, you may have installed different versions of the module. For example, after I had the lxml3.4.4 installed via pip, I also installed lxml3.5.0 using its pre-built binary, and thus, the command listed above only remove the first one. So I need to run it twices
pip uninstall lxml
pip uninstall lxml

And it got completed uninstalled. See whether it helps.
Answer: This has already been asked here.
Go into the "site-packages" directory of your python install and remove the files manually.
Answer: Another way using -m flag (especially if Alex Feng's answer is not working) is:
python -m pip uninstall module

NOTE: This works only for Windows, and is to be run in the Command Prompt.
To see if the module has been uninstalled, simply try to import the module again.

Deleting Python modules


use DFS to sync 2 win 2008 r2 iis 7 servers behind load balancer

Question: I want to use DFS to keep in sync for 2 IIS servers behind a load balancer.  These machines are VPS at remote locations and have user uploaded files.  To use DFS you need to be in a domain but I have read that you should not have a domain controller with IIS.
How does one setup 2 iis servers with DFS, on a domain, without one of them being a domain controller?  Sorry, I am really new to the window's way of things and feel I must have a faulty assumption.
Comment: Why not just use a VPN + shared folder?
Comment: With the load balancer I want to be able to have one server go down and still have access.  A shared folder would be located on one server and be a single point of failure as I understand it.
Answer: I think you'd be better served by using a standalone file synchronization tool (rsync, ROBOCOPY, SureSync, etc) rather than DFS-R. You're going to need to stand up a domain for DFS-R and since, presumably, you won't want to dedicate a domain controller (DC) machine on each network, you're going to be in the position of running non-DC roles on a DC. That's generally not recommended.
I wouldn't get so hung up about doing things the "Windows way" that you end up building-out unnecessary infrastructure just to take advantage of a feature that, in your application, is of dubious value.
Comment: I had understood DFS to be near instant in syncing so I thought it would be better than robocopy over a vpn.  Sounds like I am making it more complex than needed.  Thanks
Comment: DFS-R is very nice, but you're talking about a reasonable level of infrastructure to make it happen. I'm the kind of person who tries a simple solution first and only makes things more complex when absolutely necessary. Since you're having users upload files you might be able to capture the uploads such that you can copy those files in near-realtime using a script that fires after an upload completes.
Comment: The load balancer is there for redundancy as the sites don't get much traffic.  I can have the LB serve one until it goes down for some reason.  The syncing can happen every minute so at worst one or two files could be missing.  I can live with that if the rest of the site stays up by the LB switching to the backup server.  Thanks for the reality check, simple is a good thing.


Unable to take input in correct format in c#

Question: A rookie into it, I am unable to take input from Console properly using the following code.
int id;
string name;
float duration;
float price;

Console.WriteLine("Enter the movie id");
id = Convert.ToInt16(Console.Read());

Console.WriteLine("Enter the movie name");
name = Console.ReadLine();

Console.WriteLine("Enter the movie duration");
duration = Convert.ToInt32(Console.Read());

Console.WriteLine("Enter the movie price");
price = Convert.ToInt32(Console.Read());

bl.addMovie(id, name, duration, price);

Comment: Not really, Nishant. You're misunderstanding what's happening there. See Jim's answer.
Comment: What is the problem or error?
Comment: you are using ToInt16 conversion on id is there any special reason for this.
Comment: It is strange that you are using Convert.ToInt32 on something that you are assigning to a float, both for duration and price.
Comment: Actually the problem is with the "name = Console.ReadLine();" line, the lines asking to enter movie name and duration are printed without waiting for the name input.
Answer: The problem is that Console.Read returns an int that represents the next character input. So what happens is that you enter multiple characters and hit Enter and the Read returns a single character. Then the ReadLine returns the rest of the characters as the string.
Replace your calls to Read with calls to ReadLine.
Answer: Read only accepts the next character.
Try:
float price;
Console.WriteLine("Enter the movie price");
string input = Console.ReadLine();
int successStatus = float.TryParse(input, out price);
bool success = successStatus != 0;

Or simply:
float price;
Console.WriteLine("Enter the movie price");
price = (float) Convert.ToDouble(Console.Readline())

The first is preferred because it is better at handling errors when parsing. See the documentation. float.TryParse is synonymous with Single.TryParse
Comment: "it is better at handling errors when parsing" - but sample show no error handling - so in current form first is actually worse as it hides invalid inputs.
Comment: TryParse has internal handling.
Answer: what you need to do is validate each input to be what you want, this is one way
static void Main(string[] args)
{
    int id;
    string name;
    float duration;
    float price;

    do
    {
    Console.WriteLine("Enter the movie id");
    }
    while(!int.TryParse (Console.ReadLine(), out id));

    Console.WriteLine("Enter the movie name");
    name = Console.ReadLine();

    do
    {
        Console.WriteLine("Enter the movie duration");
    }
    while (!float.TryParse(Console.ReadLine(), out duration));

    do
    {
        Console.WriteLine("Enter the movie price");
    }
    while (!float.TryParse(Console.ReadLine(), out price));

    Console.WriteLine("{0}, {1}, {2}, {3}", id, name, duration, price);

    Console.ReadKey();
}

Answer: This worked fine.Use the Console.ReadLine.

  int id;
            string name;
            float duration;
            float price;

            Console.WriteLine("Enter the movie id");
            id = Convert.ToInt16(Console.ReadLine());

            Console.WriteLine("Enter the movie name");
            name = Console.ReadLine();

            Console.WriteLine("Enter the movie duration");
            duration = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the movie price");
            price = Convert.ToInt32(Console.ReadLine());


What's the difference between cudaMalloc() and cuMemAlloc()?

Question: Both cudaMalloc() and cuMemAlloc() can apply memory of device. So what's their difference ?
I'm studying CUDA framework, and trying to understand difference between CUDA runtime API and CUDA driver API.
Comment: They come from different APIs. That is the difference
Answer: CUDA has two "base" APIs, that is, two base sets of functions to interact with a CUDA GPU.  These two APIs are referred to as the "driver API" (documented here) and the "runtime API" (documented here).
cudaMalloc(), along with most functions that begin with cuda belong to the runtime API.
cuMemAlloc() along with most functions that begin wtih cu but not cuda belong to the driver API.
The programming guide has sections discussing both driver API and runtime API, although the runtime API is largely used for demonstration in the programming guide.
The two APIs have considerable symmetry - you would not ordinarily mix them in the same program.  For basic usage, you can do anything you would expect in CUDA (e.g. manage device memory, launch kernels, copy data) using either the driver API or the runtime API.  To punctuate this, here is the basic vectorAdd sample code realized using the driver API, and here is the same realized using the runtime API.
Once you get into the details, of course, there are numerous differences.  To pick just one random example, the driver API allows you to create multiple contexts per GPU, if that is something you would want to do.  This would normally not happen with  a runtime API application.
For beginners, the conventional wisdom is that the runtime API is the place to start.  Most introductory trainings will have the runtime API in view, and the runtime API is usually less verbose than the driver API.
So if you are writing a "runtime API application" you would use cudaMalloc().  If you were writing a "driver API application" you would use cuMemAlloc().  However functionally, they do essentially the same thing - allocate device memory and return a pointer or handle to it.


How to compare WAIC value when they are negative?

Question: How to compare WAIC values when they are negative? Is it still the lower the better?
I got two complex Gaussian models with continuous probability density and the WAIC value are -8351 and -7321, respectively. Is the model with lower WAIC better? Thank you!
Answer: The Widely Applicable Information Criterion (WAIC, Watanabe, (2010) "Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory". Journal of Machine Learning Research 11, 3571–3594.), is a fully Bayesian approach for estimating the

expected log pointwise predictive density for a new dataset

starting with the computed log pointwise posterior predictive density and then adding a correction for the effective number of parameters to adjust for overfitting.
In Watanabe's original definition, WAIC is the negative of the average log pointwise predictive density (assuming the prediction of a single new data point), thus it can take on negative values as the AIC, DIC or the BIC.
Note however that the WAIC in this original definition is not comparable with the AIC or DIC since it is not on the deviance scale. To bring it on the deviance scale you will have to multiply by $-2n$; for more details check Gelman et al. (2014) "Understanding predictive information criteria for Bayesian models", Statistics and Computing 24, 997–1016.
Comment: clear explanation. Thank you!


Set data value of entity reference field with rules

Question: Is there a way that you can "Set data value" of an entity reference field using rules. So I would like to set a newly created node's entity reference field to another node's entity reference field.
Thank you in advance!
Comment: I would say the answer is yes. However, for something as complicated as Rules your question is very vague.
Comment: Hi,

Sorry for the vagueness! I have a content type called "Parent" and a content type called "Child" (This is just for this example). I have downloaded the Rules_link module which places a link on a node of your choice. When clicked it triggers an event. In this case the link would be placed on the parent node and when clicked, this should create a new entity which would be a child node. This child node will contain an entity reference field which will reference to the parent node. But I cannot find a way to set the data value of the child node's reference field.

Thanks for replying!
Answer: If you can't work out how to do it with Rules, maybe try a custom module. It's been suggested to me that you could use hook_node_update(), or hook_node_insert() to populate that field.
Check http://drupal.org/node/1388924.
Answer: Using entity references in rules  & More rule Links this might be of some help....


Como fazer com que a borda superior da div se sobreponha a ponta superior da borda direita?

Question: Estou tentando fazer com que a borda superior da div se sobreponha totalmente a ponta superior da borda da direita, mas não estou obtendo sucesso.
html

css
.caixa{
    width:100px;
    height:100px;
    border-top:14px solid red;
    border-right:14px solid blue;
}

Vejam no exemplo abaixo que as bordas no canto superior direito da div se encontram de forma diagonal, gostaria que a borda superior cobrisse totalmente o canto superior direito.
http://jsfiddle.net/zNkcV/
Answer: Usando pseudo-elemento .caixa::after, é possível obter o efeito desejado:
.caixa{
width:100px;
height:100px;
border-top: 14px solid red;
position: relative;

}
.caixa::after {
    content: "";
    position: absolute;
    bottom: 0; top: 0px; left: 0; right: 0;
    border-right: 14px solid blue;
}

JS Fiddle


How do I set the Views Plugin handler path different from the theme path?

Question: The file path of the module is set up like this:
addressfield/views/addressfield.views.inc
addressfield/views/addressfield_plugin_row_jmappingfields.inc
addressfield/views/addressfield_plugin_style_jmapping.inc
addressfield/theme/addressfield-jmapping-view.tpl.php
addressfield/theme/addressfield-view-jmappingfields.tpl.php

The problem is I can not figure out how to set the path in the plugin definition for the View. If I set the 'theme path' key to drupal_get_path('module', 'addressfield'). '/views' the handlers will register but the themes can not be found and vis versa.
/**
 * @file
 *  Provide the Addressfield plugin definition.
 */

function addressfield_views_plugins() {
  $path = drupal_get_path('module', 'addressfield') . '/views';
  return array(
    'module' => 'addressfield',
    'style' => array(
      'jmapping' => array(
        'title' => t('jMapping'),
        'help' => t('Display a view jMapping map.'),
        'handler' => 'addressfield_plugin_style_jmapping',
        'theme' => 'addressfield_jmapping_view',
        'theme path' => $path,
        'uses row plugin' => TRUE,
        'uses options' => TRUE,
        'uses grouping' => TRUE,
        'type' => 'normal',
        'parent' => 'default',
      ),
    ),
    'row' => array(
      'jmappingfields' => array(
        'title' => t('jMapping Fields'),
        'help' => t('Choose the fields to display in the jMapping Map.'),
        'handler' => 'addressfield_plugin_row_jmappingfields',
        'theme' => 'addressfield_view_jmappingfields',
        'theme path' => $path,
        'uses fields' => TRUE,
        'uses options' => TRUE,
        'type' => 'normal',
      ),
    ),
  );
}

How do I keep the theme templates for the style plugin and the handlers in separate folders for clarity?
I'm using Views 3 in Drupal 7.
Comment: To which Drupal version are you interested?
Comment: I'm using Views 3 in Drupal 7.
Answer: You should create an addressfield/theme/theme.inc that contains the template_preprocess_addressfield_* functions. Then add: $theme_path = drupal_get_path('module', 'addressfield') . '/theme'; at the top.
'handler' => 'addressfield_plugin_style_jmapping',
'path' => $path,
'theme' => 'addressfield_jmapping_view',
'theme path' => $theme_path,
'theme file' => 'theme.inc',

That should work just fine.


How to concat strings in application.yaml?

Question: I want to add two lines in a yaml file, or rather, I want the instance-id field to contain the result of adding the values of the port and name fields
I tried using +, tried through various tags that I saw in similar questions, like !join, !concat (java says they don't exist). But nothing worked in the end.
Is there a solution?
Example yaml (Sorry, i dont know how to load yaml here):

server:
  port: &port 62000
spring:
  application:
    name: &appname 'appname'
eureka:
  client:
    service-url:
      defaultZone: 'http://localhost:8081/eureka/'
  instance:
    instance-id: here should be *appname + ":" + *port (result appname:62000)
Comment: This is an application.yaml for spring boot, I assume? Maybe update the title to reflect that.
Comment: Does this answer your question? [String interpolation in YAML](https://stackoverflow.com/questions/15777987/string-interpolation-in-yaml)
Answer: This won't work for YAML in general, but it will work in Spring Boot, since you can use Property Placeholders, and thus reference other properties from within a property value:
server:
  port: 62000
spring:
  application:
    name: 'appname'
eureka:
  client:
    service-url:
      defaultZone: 'http://localhost:8081/eureka/'
  instance:
    instance-id: ${spring.application.name}:${server.port}

This also works with environment variables, btw.
Comment: Hi!
I tried it - it didn't work, but then, apparently, my application did not perceive my application file as an application file (the settings were not read from there)
I renamed the file and put it in the resource root and everything worked.
Thanks!
Answer: i can provide my application.yml file config for flyway, i think that, based on this code, you can achieve what you want

  flyway:
    url: jdbc:postgresql://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}
    user: ${DATABASE_USER}
    password: ${DATABASE_PASSWORD}
    driver-class-name: org.postgresql.Driver
    baseline-on-migrate: true
    enabled: true
    validate-on-migrate: true
    baseline-version: 0
    default-schema: ${DATABASE_SCHEMA}

and you should remember, that this values must been provided by you, while running application, put them in a environment variables see a link!, or if you run integration tests, you can use @DynamicPropertySource public static void setUpDynamicPropertyValues(DynamicPropertyRegistry registry) { // registry.add("eureka.instance.instance-id", () -> "your instance-id here");
Answer: typically we don't have direct string concatenation or arithmetic operations like in some other languages. However, you can use YAML anchors and aliases to achieve something similar.


Injeção de dependencia com Ninject

Question: Estou usando Ninject no ASP.Net MVC e tentando implementar, mas estou pegando um erro:

Error activating ISessionFactory
No matching bindings are available, and the type is not self-bindable.
Activation path:
3) Injection of dependency ISessionFactory into parameter session of constructor of type PersonRepository
2) Injection of dependency IPersonRepository into parameter personsRepository of constructor of type HomeController 1) Request for HomeController

Estou utilizando ISessionFactory no meu repositório, eu preciso dar bind nele?
Estou usando Fluent NHibernate.
Meu repositório:
public class PersonRepository : IPersonRepository
{
    private ISession openSession;
    private ISessionFactory session;

    public PersonRepository(ISessionFactory session)
    {
        this.openSession = session.OpenSession();
        this.session = session;
    }

    public void CreatePerson(Person person)
    {
        openSession = NhibernateUtilities.OpenIfClosed(session, openSession);
        openSession.SaveOrUpdate(person);
    }
}

Meu controller:
public class HomeController : Controller
{
    private readonly IPersonRepository personsRepository;

    public HomeController(IPersonRepository personsRepository)
    {
        this.personsRepository = personsRepository;
    }

    public ActionResult Index()
    {
        Person test = new Person()
        {
            Id = 1,
            Name = "teste",
            Surname = "teste",
            Nickname = "teste",
            Age = 25,
            Division = "teste",
            Email = "teste",
            Lane = "teste"
        };

        personsRepository.CreatePerson(test);

        return View();
    }

Global.asax:
public class MvcApplication : NinjectHttpApplication
{
    protected override IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        kernel.Bind<IPersonRepository>().To<PersonRepository>();
        return kernel;
    }

    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

}

Answer: Rodrigo,
A princípio é preciso que você faça o bind do seu ISessionFactory.
Segue um tópico do stackoverflow em inglês onde contém o bind.
https://stackoverflow.com/questions/4694917/how-do-i-setup-my-repository-with-fluent-nhibernate

Injeção de dependencia com Ninject


Django Ignore string after PK in URL

Question: product urls.py
urlpatterns = [
    path('<int:pk>/', ProductDetailView.as_view(), name='detail'),
]

Currently my url looks like this http://127.0.0.1:8001/product/11/
However I want to also append the slug of the product. http://127.0.0.1:8001/product/11/example-slug/
But it shouldn't matter what the string is behind it, it should just use the pk in order to display the page. It should ignore the string after /11/ how can I do that?
Comment: Can you add your `ProductDetailView` ?
Comment: Ignoring the slug could be bad for SEO, because search engines will see the same content on `/product/11/example-slug/` and `/product/11/other-slug/`. To avoid this, Stack Overflow redirects to the real slug, e.g. `https://stackoverflow.com/questions/62445649/made-up-slug` will be redirected to the URL with the correct slug for this question.
Comment: other-slug is never linked though, but I understand yea
Answer: Url:
path(<int:pk>/<str:xxx>', ProductDetailView.as_view(), name='detail')

The view side should look like:
   def getproduct(request,pk,xxx):

       the_product= Product.objects.get(pk=pk)

But you should note that if a user changes the string part of the url, the user will still be able to see the page.

Django Ignore string after PK in URL


Running IIS and Confluence both on port 80 (multiple IP addresses)

Question: I'm running Windows Server 2008 with IIS and Confluence. The server has two ip addresses setup at Network Settings.
Confluence is setup to use the second IP address. Both IIS and Confluence seem to startup fine (no errors in logs). However I can't reach Confluence. As soon as I set the port to 8090 i can see Confluence.
Is it possible to use two IP addresses on your server like this?
Answer: Yes, it's possible. Make sure that all sites on the server are bound to specific IP addresses, that includes your default site. In my example on a Windows Media Services server:

Check to see what is listening on port 80 for that IP address using netstat -abn to make sure that nothing else is causing interference.
Comment: I did this, and I also checked using `netstat` that my server is running on port 80. I can reach my second server (not IIS) locally through http://ipaddress/ however from my home pc i can't reach the server. The firewall is open on all IP addresses (port 80) and I can also ping the server, but I can't reach port 80 on the second IP from home...


HtmlUnit failing when it tries to open dead javascript links. Is there a way to tell it not to load specific URLs?

Question: I'm trying to do a little scraping on this site to programatically find polling info. I originally tried Python, which worked great for loading the site and navigating around the aspx forms, but couldn't extract the embedded maps data (since no packages (as of yet) handle javascript). So I've opted to dust off my Java skills and break out HtmlUnit. However, I almost instantly hit a snag.
It appears as though there are some dead links to javascript files on the site that don't exists. When HtmlUnit tries to load them it gets a 404 and self destructs.
Specific Error
Jul 21, 2013 9:51:22 PM com.gargoylesoftware.htmlunit.html.HtmlPage loadExternalJavaScriptFile
SEVERE: Error loading JavaScript from [http://www.eci-polldaymonitoring.nic.in/psl/GoogleMapForASPNet.ascx/jsdebug].
com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 404 Not Found for http://www.eci-polldaymonitoring.nic.in/psl/GoogleMapForASPNet.ascx/jsdebug
    at com.gargoylesoftware.htmlunit.WebClient.throwFailingHttpStatusCodeExceptionIfNecessary(WebClient.java:544)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.loadJavaScriptFromUrl(HtmlPage.java:1119)
    at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:1059)
    at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:399)
    at com.gargoylesoftware.htmlunit.html.HtmlScript$3.execute(HtmlScript.java:260)
    at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:276)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:676)
    at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:635)
    at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1170)
    at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1072)
    at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:206)
    at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:330)
    at org.cyberneko.html.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3074)
    at org.cyberneko.html.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2041)
    at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:918)
    at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:499)
    at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:452)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:892)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:241)
    at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:187)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:268)
    at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:156)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:434)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:309)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:374)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:359)
    at ScrapeTest$.main(ScrapeTest.scala:12)
    at ScrapeTest.main(ScrapeTest.scala)

Is there a way to tell it to either (a) ignore 404 errors completely, or (b) ignore specific javascript urls?
My Code thus far (Scala)
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.BrowserVersion
import com.gargoylesoftware.htmlunit.html.HtmlPage

object ScrapeTest {

  def main(args: Array[String]): Unit = {
    val pageurl = "http://www.eci-polldaymonitoring.nic.in/psl/"
    val client = new WebClient(BrowserVersion.INTERNET_EXPLORER_8)

    var response: HtmlPage = client.getPage(pageurl)

    println(response.asText())
  }
}

Answer: A brief look at the HtmlUnit JavaDoc seems to indicate that you should be able to use WebClientOptions#setExceptionOnFailingStatusCode(boolean)
e.g.,
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.BrowserVersion
import com.gargoylesoftware.htmlunit.html.HtmlPage

object ScrapeTest {

  def main(args: Array[String]): Unit = {
    val pageurl = "http://www.eci-polldaymonitoring.nic.in/psl/"
    val client = new WebClient(BrowserVersion.INTERNET_EXPLORER_8)
    // Don't throw exception on failing status code
    client.getOptions.setExceptionOnFailingStatusCode(false)

    var response: HtmlPage = client.getPage(pageurl)

    println(response.asText())
  }
}

If that doesn't work you could also try:

WebClientOptions#setJavaScriptEnabled(boolean)
WebClientOptions#setThrowExceptionOnScriptError(boolean)
Comment: thanks. setThrowExceptionOnScriptError(false); and setThrowExceptionOnFailingStatusCode(false); did it for me
Answer: I had the same problem. I don't want that HTMLUnit is requesting external Links. Also I don't want printing out css/js warnings and all the noise.
I configured HtmlUnit (with Spring WebApplicationContext):
@NoArgsConstructor(access = PRIVATE)
public final class _MockWebClientCreator {

  public static WebClient createWebClien(WebApplicationContext wac) {
    WebClient webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
    webClient.getOptions().setThrowExceptionOnScriptError(FALSE);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(FALSE);
    webClient.getOptions().setPrintContentOnFailingStatusCode(FALSE);
    webClient.setCssErrorHandler(new SilentCssErrorHandler());
    webClient.setJavaScriptErrorListener(new SilentJavaScriptErrorListener());
    webClient.setWebConnection(new WebConnectionWrapper(webClient) { // Use only internal urls
        @Override
        public WebResponse getResponse(WebRequest request) throws IOException {
            return (startsWith(request.getUrl().toString(), "http://localhost"))
                ? super.getResponse(request)
                : new StringWebResponse("", request.getUrl());
        }
    });
    webClient.setJavaScriptTimeout(Duration.ofSeconds(INTEGER_ONE).toMillis());
    return webClient;
  }
}


Show that $\limsup$ of $\sin n$ is 1

Question: I want to prove that the $\limsup\limits_{n\rightarrow \infty} \sin n=1$. I know that $1$ is an upper bound for $\sin n$ but I cannot find a subsequence of $\sin n$ that converges to $1$. Can somebody help me construct such a subsequence?
Comment: $\sin\left(n\pi+\frac{\pi}{2}\right)$?
Comment: http://math.stackexchange.com/questions/63526/showing-sup-sin-n-mid-n-in-mathbb-n-1
Comment: @cand sorry but that is not a subsequence of $\{\sin n\}$.
Comment: @cand I think he meant $n \in \mathbb N$
Comment: Can't you just use the ergodic theorem on the circle (which is easy to prove directly) to say that there are integers that get arbitrarily close to $\frac{\pi}{2}$ (working modulo $2\pi$, of course)?
Comment: A sketch of a direct method: find a sequence of positive integers $x_n$ and a sequence of positive integers $y_n$ which are equivalent to $1$ mod $4$ such that $q_n = x_n/y_n \to \pi/2$. Then certainly $\sin(q_n) \to 1$. Try to make the convergence sufficiently rapid as $y_n$ grows that $\sin(x_n) = \sin(y_n q_n)  \to 1$. This "make the convergence rapid as $y_n$ grows" idea leads naturally into continued fraction expansion.
Comment: https://math.stackexchange.com/questions/4764/sine-function-dense-in-1-1
Answer: There is a theorem by Kronecker (?) that says that the grid in $\Bbb R$ generated by $1$ and some number $r$ is either dense or an arithmetic progression, obviously corresponding to the cases $r$ irrational or rational.
In this case it means that the sequence of integers modulo $2\pi$ is dense in the interval $[0,2\pi)$, and thus the set of values $\sin(n)$ dense in the interval $[-1,1]$.
Comment: Is there a way we can find the sequence in concrete terms?
Comment: Which sequence, and what does "concrete terms" mean?
Comment: Can we get a certain subsequence of $N$ such that $\sin$ of the sequence converges to 1?

Show that $\limsup$ of $\sin n$ is 1


How to embed and render an entityform

Question: I have an entityform called 'foia_generator' and I'm trying to embed it as a contact form on a page (the tutorial I used is for embedding entityforms in blocks) ... hence my problem...
function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    echo drupal_render($render_estimate_form);
    return $form;
}

This displays the form but it's not 'inside' the normal bounds of the site (using bootstrap subtheme) i.e. it's not rendered properly - it appears before the regular divs like the navbar etc... and spans the entire width of my screen.
If I can't do it this way can I programattically embed the 'entityform' on my 'contact page' as an entityreference field, (rendered)?
Thanks
Answer: Seems like a odd piece of code you've got there, for instance this will render your form randomly in the page:
    echo drupal_render($render_estimate_form);

Which is probably what you're noticing already, that example you're linking is for render that piece of code inside a template but for what you describe you're rendering it in a form inside a block, I'd try something like this instead (untested):
function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    $form['foiagen'] = $render_estimate_form;
    return $form;
}

Comment: Ok, so is it the 'echo' that causes the form to be rendered before everything else? Is the code odd in other ways?
Comment: Yeah, that's it, the rest looks fine but you'll probably want to tweak the form for your specific needs.
Answer: Here's a function I made to embed any entityform:
function my_module_entityform_form($form, &$form_state, $entityform_name) {
  form_load_include($form_state, 'inc', 'entityform', 'entityform.admin');
  $entityform = entityform_create(array('type' => $entityform_name));

  return entityform_edit_form($form, $form_state, $entityform, 'submit', 'embed');
}

And then you can call it using your specific entityform name as a Drupal form:
$form = drupal_get_form('my_module_entityform_form', 'entityform_name');

This is good because it uses form_load_include instead of module_load_include, so the validate and submit functions will also have access to entityform.admin.inc.
Comment: This is useful, but makes it tricky to use hook_form_alter as the $form_id will always be 'my_module_entityform_form'
Comment: I believe you could use hook_form along with drupal_build_form (or whatever it is) in order to create a variable form_id -- allowing unique form alters.

How to embed and render an entityform


GCM: How to send heartbeat to GCM server

Question: I want to send a heartbeat from my application to the GCM server, so the connection will stay alive.
How can I do that, and how can I know the URL of my GCM server??
Thanks in advance!!
Answer: How to send the heartbeat
This class can sent the proper intents
   public class GcmKeepAlive  {

        protected CountDownTimer timer;
        protected Context mContext;
        protected Intent gTalkHeartBeatIntent;
        protected Intent mcsHeartBeatIntent;

        public GcmKeepAlive(Context context) {
            mContext = context;
            gTalkHeartBeatIntent = new Intent(
                    "com.google.android.intent.action.GTALK_HEARTBEAT");
            mcsHeartBeatIntent = new Intent(
                    "com.google.android.intent.action.MCS_HEARTBEAT");
        }

        public void broadcastIntents() {
            System.out.println("sending heart beat to keep gcm alive");
            mContext.sendBroadcast(gTalkHeartBeatIntent);
            mContext.sendBroadcast(mcsHeartBeatIntent);
        }

    }

if you just want to send the heartbeat you can do the following in an Activity
GcmKeepAlive gcmKeepAlive = new GcmKeepAlive(this);
gcmKeepAlive.broadcastIntents();

I don't think you need to set any additional permissions for this but here are the gcm related permissions I have in my manifest
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
    android:name=your_package_name.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="your_package_name.permission.C2D_MESSAGE" />

One way to send the heartbeats on a regular basis
If you want to send them on a regular basis, here is how I am doing that:
    public class GcmKeepAliveBroadcastReceiver extends BroadcastReceiver {

        private GcmKeepAlive gcmKeepAlive;

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("inside gcm keep alive receiver");
            gcmKeepAlive = new GcmKeepAlive(context);
            gcmKeepAlive.broadcastIntents();

        }

    }

I also have a service that has an Dagger injected alarmmanger and pendingintent
@Inject AlarmManager alarmManager;
@Inject PendingIntent gcmKeepAlivePendingIntent;

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, 4*60*1000, gcmKeepAlivePendingIntent);

Here is the section of the Dagger module that provides the alarm manager and pending intent.
There are several ways to have an alarm manager periodically call a method, so assuming you don't use Dagger, you should still be able to pull out the relevant parts.  Your question was how to send the heartbeat, not how to use an alarm manager.  There are lots of answers to that already so search on that.
@Provides PendingIntent provideGcmKeepAlivePendingIntent() {
    System.out.println("pending intent provider");
    Intent gcmKeepAliveIntent = new Intent("com.gmail.npnster.first_project.gcmKeepAlive");
    return PendingIntent.getBroadcast(mContext, 0, gcmKeepAliveIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

@Provides  AlarmManager provideGcmKeepAliveAlarmManager() {
    return (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
}

Comment: I put that code inside button to refresh, and it still not getting the messageges from the GCM al the time... Sometimes it work and sometimes not... Any idea?
Comment: maybe I should not have included the broadcast receiver here. I use it in along with an alarm manager to send the keep alive heartbeats on a regular basis If you create an instance of the GcmKeepAlive class and then call boadcastIntents(); on it, it should send the keep alive heartbeat.
Comment: I just updated my answer.  I broke it into two parts how to send the heartbeat and then one way in which you can arrange to have the heartbeat sent on a regular basis.
Comment: Thanks for your update, but I understood how to send the heartbeat from your first answer. My problem is that even when I send the heartbeat I'm not always get the data that I should get from the GCM server. Sometimes I get it, and sometimes not. In your app the push notifications is instance?
Comment: So are you saying you already knew how to send the heart beat? Or did this answer that question and now you have a new question?
Comment: Well, I asked that question because of a research that I did, that tells that to solve the instant problem, I need to send heartbeat to the GCM server. Your code didn't solved the problem, so I'm not sure that thus is the way to send the heartbeat.... Did it solve it for you?
Comment: Based on my Logcat's the way to tell if the heartbeat is being sent is to look for a message in the log that says has the string com.google.e.a.a.h ... i see that within 500ms of the heartbeat.
Comment: If the heart beat is not your problem, then you can take a look at http://developer.android.com/google/gcm/server.html#params,  i set time_to_live to 0 and delay_while_idle to false, there also might be something in the collapse_key.
Comment: And yes, the code I have shown above, solved the problem of not getting reliable gcm messages from my server.  It is always possible that you have other issues beyond the scope of the question you asked.  Hopefully I helped point you in the right direction - good luck!
Comment: Should I add anything to the Manifest for your code?
Comment: And if the time_to_live be 0, the message won't be sent to device if it's offline, is it?
Comment: right, but for some apps that is OK since it's more of a now or never requirement ... ie if you are requesting the device to send it's location to the server you might only be interested in the location at that moment.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67034/discussion-between-itay-and-npn).


Como criar tabela temporária espelhada em outra

Question: É possível eu criar uma tabela temporária espelhada em outra?
Exemplo: Digamos que eu tenho em meu banco uma tabela com 60 campos. Gostaria de criar uma temp com o nome #tabela com a mesma estrutura da tabela no banco, mas sem precisar escrever os nomes dos campos e tipos, novamente. Isso é possível?
Comment: Já tentou criar uma view?
Answer: Simplesmente:
SELECT * INTO #tabela
FROM TabelaOrigem

Answer:  View pode ser definida como uma tabela virtual composta por linhas e colunas de dados vindos de tabelas relacionadas em uma query (um agrupamento de SELECT's, por exemplo).
CREATE VIEW active_users AS
SELECT id, username, ...
FROM users
WHERE active=True

Dessa forma você terá uma tabela virtual chamada active users
http://www.devmedia.com.br/conceitos-e-criacao-da-view-views-no-sql-server-parte-1/22390
Comment: Esse link pode ser uma boa sugestão, mas sua resposta não terá validade se um dia o link deixar de funcionar. Além disso, é importante para a comunidade ter conteúdo aqui no site mesmo. Seria melhor incluir mais detalhes na sua resposta. Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Queremos respostas que contenham somente links?](http://meta.pt.stackoverflow.com/q/42/74)
Comment: Estou me familiarizando por aqui, alterei a resposta sendo mais objetiva com um exemplo. Acredito que agora poderá contribuir melhor para comunidade. Obrigado pelo conselho
Answer: A ação de criar uma tabela temporária baseada em outra tabela no SQL Server pode ser feita durante um select qualquer. Poderá criar referenciando a tabela inteira ou apenas alguns campos.
Exemplo:
SELECT * INTO #TEMP FROM TABELA
Você pode testar o resultado imediatamente verificando os registros na tabela temporária.
SELECT * FROM #TEMP;
Caso queira apenas uma amostra da tabela, poderá impor um limite no select do tipo SELECT TOP 100 ou SELECT TOP 1000 etc.
Lembrando que não será "copiado" nenhum CONSTRAINT.
Answer: Para criar uma estrutura idêntica, mas sem qualquer conteúdo, pode utilizar a seguinte forma:
-- código #1
IF Object_ID('tempDB..#tabela','U') is not null DROP TABLE #tabela;

SELECT *
  into #tabela
  from minhatabela
  where 1 = 0;

Como a restrição da cláusula WHERE é falsa, somente a estrutura será copiada.
Comment: Diz, ao criar uma tabela sem dados, criei ela de forma temporária, mas não a encontro na árvore de tabelas. Ela existe, mas não vejo. Como eu faço?
Comment: @pnet: Tabelas temporárias ficam no banco de dados tempDB. As tabelas temporárias locais são visíveis apenas na sessão atual. Vide documentação em https://msdn.microsoft.com/pt-br/library/ms174979.aspx#Anchor_4


Deploying a machine learning algorithm, should I include the validation set?

Question: We have developed, trained, and tuned a random forest algorithm for a certain task. We followed the classic split of training/test/validation and we are satisfied with the performance of the algorithm at the moment.
My question is, for production/deployment, should we fit the algorithm on all the data (including the validation set)? We have sufficient self-control that no one will touch that fitted object for any thing other than the production deployment.
Please provide pros and cons for your answers (with references if possible).
Comment: Two things come to mind (without references right away): (1) For deployment is is good to have a model trained on as much data as possible (in general more the better). (2) Random forest are generally stable so your tuned parameters should work well on the complete data.
Answer: How do you define validation?
Normally it is train, validation=dev=tuning, test; I will proceed according to this.
You have trained on train+val and tested on test.
I think you are asking whether to further train on train+validation+test.  If you train on train+val+test you need to use nested CV or bootstrap to obtain a performance estimate. The performance estimate you got from the test set for a model trained on train+val does not apply to this model trained on train+val+dev.  For example, you might have set a HP that gives best results for the tuning set when training on the train set, but it is too restrictive for training on the full set.  Most HP prevent overfitting—-so does more data—-so you likely could have imposed a less severe penalty to get best performance of a model fit on all the data.  I think usually this would be the case, so your model would actually slightly underfit the full set, which is good because you won't be optimistic with your error estimate.  However not really sure. Your train+val set might be a very weird sample and have caused you to actually select a HP that leads to overfitting even on the full data.
I would not feel comfortable reporting a performance estimate for a model trained on the full dataset if the estimate was made for a model trained on train+validation and tested on a test set.  Better to just use the model you have (traInès on train+validation), even though you throw out some data, or use nested CV or bootstrap to correctly obtain performance estimate for model on full data.  Better to be wrong but know it than be wrong but not know it, even if you don't make full use of your data.


Angular 9: interceptor cyclic dependency while injecting lazy loaded service

Question: I face Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS error while injecting my lazy loaded service in the interceptor.
However, so strange my problem is being solved by adding an empty setTimeout(() to the service injection in the interceptor. I am wondering why that happens though...
the lazy loaded LanguageService:
import { HttpClient } from '@angular/common/http';
@Injectable()

export class LanguageService {

  constructor(private http: HttpClient,
    private _translate: TranslateService) {
    this.getLanguages();
  }
// ....

the interceptor:
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { LanguageService } from '../app/blog/services/language.service';

@Injectable()

export class LanguageInterceptor implements HttpInterceptor {
    private _languageService:LanguageService;

    constructor(private injector: Injector) {
        /*  This way Works!
            setTimeout(() => {
            this._languageService = this.injector.get(LanguageService)
         })*/

            this._languageService = this.injector.get(LanguageService)

    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

the interceptor barrel:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LanguageInterceptor } from './lang-interceptor';

export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: LanguageInterceptor, multi: true }
];

the shared module
import { NgModule } from '@angular/core';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { httpInterceptorProviders } from 'src/utilities/interceptor-barrel';
import { ShareModule } from '@ngx-share/core';
import { FormsModule, ReactiveFormsModule }   from '@angular/forms';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, '../assets/i18n/', '.json');
}

const MODULES = [
    HttpClientModule,
    HttpClientJsonpModule,
    CommonModule,
    RouterModule,
    ShareModule,
    FormsModule,
    ReactiveFormsModule
];

@NgModule({
    imports: [
        MODULES,
        TranslateModule.forRoot({
            defaultLanguage: 'en',
            loader: {
                provide: TranslateLoader,
                useFactory: (HttpLoaderFactory),
                deps: [HttpClient]
            }
        }),
    ],
    exports: [
        MODULES,
        TranslateModule
    ],
    declarations: [],
    providers: [
        httpInterceptorProviders
    ],
})

the lazy loaded module:
 // ....
imports: [
        SharedModule
    ]
 // ....
 providers: [
        LanguageService
    ]

Answer: Your LanguageService should not be added to the providers of the lazy loaded module. It should not be added to any providers array of a module. It should have a providedIn: 'root' in the decorator:
@Injectable({ providedIn: 'root' })
export class LanguageService {}

//  lazy loaded module
imports: [
  SharedModule
]

// ....
providers: []

Interceptors on the other hand, should either be declared in your core module, which is included in the App root once. Or in a lazy loaded module, to define a interceptor just for that lazy loaded module

You should restructure your application. Split up your SharedModule to -only- (!important) include components/pipes/directives. These are things that should go in a SharedModule. What -definitely- should not go in there, are application related services and imports.
By the looks of it, your SharedModule should be a CoreModule, and only be imported (not exported) in your AppModule. You should -not- import this module in a lazy loaded module. In your case it will redeclare the HttpClientModule -without- the interceptors, because they are declared in the root and not in the lazy module, making you have the issues you're facing.
Angular itself has a good overview of what kind of modules there are, and what they should and should not contain, and where they should be or should not be imported:

There are five general categories of feature modules which tend to fall into the following groups:

Domain feature modules.
Routed feature modules.
Routing modules.
Service feature modules.
Widget feature modules.
Comment: I tried this but I don't know why the interceptor does not hit any of http requests when included in the app root module...
Answer: The problem is in where you include your interceptors. Your Interceptors should be part of your app/core module.
Comment: Thank you but this way the interceptor does not hit any of http requests
Comment: you have included it in providers of core module? it will work for sure. can you provide a stacblitz with minimal code?
Answer: I've faced the same issue, but I've finally found that I should restart the angular app and everything worked fine after the restart.
Comment: In my case, I have imported a new module and sometimes, angular doesn't feel the newly imported module tell it restarted.
Comment: I'm in the same situation, but I feel that by restarting the app we're just hiding the issue under the carpet. There is something deeper going on here.
Answer: That error occur when you have to import your module inside imports but forgot to add in export section. e.g:
@NgModule({
      declarations: [
      ],
      imports: [
        RadioGroupModule,
      ],
      exports: [

      ],

    })
    export class SharedModule { }


DL360 - Windows Server 2012 Core hyper-v on SD card?

Question: My "plan" is to install 2012 Server Core with the Hyper-v role on an internal SD card in a DL360 G7 (Bios P68 05/05/2011), and put the guest VHDs on iSCSI storage.
Two questions:

Is this viable? Or am I mad?
When I try and install my OS (either via SmartStart or directly), the SD card storage is not recognised (SmartStart says "No disk available for installing an operating system"). I've tried a variety of SD cards - admittedly all from SanDisk. Do I need to load specific drivers for Server2012? Am I missing something fundamental?
Answer:
Sorta. You can install Hyper-V Server 2012 on the SD. You can not install Server 2012 with Hyper-V to a SD however. Those are two different products with unfortunately similar names.
Hyper-V Server 2008 R2 (2.0) can be booted from a SD card too.
There are special directions for doing this, you can't just run setup as you're trying.
Microsoft has provided directions Deploying Microsoft Hyper-V Server 2008 R2 on USB Flash Drive, which work for both 2008 R2 and 2012.

Side note: The SD card must appear as a USB disk device, this is dependent on the SD controller. In HP and Dell servers I've seen, this is the case. I've only seen otherwise in embedded hardware.
Answer: To the best of my knowledge, booting from an SD card is not supported for Hyper-V. This makes the rest of the discussion mostly irrelevant as you simply shouldn't be doing this in production.
Comment: So it's fair to say that Chris S's "Deploying Microsoft Hyper-V Server 2008 R2 on USB Flash Drive" link really just applies test environments, yes? And from what I can see it also involves booting off a VHD?
Comment: @Pete It depends if you have an SD controller that shows as a permanent USB device, and if you want Hyper-V or Server 2012 **with** Hyper-V
Comment: I'm pretty sure my hardware supports it - but I guess I need to check licensing. I have Server2012 Standard licenses - and as far as I can see they each support 1 host and 2 guest instances. Need to check the position if the host is Hyper-v server?
Answer: The SmartStart disk will not allow you to install on the SD card.
VMware vSphere 5 addresses this by telling you NOT to use the SmartStart disk.  I run VMware vSphere 5 on an SD card in an HP DL 360 and am anticipating using HyperV next.  HP had a specific version to install.  It may have that for HyperV also.  I should check but I'm busy at TechStraviganza in the NYC Microsoft offices right now.