mardi 30 avril 2019

User.Identity.Name returns empty and IIS asks for credentials when API is hosted

User.Identity.Name is empty when hosted on IIS. Also IIS asks for cendentials when IP address is put in URL rather than localhost. Please advise how to fix this.

Windows and Anonymous Authentication is enabled in IIS.

I tried enabling and disabling anonymous authentication in IIS

namespace System.Web.Mvc
{
    public class AccessController : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if(!isAuthorized)
            {
                return false;
            }

            return base.AuthorizeCore(httpContext);
        }
    }
}        


My controller
        [System.Web.Http.HttpGet]
        [AccessController]
        [System.Web.Http.Route("api/GetUser")]
        public string GetCurrenTUser()
        {
            if(User.Identity.IsAuthenticated)
            {
                return User.Identity.Name.Replace("EMEA\\", "");
            }

            return "false";

        }

Web.Config

 <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <authentication mode="Windows"/>
  </system.web>




Can I use information (text) from websites to my mobile app/game freely?

I'm developing a game for Android about the things like Fruits and Vegetables. I got to know that I must use Open-Source or Revenue Free images to use in my game. I have found images on www.pexels.com but now I need to know if there's something like "Revenue Free" information or "Free To Use" Information? As I need to include the text about the benefits of a fruit/vegetable. Please share your knowledge.




Calling an asmx service from Web API

Need to call asmx service from one of my get methods in web api .How can we do that ? Can we add a config entry in appsettings to the asmx service url and call it from the web api get mehod?

web config app settings entry:

key="myOldWebservice" value = "http://testAPI/webservice/client.asmx"/>




How to scrap 1-3 million keyword google search web results for numeric data?

I'm looking to build a list of numbers from google keyword searches. Basically, I'd search for a keyword, like "phone number for x daycare". Then, I'd like to scrape the top 10 results for the phone number, so "Maria's Daycare, phone 345-785-9828". Then, I use regex to get the phone number. This gives you an example although, the number I'm looking for is not a phone number, it basically works the same way.

I built this scrapper already and scrapped about 300 keywrods and then was blocked by google. Is there another way to do this preferable for free or relatively cheap? I have about 1-3 million keywords to search. How to unblock my IP?

I already build a web scrapper and was blocked. I receive the 503 error when I try to pull results.

Code is straightforward web scrapper in python.




jQuery events don't occur after I change button class

I am trying to change my buttons' classes when being clicked so as to perform different actions the next time they are clicked. (I do not want to use toggle)

After changing the class, the next time these buttons are clicked nothing occurs even though the class has been changed. Can anyone please help me out? I am just starting to pick up jQuery so I don't know a lot of advanced mechanisms.

 $(".showcontactbutton").click(function(){
    $("#contactform").show();
    //$(this).attr('class', 'hidecontactbutton');
    $(this).removeClass('showcontactbutton').addClass('hidecontactbutton');
    $(this).text("Hide Contact Form");
    //html("<button id='hidecontactbutton'>Hide Contact Form</button>");

});

$(".hidecontactbutton").click(function(){
    alert("Works:");
    $("#contactform").hide();
    //$(this).attr('id', 'showcontactbutton');
    $(this).removeClass('hidecontactbutton').addClass('showcontactbutton');
    $(this).text("Contact Us");
});




Blank screen when trying to draw a triangle with HTML and CSS

I am trying to draw a triangle with HTML and CSS. But I am unable to do it succesfully.

I looked up the most common solution for drawing triangle in CSS.

This the HTML code:

<html>
    <head>
        <link rel="stylesheet" href="tiangle.css" type="text/css">
    </head>
    <body>
        <div id = 'triangle-up'></div>
    </body>
</html>

This is the CSS code:

#triangle-up {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 100px solid red;
  }

The code should draw a red colored upward-facing triangle, but it displays a blank white page. Please help.




How to build a trust badge like trustlock.co

I want to create a badge business like https://trustlock.co I did not know where to start coding such a badge to make it looks like this one https://trustlock.co, It s responsive and support most platforms like wordpress , you only give a script to a client and the badge apears on all pages




How to resize a video to fit the size of image above it?

I'm trying to find a way to scale the video to fit the same width as my header photo. How would I scale the video up to the same size as in the original website? Here's the codepen; https://codepen.io/anon/pen/wZbjNw For reference, I'm trying to mimic this website: https://jackwhiteiii.com/ Thanks!


    <header>

        <div class="headerlogo">
            <img class="jwlogo" src="https://jackwhiteiii.com/wp-content/themes/lazaretto/images/JW_BHR_SplashPage_tiny.jpg" alt="Header Logo">
        </div>


    </header>



    <container>
        <div class="video">
            <iframe class="vevovideo" width="560" height="315" src="https://www.youtube.com/embed/8vKTaoxvZMY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
    </container>




    .jwlogo{

            max-width: 69%;
            height: auto;
            padding:13px;
            image:no-repeat



    }

    .video{
        text-align: center;
        width: 100%;
        height: 100%;
        padding:13px;

    }







Paged list says it does not contain a definition for PagedListPager

When trying to create a Paged ListPager under my Table I get the following error:

'IHtmlHelper<IPagedList<Partnership>>' does not contain a definition for 'PagedListPager'

I have the proper imports as far as I can see so i am not sure what is wrong. Here is my view:

@using PagedList.Mvc;
@using PagedList;
@model IPagedList<Partnership>

@{
    ViewData["Title"] = "Search";
}
<h2>Search</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                Organzation
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var partnership in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => partnership.OrganizationName)
                </td>
            </tr>
        }
    </tbody>
</table>
    @Html.PagedListPager(Model, page => Url.Action("Search", new { page }));

Here is my Controller:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PACE.Models;
using PagedList;

namespace PACE.Controllers
{
    public class SearchPartnershipsController : Controller
    {
        // GET: SearchPartnerships
        public ActionResult Search(int? page)
        {
            var PaceDB = new Models.PaceDB();
            var Organizations = PaceDB.GetAllOrganization();
            var Partnerships = new List<Partnership>();
            var PartnershipsCount = PaceDB.PartnershipTotal();
            Debug.WriteLine(PartnershipsCount);

            for(int i = 0; i<=PartnershipsCount; i++)
            {
                Partnerships.Add(new Partnership { OrganizationName = Organizations[i] });
            }
            int pageNumber = (page ?? 1);
            return View(Partnerships.ToPagedList(pageNumber,20));
        }
    }
}

Could I be missing a package or using that is a bit more obscure. Most people who have this problem seem to get it solved by adding the two imports I have at the top of my view.




blank page when deployed web api to IIS

When deployed to IIS, it was a blank page. But, it works fine on IIS express

warn: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository[50] Using an in-memory repository. Keys will not be persisted to storage. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[59] Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits. warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35] No XML encryptor configured. Key {93884687-9ea2-4971-b76b-9481b4f645ad} may be persisted to storage in unencrypted form. Hosting environment: Production Content root path: C:\Publish\ms_apii Now listening on: http://127.0.0.1:34369 Application started. Press Ctrl+C to shut down. fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLMDI1NSDTPF", Request id "0HLMDI1NSDTPF:00000001": An unhandled exception was thrown by the application. Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = SwaggerGenerator (ReflectionActivator), Services = [Swashbuckle.AspNetCore.Swagger.ISwaggerProvider], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = SchemaRegistryFactory (ReflectionActivator), Services = [Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsManager1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsFactory1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptionsFactory1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IConfigureOptions1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable1[[Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]], Microsoft.Extensions.Options, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = SchemaRegistryFactory (ReflectionActivator), Services = [Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsManager1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsFactory1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptionsFactory1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IConfigureOptions1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable1[[Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]], Microsoft.Extensions.Options, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsManager1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsFactory1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptionsFactory1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IConfigureOptions1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable1[[Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]], Microsoft.Extensions.Options, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = OptionsFactory1 (ReflectionActivator), Services = [Microsoft.Extensions.Options.IOptionsFactory1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IConfigureOptions1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable1[[Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]], Microsoft.Extensions.Options, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IConfigureOptions1[] (DelegateActivator), Services = [System.Collections.Generic.IEnumerable1[[Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]], Microsoft.Extensions.Options, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ConfigureSchemaRegistryOptions (ReflectionActivator), Services = [Microsoft.Extensions.Options.IConfigureOptions1[[Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryOptions, Swashbuckle.AspNetCore.SwaggerGen, Version=4.0.1.0, Culture=neutral, PublicKeyToken=d84d99fb0135530a]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(System.IServiceProvider, Microsoft.Extensions.Options.IOptions1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions])' on type 'ConfigureSchemaRegistryOptions'. ---> Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. (See inner exception for details.) ---> System.IO.FileNotFoundException: Could not find file 'C:\Publish\ms_apii\Milestone.WebApi.xml'. at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle) at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at System.Xml.XmlTextReaderImpl.OpenUrl() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space) at System.Xml.XPath.XPathDocument..ctor(String uri, XmlSpace space) at Microsoft.Extensions.DependencyInjection.SwaggerGenOptionsExtensions.<>c__DisplayClass23_0.b__0() at Microsoft.Extensions.DependencyInjection.SwaggerGenOptionsExtensions.IncludeXmlComments(SwaggerGenOptions swaggerGenOptions, Func1 xmlDocFactory, Boolean includeControllerXmlComments) at Milestone.WebApi.Startup.<>c.<ConfigureServices>b__8_2(SwaggerGenOptions options) in C:\Apps\MilestoneAPI\Milestone.WebApi\Startup.cs:line 87 at Microsoft.Extensions.Options.OptionsFactory1.Create(String name) at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue() at lambda_method(Closure , Object[] ) at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() --- End of inner exception stack trace --- at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at System.Linq.Enumerable.SelectIPartitionIterator2.MoveNext() at System.Linq.Enumerable.OfTypeIterator[TResult](IEnumerable source)+MoveNext() at System.Collections.Generic.LargeArrayBuilder1.AddRange(IEnumerable1 items) at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source) at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable1 parameters) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp, Type type, Type middleware) at lambda_method(Closure , Object , HttpContext , IServiceProvider ) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)




Is there a way to create an Image (AMI) when a spot instance receives a termination request?

Just before a spot instances gets terminated - I'd like to start creating an image of the instance.

I tested and AWS waits for image generation to complete before the shutdown completes.

I also saw this may provide easy access to termination information but have yet to see it on my instance:

wget -q -O - http://169.254.169.254/latest/meta-data/spot/termination-time




File_get_content on lazada webpage not working

I want to get content from lazada page using php, one of easy method is file_get_contents, however when i run the code lazada server was block it.

using php file_get_contents

$a = file_get_contents("https://www.lazada.com.my/catalog/?q=huawei+p30"); echo htmlspecialchars($a, ENT_QUOTES, 'UTF-8');

Expected result is html content result of huawei p30. Instead Lazada has block it.




I want to be a web master

I want to become a web master when I do not know anything about this notion. I only know programmed. I only want to know what are the steps that I must follow to be a web master?




change url without loading (change domain) [duplicate]

This question already has an answer here:

How do I change the site.com address to site2.com but without loading the page but with my content?

The problem I have is that the pushState and replaceState methods only change the internal URLs of my site and the window.location.href method also has the problem of opening the page that I do not want, but I want to add another site address in the address bar Displays without loading that page.




Why I use Reactstrap when I have bootstrap?

The Reactstrap is made based on Bootstrap, Can I use bootstrap instead of Reactstrap?




lundi 29 avril 2019

CSS website changes div size once published

I'm working on my website, and have the main body div set to a certain width. But when I upload all my files to the web host the size of width shrinks, and no matter how i adjust the code for the div the width size stays the same(wrong size) on my published site, despite looking right when i just open the code in a browser.

I've tried Editing the code directly in the web host to see if I can even adjust the width at all. I've already tried deleting and re-uploading everything a few times.

Heres what I have on my css style sheet:

.body1{

max-width: 1200px;
height: 1000px;
background-color: #fffdf8;
margin: auto;
padding: 10px;
text-align: center;
border: 2px solid #f892c9;

}

the width of 1200px is how big i want it to be, and it appears correctly when i open the html file in a browser. When I upload the code with a webhost the width is smaller, and even if I change it to a bigger number like 1500px it stays the small size.




How do I deploy my vue.js web app using a virtual machine?

I am new to web development and I am having trouble deploying a web app.

Context:

I have a working web app, which consists of:

1) front-end: written in vue.js, I used npm run serve to run

2) back-end: written in Django. I used python manage.py runserverto run

Because the app involves GPU computation, I have to run it on my department server. In order to view it, I use SSH port forwarding to forward both the frontend and backend to my localhost (so that I can access it from localhost:16006). It works.

Now, I need to deploy this website to public. My department set up a Ubuntu 18.04.2 virtual machine(VM) for me (using ufw as its firewall software and allowing all outbound connections and inbound ssh, http, and https):

layout2im.cs.ubc.ca

Problems

I pulled my code to this VM and installed relevant dependencies/packages. For frontend, I configured vue.config.js like this:

const BundleTracker = require("webpack-bundle-tracker");

module.exports = {
    publicPath: '',
    outputDir: './dist/',

    chainWebpack: config => {

        config.optimization
            .splitChunks(false)

        config
            .plugin('BundleTracker')
            .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}])

        config.resolve.alias
            .set('__STATIC__', 'static')

        config.devServer
            .public('https://layout2im.cs.ubc.ca:80')
            .host('0.0.0.0')
            .port(80)
            .hotOnly(true)
            .watchOptions({poll: 1000})
            .https(true)
            .headers({"Access-Control-Allow-Origin": ["\*"]})
            .open(true)
    }
};

Then I npm run serve and it said app running at

App running at:
  - Local:   https://localhost:1024
  - Network: https://layout2im.cs.ubc.ca:80/

But I can't open https://layout2im.cs.ubc.ca:80/ in the browser. (I tried port 443 and it doesn't work either)

This site can’t be reached
layout2im.cs.ubc.ca refused to connect.

(I don't know if this is relevant, but I tried npm run build too, and dist/index.html contains:

<noscript><strong>
We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.
</strong></noscript>

)

I am not even sure if I am on the right track. It'd be great if somebody can point out my mistakes and how I should properly make use of the VM to deploy this website. (e.g. Do I need Docker?)




How to add Background Image for PHP file

How can I add a background image on my PHP file? I want to add an image to the page that thanks my users for subscribing to the newsletter.

I have tried the body background attribute for HTML but it did not work.

<body>
  <div class="center">
    <?php

    /* CONNECTION */
    $database_connection = new StdClass();

    /** MySQL hostname */
    $database_connection->server = '829.23.12.123';

    /** MySQL database username */
    $database_connection->username = 'something_usr';

    /** MySQL database password */
    $database_connection->password = 'KJGAout7L';

    /** The name of the database */
    $database_connection->name = 'database_content';

    /* ESTABLISHING THE CONNECTION */
    $database = new mysqli($database_connection->server, $database_connection->username, $database_connection->password, $database_connection->name);

    if($database->connect_error) {

      echo 'connection failed';
    }

    $stmt = $database->prepare("INSERT INTO Email_Subs (email) VALUES (?)");
    $stmt->bind_param("s", $_POST[email]);
    $stmt->execute();
    $stmt->close();

    echo "<div class='jumbotron text-xs-center bg-white'>";
    echo "<h1 class='display-3'>Thank you, you have successfully subscribed!</h1>";
    echo "<p class='lead'>You will be the first to hear about news, events, exclusive stories, and more!</p>";
    echo "<p class='lead'>";
    echo "<a class='btn btn-primary btn-sm' href='index'>Return to Home</a>";
    echo "</p>";
    echo "</div>";

    $database->close();

    ?>
  </div>

</body>




How to make a user on my website ping a specific ip address?

I'm wondering how website like this one : https://ping.eu/ping/ manage to make our ip ping an other ip and get the result.

Someone have an idea ?

Thanks




Auto Slideshow with pure JS

I need to write code for auto slideshow js without library.But i got stuck how to get children of div with class name.(new to web development)

<div class="slideshow">
    <img src="img/kitten_1.jpg">
    <img src="img/kitten_2.jpg">
    <img src="img/kitten_3.jpg">
    <img src="img/kitten_4.jpg">
    <img src="img/kitten_5.jpg">




Spring been type not well define and missing configuration

I am making changes to the security of Spring to connect to the database, however it says that the bean is not well define and I have use the @Autowired and its corresponding @Bean; I am still learning the configuration.

Could this be a missing plug?

Error:
Description: Field env in com.bookstore.config.SecurityConfig required a bean of type 'org.hibernate.cfg.Environment' that could not be found.

The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.hibernate.cfg.Environment' in your configuration.

Github: https://github.com/latinprogrammer/Ecommerce-Spring-Boot

SecurityConfig.java

    package com.bookstore.config;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.hibernate.cfg.Environment;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

    import com.bookstore.service.impl.UserSecurityService;
    import com.bookstore.utility.SecurityUtility;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired
private Environment env;


@Autowired
private UserSecurityService userSecurityService;

private BCryptPasswordEncoder passwordEncoder() {

    return SecurityUtility.passwordEncoder();

}

private static final String[] PUBLIC_MATCHERS= {
        "/CSS/**",
        "/JS/**",
        "/img/**",
        "/",
        "/myAccount"


};

@Override
protected void configure(HttpSecurity http) throws Exception {

    http

         .authorizeRequests(). 
      /*   antMatchers("/**").*/
         antMatchers(PUBLIC_MATCHERS).
         permitAll().anyRequest().authenticated();

    http

    .csrf().disable().cors().disable()
    .formLogin().failureForwardUrl("/login?error").defaultSuccessUrl("/")
    .loginPage("/login").permitAll()
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
    .and().rememberMe();


}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());

}

}

---------------------------------------------------------
SecurityUtility.java


package com.bookstore.utility;

import java.security.SecureRandom;
import java.util.Random;

import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtility {

    private static final String SALT = "salt"; // Salt should be protected carefully

     @Bean
     public static BCryptPasswordEncoder passwordEncoder() {
        return new  BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));

     }

     @Bean
     public static String randomPassword() {

         String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
         StringBuilder salt = new StringBuilder();
         Random rnd = new Random();

         while(salt.length() < 18)
         {
             int index = (int) (rnd.nextFloat() * SALTCHARS.length());
             salt.append(SALTCHARS.charAt(index));
         }

         String saltStr = salt.toString();
         return saltStr;
     }

}


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->

    </parent>
    <groupId>com.bookstore</groupId>
    <artifactId>bookstore</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bookstore</name>
    <description>Frontend part for bookstore project</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>




How to create a local database using JSON and JavaScript for webapp

I need to develop a simple webapp with a login system, users and data saved to each one of those users, with no knowlege of PHP or Data bases, only HTML, JavaScript/JQuery and JSON.

I must be able to sign up, log in and save some data (it's an online store, i must be able to save purchases historic, list of avourite products, user preferences, etc), all this locally only.

What is the best way to do this?

Security issues are not relevant.

I'm sorry for the bad english, I'm not a native speaker.

Hope you can help me!




What are the dimensions of safari mobile view with the url bar?

I've seen countless posts on SO but not one concrete answer. I already know when typing window.innerwidth in the console, it gives you the width of the view, assuming the URL bar isn't taken in account.

This time I want to take into account the URL bar. What's a good way to find out the dimensions of iOS mobile devices with the URL bar showing in Safari?




How to cast a whole html body with .CSV format to an Excel sheet with VBA

How to grab the whole body of an html document accessed through a macro with IE as an object.

I have a working VB code that goes into an internal enterprise site and pulls a report as expected, the problem is that the report is a .CSV table in the HTML body, nothing else, only the table, I guess for security matters there's no download button (as a matter of fact this .csv format only works with admin privileges, a radio button is checked for .csv report to be displayed), so, the idea is that the macro goes into the report, creates the report and then grabs this info and puts it in a sheet on range A1.

The url looks like this:

http://teamadmin.mycompany.com/teams/repmemc.php?mode=1&group=Team&format=csv&attr%5B%5D=uid&attr%5B%5D=mail&attr%5B%5D=givenname&attr%5B%5D=sn

If I use the tool: DATA>From Web it works fine and gets the csv into the sheet, but when I try to automatize I no positive results.

The html code of the website containing the table looks like this:

<html>
<head></head>
<body>
</br>
"Saxon, Joseph",123,jsaxon@mycompany.com,Joseph,Saxon
</br>
"Carillo, Yul",456,ycarillo@mycompany.com,Yul,Carillo
</br>
"wilmier, omuaus",789,owilimier@mycompany.com,Omaus,Wilmier
</br>
"Kelly, Brandon",101,bkelly@mycompany.com,Brandon,Kelly
</br>
"Skien, Thomas",112,tskien@mycompany.com,Thomas,Skien
</br>
"Pereis, Adriano",131,apereis@mycompany.com,Adriano,Pereis
</br>
"Lans, Carinemer",411,clans@mycompany.com,Carinemer,Lans
</br>
"Sampson, Odimi",511,osampson@mycompany.com,Odimi, Sampson
</br>
</body>
</html>




Are get request with body allowed on AWS? 403 error

I published an API to AWS with Visual Studio, for now I am testing the methods with postman, but all get methods that require a body are returning an error that mentions cloudfront in the response, I do not know if the issue is related to cloudfront or if is the AWS HTTP 1.1 specification implementation that does not allow get requests with body:

Note:Get request with body were a requirement from our client

RFC 7231 HTTP/1.1 specification says the following: A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

    <HEAD>
        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
        <TITLE>ERROR: The request could not be satisfied</TITLE>
    </HEAD>
    <BODY>
        <H1>403 ERROR</H1>
        <H2>The request could not be satisfied.</H2>
        <HR noshade size="1px">
Bad request.


        <BR clear="all">
        <HR noshade size="1px">
        <PRE>
Generated by cloudfront (CloudFront)
Request ID:
</PRE>
        <ADDRESS></ADDRESS>
    </BODY>
</HTML>

so my questions are:

  1. are get request with body allowed in AWS?
  2. How AWS deals with get request with body?
  3. is there a way to use get methods with body on AWS?

I saw almost the same question here:AWS GET request with body rejected by CloudFront

and they point to this document: https://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-lambda-non-proxy-integration.html that says if you send a get request with body it returns a 400 error, but the error I am getting is 403 error

so could you clarify a little bit more? or could you point to an amazon document that mentions the restrictions on get requests?

Many Thanks




How the server knows which website is required by the client?

While accessing a website, how the server knows which website i need to access.

Please do not provide me external links, thank you.




Sending data to web by connected to Mac Address of Esp8266

I know the Mac address of my esp8266 but i don't need to send it through esp8266 ip address. i need to connect to the server through esp8266 mac address. so every time i don't want to manually change the ip address and burn the code.

const char server[] = "192.168.43.189"; 

I need that my server string should use mac address rather than ip address and can communicate with web.

this line connect esp8266 to the server: if (client.connect(server, 80))

    #include <SPI.h>
    #include <MFRC522.h>
    #include "ESP8266WiFi.h"

    constexpr uint8_t RST_PIN = 0;          // Configurable, see typical pin 
    layout above
    constexpr uint8_t SS_PIN = 15;         // Configurable, see typical pin 
    layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    const char server[] = "192.168.43.189"; 

    const char* MY_SSID = "project";
    const char* MY_PWD =  "12345678";

    WiFiClient client;

    unsigned long getID(){
    if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial 
    and continue
    return -1;
    }
    unsigned long hex_num;
    hex_num =  mfrc522.uid.uidByte[0] << 24;
    hex_num += mfrc522.uid.uidByte[1] << 16;
    hex_num += mfrc522.uid.uidByte[2] <<  8;
    hex_num += mfrc522.uid.uidByte[3];
    mfrc522.PICC_HaltA(); // Stop reading
    return hex_num;
    }


    void setup() {
     Serial.begin(115200);   // Initialize serial communications with the PC
     while (!Serial);    // Do nothing if no serial port is opened (added 
     for Arduinos based on ATMEGA32U4)
     SPI.begin();      // Init SPI bus
     mfrc522.PCD_Init();   // Init MFRC522
     mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 
     Card Reader details
     Serial.println(F("Scan PICC to see UID, SAK, type, and data 
     blocks..."));
     Serial.print("Connecting to "+*MY_SSID);
     WiFi.begin(MY_SSID, MY_PWD);
     Serial.println("going into wl connect");

     while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to 
     connect
      {
        delay(1000);
        Serial.print(".");
      }
      Serial.println("wl connected");
      Serial.println("");
      Serial.println("Credentials accepted! Connected to wifi\n ");
      Serial.println("");


      if(mfrc522.PICC_IsNewCardPresent()) {
       unsigned long uid = getID();
       if(uid != -1){
        Serial.print("Card detected, UID: "); 
        Serial.println(uid);
        // if you get a connection, report back via serial:
         if (client.connect(server, 80)) {
           Serial.println("connected");
           // Make a HTTP request:
          client.println("GET 
                    /Embedded_System/EmbeddedSystem/EmbeddedSystem/match.php HTTP/1.1");
          client.println("Host: 192.168.43.189");
          client.println("Connection: close");
          client.println();
    }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
    }
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    if(c == 1){
      Serial.print("1");
    } else {
      Serial.print("2");
    }
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}




Simply Hosting Files with Java

I am searching for a simple solution in java, and am afraid I am just not using the right terminology for it.

I have a directory of MP3 files I want to make available through my server. SO if I went to "localhost:1000/track1.mp3" i would be able to access that file.

In the past I have used Flask with python, and basically have been able to make entire file directories available through localhost, allowing me to go into sub directories such as : localhost:8000/subdir1/file.mp3". etc.

Does that make sense? Is there a simple solution to do this? I have been struggling to find one.




How to write "K extends keyof T" in a generic class and use K then

I want to create a class, which gets an object as type parameter and then uses the type as a type of a property in that class, so that I can only set and get values, if that key exists in that object.

I create an interface, lets call it IStorage. A class Storage should implement iStorage and store values based on if the key exists in the given object.

interface iStorage<T, K extends keyof T> {
    getField(k: K): T[K];

    setField(k: K, v: string | number | object): T[K];

    render(): void;
}

class Storage<T, K extends keyof T> implements iStorage<T, K> {
    private fields: { [key: K]: string | number | object };

    public getField(k: K): T[k] {
        return this.fields[k];
    }

    public setField(k: K, v: string | number | object): T[k] {
        return (this.fields[k] = v);
    }
}


let storage = new Storage<{name: string, type: number}>();


I want fields in Storage to match the the generic defintion (I think T[K]), but typescript says that key must be of type string or number, so this is not working as expected. In my interface I would like to say, that the second parameter of setFormField is also T[K]. I also think, that my type definition is repetitive. Typescript wants me to give a seconds argument too, which makes sense to me, but I don't want to write K extends keyof T everytime on a function, nor could I then use it as a property type.

Tried quiet a lot, but couldn't get it to work.. I'm a bit lost actually, since I'm trying this for several hours now. Never had to do with generics before, so please be gentle on me. :D

Hope someone could give me a helping hand.




What is the best approach to make an website like JSBin or JSFiddle? [on hold]

I am an app developer looking to expand into web development. For my first project, I want to make a site like JSBin or JSFiddle.

I know how to make the front end of this app, but I have a few questions about the backend.

The main problem I have is how can do you do the compiling in real time? Do I need a server to do this? I want my app to run in real time.

The second question is how would I format the text to show colors for HTML, CSS and Javascript. Is there a library or a way of doing this?

What would the best framework be for front end in this case? There are lots and what do JSBin and JSFiddle use?

Lastly, as an app developer, I am all about clean code and efficient projects. Xcode usually does the work for me. What are some good tips to make this project clean and efficient from a web developers point of view?

Thanks for your time.




Is there a way to control where to download files from the website on android phone?

So I'm building a website with react which downloads mp3 files.Downloading is working on pc and android. The problem is the mp3 file gets stored in "storage/emulated/0" on android and can't detect it with audio players.

The song can be played in "storage/emulated/0".




I need to implement a giveaway on my website with custom action tracking

I need to implement a giveaway in a Wordpress website (and later in an android/ios app).
I know I can use services like gleam.io but I need some custom action tracking. The difficult part is that I need to track if a user is listening to the radio on my website (for example: 1 hour of listening equals 1 entry per day).

Do you know if there is any online service that lets me keep track of the users and track actions with custom code? I tried emailing most of the services like gleam and kingsumo but I'm not getting affermative answers. If I need to build this by scratch, do you know if there is any example of code (maybe on GitHub) where I can see how a giveaway system is implemented?




How to open PDF Document programatically without saving it?

I have PDF document saved into my PDFs folder. I have created one function whose duty is to load the PDF into PdfDocument class, add some styles on runtime, save it back as temporary file and preview it in WebClient. My logic is working absolutely fine. I want to eliminate saving it back as temporary file. I want to directly preview it without saving, is it possible? I searched online but didn't get any good source. Following is my code:

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("MyFile.pdf");
pdf.SaveToFile("ModifiedMyFile.pdf"); // Eliminate this part
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData("ModifiedMyFile.pdf");
if (FileBuffer != null)
{
  Response.ContentType = "application/pdf";
  Response.AddHeader("content-length", FileBuffer.Length.ToString());
  Response.BinaryWrite(FileBuffer);
}




How to tell ubuntu to run __init__.py instead of index.html on homepage

So I am learning Python Web programming using Putty and Flask. I have set up server and did some Flask backened set up. I have created __init__.py file with "Hello World" as a test. So If I open my website address in browser I should see simple Hello World. But when I open my website it shows content that is inside index.html file.

Here's the code for my __init__.py file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def homepage():
    return "Hello World"

if __name__ =="__main__":
    app.run()

Code for flaskapp.conf

<VirtualHost *:80>
    ServerName *****website.com
    ServerAdmin ***********
    ServerAlias www.*****website.com
    WSGIScriptAlias / /var/www/flaskapp/flaskapp.wsgi
    <Directory /var/www/flaskapp/flaskapp/>
        Order allow,deny
        Allow from all
    </Directory>
    Alias /static /var/www/flaskapp/flaskapp/static
    <Directory /var/www/flaskapp/flaskapp/static/>
        Order allow,deny
        Allow from all
    </Directory> 


    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined


</VirtualHost>

code in flaskapp.wsgi

#!/usr/bin/python

import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/flaskapp")
from Flaskapp import app as application
application.secret_key = '*********'



If you need any other information please let me know.

Any help will be much appreciated, thank you




Can somebody tell why I'm getting this URL is crawled more than other pages?

I checked the web stats of my site and seeing specific URL getting more hits than the other.

I just scan the site trying to find out the location but file not exist.

{"version":"1.0","provider_name":"Pragmatic Web Media","provider_url":"https://pragmaticwebmedia.com","title":"How to Add ClickTag in HTML5?","type":"rich","width":600,"height":338,"html":"How to Add ClickTag in HTML5?</a></blockquote>\n\n1e3)g=1e3;else if(~~g<200)g=200;f.height=g}if(\"link\"===d.message)if(h=b.createElement(\"a\"),i=b.createElement(\"a\"),h.href=f.getAttribute(\"src\"),i.href=d.value,i.host===h.host)if(b.activeElement===f)a.top.location.href=d.value}else;}},d)a.addEventListener(\"message\",a.wp.receiveEmbedMessage,!1),b.addEventListener(\"DOMContentLoaded\",c,!1),a.addEventListener(\"load\",c,!1)}(window,document);\n\/\/-->\n</script></iframe>","thumbnail_url":"https://pragmaticwebmedia.com/wp-content/uploads/2018/01/Clicktag-768x432-768x432.jpg","thumbnail_width":600,"thumbnail_height":338}

Need to understand what that means?. Is this malware injection?




dimanche 28 avril 2019

How to set a larger size for an element inside the code

I have a sidebar, I need to remove this sidebar when I remove the mouse from this sidebar.

At the moment it is removed when I move the mouse away from it, but I need it to be removed when I move the mouse away from it + 100 pixels to the right, but I don’t want to add 100 pixels to its width, I want it all to be left only inside the js code and does not reflect inside html.

I tried to do it like this: $(".group-side-context").offset().right + 100px

if($(".group-side-context").mouseover){
$(".group-side-context").mouseleave(function(){
    $(this).parent().removeClass("context-sidebar-active").addClass("context-sidebar-close").removeClass("context-sidebar-close").addClass("context-sidebar");
  })
};




How can users upload a post to our website - like with instagram

We are setting up a food social media website - where users upload a recipe to our website as a post - like how people upload posts to Instagram.

We have tried saving all of the forms submissions into an HTML page use document.write just now we need that to appear on our website with all of the other posts

function getcode() {
  var nameinput = document.getElementById("name").value;
  document.getElementById("name1").innerHTML = nameinput;

  var ingreinput = document.getElementById("ingre").value;
  document.getElementById("ingre1").innerHTML = ingreinput;
}
<form id="form" onsubmit="return false;">
  <input type="text" placeholder="Name" id="name">
  <input type="text" placeholder="Ingredients" id="ingre">
  <input type="submit" onclick="getcode();" />
</form>


<p id="name1"></p>
<p id="ingre1"></p>



Can someone convert this arrow function into Normal function?

I am unable to convert this arrow function into Normal function. I have tested this in the console panel of the chrome. This code was taken from freecodeCamp.org in the Es6 lesson

//This is what I have tried. The final output result is showing undefined


const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = function(arr) {
    "use strict";
    const squaredIntegers = function(num) {
        (function() {
            arr.filter(Number.isInteger(num) && num > 0);
        });       
        return squaredIntegers;
    } 
}

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

//Here is the Arrow function I was trying to convert

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
    "use strict";
    const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0);
    return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);


//The code should output this
[4, 42, 6];




HTTP Audio Stream redistribution

I am interested in re-distribution of HTTP stream to LAN HTTP clients which will be downloaded from a WAN based streaming source. I don't want all the LAN client to make a WAN call and consume the bandwidth for the same stream. An alternative would be to write a stream client and act as a server as manage the subscription of all the client requests coming from local clients and distribute the incoming chunks downloaded to all the subscribers. But wondering if there is some existing util/lib which could help me with this.




How do I put a Server class on my website so my Client class can communicate with it from different computers?

I have a server client application working just how I want it locally. I need to get the server online so the client program can be used from different computers. Not sure how to do this. I have my own website that I thought I could just put the Server on in the background.

Is this possible or am I just looking at this the wrong way.

Server.java

package core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;



import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws IOException {

        ArrayList<ClientHandler> clients = new ArrayList<>();
        ServerSocket serverSocket = null;
        int clientNum = 1; // keeps track of how many clients were created

        // 1. CREATE A NEW SERVERSOCKET
        try {
            serverSocket = new ServerSocket(4444); // provide MYSERVICE at port
                                                    // 4444
        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            System.exit(-1);
        }

        // 2. LOOP FOREVER - SERVER IS ALWAYS WAITING TO PROVIDE SERVICE!
        while (true) {
            Socket clientSocket = null;
            try {

                // 2.1 WAIT FOR CLIENT TO TRY TO CONNECT TO SERVER
                System.out.println("Waiting for client " + clientNum + " to connect!");
                clientSocket = serverSocket.accept();
                clientNum++;
                ClientHandler c = new ClientHandler(clientSocket, clients);
                clients.add(c);
                // 2.2 SPAWN A THREAD TO HANDLE CLIENT REQUEST
                Thread t = new Thread(c);
                t.start();

            } catch (IOException e) {
                System.out.println("Accept failed: 4444");
                System.exit(-1);
            }

            // 2.3 GO BACK TO WAITING FOR OTHER CLIENTS
            // (While the thread that was created handles the connected client's
            // request)

        } // end while loop

    } // end of main method

} // end of class MyServer

class ClientHandler implements Runnable {
    Socket s; // this is socket on the server side that connects to the CLIENT
    ArrayList<ClientHandler> others;
    Scanner in;
    PrintWriter out;

    ClientHandler(Socket s, ArrayList<ClientHandler> others) throws IOException {
        this.s = s;
        this.others = others;
        in = new Scanner(s.getInputStream());
        out = new PrintWriter(s.getOutputStream());
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        // 1. USE THE SOCKET TO READ WHAT THE CLIENT IS SENDING
        while (true) {
            String clientMessage = in.nextLine();
            // System.out.println(clientMessage);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try (PrintWriter fileWriter = new PrintWriter(new FileOutputStream(new File("chat.txt"), true));) {
                        fileWriter.println(clientMessage);
                        fileWriter.close();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    // System.out.println(others.size());
                    for (ClientHandler c : others) {
                        // System.out.println(c.toString());
                        c.sendMessage(clientMessage);
                    }

                }
            }).start();
        }
    }

    private void sendMessage(String str) {
        out.println(str);
        out.flush();
    }
} // end of class ClientHandler

ClientSide.java

package core;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;

/**
 * @author tywemc
 *
 */
public class ClientLogin extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ClientLogin frame = new ClientLogin();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ClientLogin() {
        setTitle("Login Page");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 300, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(59, 167, 171, 25);
        contentPane.add(textField);
        textField.setColumns(10);

        JLabel lblClient = new JLabel("Client");
        lblClient.setFont(new Font("Arial Black", Font.BOLD, 34));
        lblClient.setBounds(36, 35, 171, 54);
        contentPane.add(lblClient);

        JLabel loginLabel = new JLabel("Enter your name:");
        loginLabel.setFont(new Font("Times New Roman", Font.PLAIN, 22));
        loginLabel.setBounds(10, 118, 197, 38);
        contentPane.add(loginLabel);

        JButton btnLogin = new JButton("Login");
        btnLogin.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                ClientSide client = new ClientSide(textField.getText());
                client.setVisible(true);
            }

        });
        btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnLogin.setBounds(83, 205, 89, 23);
        contentPane.add(btnLogin);
    }
}




storing user locally html and json connection

enter code herehelp with the following requirement out of the files shared. to create two separated forms. Each form should correspond to one of the tasks of registering and logging in. You should use localStorage object to store users. Users can register using a unique email address (that is not already saved in the system). For the registration, you must ask twice for the password and check if they match. Users must be redirected to the main page after a successful registration (using window.location.href). If someone try to register using an email address that is already saved in the system, you should generate an appropriate error message and show it to the user so they can enter another email. In the case of password mismatch, an appropriate error message should be generated for the user. Use Bootstrap to create the Register/Login page. You’re free to use any class from Bootstrap such as Modals, Panels, or simply two columns in a row. Remember that after a successful register or login, user must be redirected to the main page. An entry containing the email address of this user must be passed to the main page (using local storage) to keep track of each user individually.




HTTP status code 304 when using Cloudflare

Is it usefull to set the HTTP status code to 304 on the webserver when using the caching of Cloudflare?




How can I make content behind a partly transparent navbar disappear?

I have a partly transparent navbar on top of my page:

.navbar {
  position: sticky;
  top: 0;
  width: 100%;
  z-index: 999;
  background-color: rgba(212, 0, 255,0.3);
}

The background of the page is a canvas.

The problem is that when i scroll down, the content doesn't disappear behind my navbar because the navbar is partly transparent. I only want the page background and the navbar show up in the navbar area and not the content




What NPM dependencies are required for modular Vue?

I am new to modern web development. I am currently learning Vue JS (the latest version) and I have watched some tutorial videos online. The videos teach Vue JS using a plain HTML + <script> setup instead of a project setup created by a Vue CLI program.

Now, I would like to know what NPM dependencies in the package.json file are required to change a project setup from a single HTML + Vue CDN script src to one with a folder structure set up by vue-cli, just like modern project folder structure created by other CLIs, e.g. Angular and React.

After running vue init <template name> I get a package.json like the following:

{
    ...,
    "scripts": {
      "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
      "start": "npm run dev",
      "lint": "eslint --ext .js,.vue src",
      "build": "node build/build.js"
    },
    "dependencies": {
      "vue": "^2.5.2",
      "vue-router": "^3.0.1"
    },
    "devDependencies": {
      "autoprefixer": "^7.1.2",
      "babel-core": "^6.22.1",
      "babel-eslint": "^8.2.1",
      "babel-helper-vue-jsx-merge-props": "^2.0.3",
      "babel-loader": "^7.1.1",
      "babel-plugin-syntax-jsx": "^6.18.0",
      "babel-plugin-transform-runtime": "^6.22.0",
      "babel-plugin-transform-vue-jsx": "^3.5.0",
      "babel-preset-env": "^1.3.2",
      "babel-preset-stage-2": "^6.22.0",
      "chalk": "^2.0.1",
      "copy-webpack-plugin": "^4.0.1",
      "css-loader": "^0.28.0",
      "eslint": "^4.15.0",
      "eslint-config-standard": "^10.2.1",
      "eslint-friendly-formatter": "^3.0.0",
      "eslint-loader": "^1.7.1",
      "eslint-plugin-import": "^2.7.0",
      "eslint-plugin-node": "^5.2.0",
      "eslint-plugin-promise": "^3.4.0",
      "eslint-plugin-standard": "^3.0.1",
      "eslint-plugin-vue": "^4.0.0",
      "extract-text-webpack-plugin": "^3.0.0",
      "file-loader": "^1.1.4",
      "friendly-errors-webpack-plugin": "^1.6.1",
      "html-webpack-plugin": "^2.30.1",
      "node-notifier": "^5.1.2",
      "optimize-css-assets-webpack-plugin": "^3.2.0",
      "ora": "^1.2.0",
      "portfinder": "^1.0.13",
      "postcss-import": "^11.0.0",
      "postcss-loader": "^2.0.8",
      "postcss-url": "^7.2.1",
      "rimraf": "^2.6.0",
      "semver": "^5.3.0",
      "shelljs": "^0.7.6",
      "uglifyjs-webpack-plugin": "^1.1.1",
      "url-loader": "^0.5.8",
      "vue-loader": "^13.3.0",
      "vue-style-loader": "^3.0.1",
      "vue-template-compiler": "^2.5.2",
      "webpack": "^3.6.0",
      "webpack-bundle-analyzer": "^2.9.0",
      "webpack-dev-server": "^2.9.1",
      "webpack-merge": "^4.1.0"
    },
    "engines": {
      "node": ">= 6.0.0",
      "npm": ">= 3.0.0"
    },
    "browserslist": [
      "> 1%",
      "last 2 versions",
      "not ie <= 8"
    ]
}

In this NPM project, it is not required to have a <script src> CDN link So which of the above dependencies are needed?

In Vue's official documentation, it states that:

The Installation page provides more options of installing Vue. Note: We do not recommend that beginners start with vue-cli, especially if you are not yet familiar with Node.js-based build tools.

May I know what dependencies do the job (or if it is the nature of a Node.js project, it is born this way) and any documentation or quotes from developers that are easy to understand for web dev newbies like me?




Bootstrap modal freezes page after modal hide

I have a button on page to open a modal:

<button data-toggle="modal" data-target="#connProductsModal" type="button" class="btn btn-brand"><%= GetGlobalResourceObject("ButtonText", "BTN_EDIT_PRODUCTS") %></button>

this opens following modal:

<div class="modal fade" id="connProductsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <asp:UpdatePanel runat="server" ID="udpEditConnProd">
                    <ContentTemplate>
                        <telerik:RadGrid ID="gvEditConnectedProducts" runat="server" AllowMultiRowSelection="True" RenderMode="Lightweight" Skin="Material" PageSize="25" BorderWidth="0" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="False">
                            <GroupingSettings CollapseAllTooltip="Collapse all groups"></GroupingSettings>
                            <ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True" EnableRowHoverStyle="True">
                            </ClientSettings>
                            <MasterTableView DataKeyNames="ProductId">
                                <Columns>
                                    <telerik:GridTemplateColumn UniqueName="CheckBoxTemplateColumn">
                                        <HeaderStyle CssClass="myGridHeader" />
                                        <ItemTemplate>
                                            <label class="k-checkbox k-checkbox--brand">
                                                <asp:CheckBox runat="server" ID="cbSelectedItem" AutoPostBack="True" OnCheckedChanged="ToggleRowSelection" />
                                                <span></span>
                                            </label>
                                        </ItemTemplate>
                                        <HeaderTemplate>
                                            <label class="k-checkbox k-checkbox--brand">
                                                <asp:CheckBox runat="server" ID="headerCheckbox" AutoPostBack="True" OnCheckedChanged="ToggleSelectedState" />
                                                <span></span>
                                            </label>
                                        </HeaderTemplate>
                                        <ItemStyle Width="25px" />
                                    </telerik:GridTemplateColumn>
                                    <telerik:GridBoundColumn DataField="ProductCode" HeaderText="<%$ resources: PRODUCT_GRID_CODE %>" UniqueName="Address" Visible="True">
                                        <HeaderStyle CssClass="myGridHeader" />
                                    </telerik:GridBoundColumn>
                                    <telerik:GridBoundColumn DataField="ProductName" HeaderText="<%$ resources: PRODUCT_GRID_NAME %>" UniqueName="first_name" Visible="True">
                                        <HeaderStyle CssClass="myGridHeader" />
                                    </telerik:GridBoundColumn>
                                    <telerik:GridBoundColumn DataField="ProductNumber" HeaderText="<%$ resources: PRODUCT_GRID_NUMBER %>" UniqueName="Address" Visible="True">
                                        <HeaderStyle CssClass="myGridHeader" />
                                    </telerik:GridBoundColumn>
                                </Columns>
                            </MasterTableView>
                        </telerik:RadGrid>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <asp:LinkButton runat="server" ID="btnAddSelectedProducts" OnClick="btnAddSelectedProducts_OnClick" class="btn btn-brand"><%= GetGlobalResourceObject("ButtonText", "BTN_UPDATE") %></asp:LinkButton>
            </div>

        </div>
    </div>
</div>

when I press "Save" in modal it should update a grind inside a update panel with conditional update mode. The trigger is the save button in the modal.

This works...but the modal will not close after the method is done.. I use this in code behind to "hide" the modal, witch works..

 ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$('#connProductsModal').modal('hide');", true);

but then the page (all java-script functions) freezes :/ If I skip the "hide" function everything works as it should but the modal does not close.

Any idea?




How to set web template variable to a dynamic html&golang code?

I have two web page on golang and I want to embed this pages codes to variable (defined in templates/main.html) being with dynamic according to the coming requests.

For example if the guest enter the userregister page I want to the variable will be userregister codes otherwise userprofile codes.

templates/userregister.html page codes;


   ...
   
   ...


templates/userprofile.html page codes;


   ...
   
   ...


templates/main.html;


<!DOCTYPE html>
<html lang="tr">
    
    <body>
        <div class="container-fluid">
            
            <div class="row">
                <nav class="col-12 col-md-2 p-0">
                    
                </nav>
                <div class="container-fluid col-12 col-md-10">


                    


                </div>
            </div>
            
        </div>
    </body>
</html>


The userregister page controller;

func PgUserRegister(c *gin.Context) {
    c.HTML(http.StatusOK,"main", gin.H{
        "pgETitle": "User Register page",
        "specialmessage": "You are on the userregister page.",

        "content": template.ParseFiles("userregister.html"),
    })
}

The userprofile page controller;

func PgUserProfile(c *gin.Context) {
    c.HTML(http.StatusOK,"main", gin.H{
        "pgETitle": "User Profile",
        "specialmessage": "You are on the userprofile page.",

        "content": template.ParseFiles("userprofile.html"),
    })
}




Angular ngClass/ngIf not rerendering on changes

I'm working on an Angular project where I need to have one class or another depending on a variable (and they have to change live, without refreshing).

I tried using *ngIf/else and [ngClass]and they do work but they do not re-render. They only work when I refresh the website

Using *ngIf/else:

<i
 *ngIf="favSongs.includes(track.id); else plus"
 (click)="setToFav(track.id)"
 class="fa fa-check"
></i>
<ng-template #plus>
  <i (click)="setToFav(track.id)" class="fa fa-plus"></i>
</ng-template>

Using [ngClass]:

<i
  (click)="setToFav(track.id)"
  [ngClass]="{'fa fa-check': favSongs.includes(track.id), 
  'fa fa-plus': !favSongs.includes(track.id)}"
></i>

As said before, it does work but only when you refresh. I'm looking for something like React, when you update the class the component get re-rendered.




How to get none sued by copyrights?

Where to start??

So, first of all is to make the internet connection already bought from internet service provider that not have access on their company devices [offline], and ip address, web browser applications, also make it's sharing text, audio, video, game...etc, under privately options and add chats too... next making sure doesn't directly to the directives; lawyers, beacuse it will be under any attacks... also social media too can be done with it plus add some code password to gain extra support on the file you've sharing... in all mean time you do the contactings u.s. court about distributings and discuss if it is ok or not, be sure correctly fill up takedowns and both google & microsoft allowence to store (not view) code passwords papers, just anything to be on safest yearly side...




Same margin both sides, still does not look centered

Trying to set a nav bar centered, but imo it looks closer to the left side than to the right.

I am giving it a width and half of the remaining one as left side margin, but does not change. I ser margin of the elements to 0 in case it might affect, and same to the padding. Does anyone have an idea if there is an element with margin i am not counting on? Thanks

nav{
    display: block;
    width: 50%;
    padding: 0;
    margin-left: 25vw;
    margin-top: 5vh;
    margin: auto;
}




What's the difference between form button-link and js button-link?

What's the difference between these two ways to turn button into a link:

<form method="GET" action="example.com">                
<button type="submit">button text</button>
</form>

VS

<button onclick="location.href = 'example.com';">button text</button>

It has the same effect but is there any flaws of usage one of ways?




How do I find my HTML code after I run Out-File on Powershell?

I accidently run Out-File index.html which removes my html code from the PC. I have no backup and I want my code back.The command which I type

Kindly help me to get my code back.

Outpuut on Web Browser




samedi 27 avril 2019

Can I host my app and my website on my google drive just like a normal hosting website

I intend to make an app and a website for the same. My question is can I use my google drive as a storage solution for both. I have unlimited google drive storage provided by my university can I use it to host my app and website. My app will allow users to send notes in pdf,photographs,notices which will take considerable storage space hence can I use my google drive to store all of the files.

I have tried to google about it but wasn't able to get any concrete answers.




Is there some way though php which will display a picture detail on click out of list of a pictures?

I'm doing a php assignment and having very basic knowledge previously of php. I 'm looping through a list of pictures from S3 but after looping through I want a selected picture to be opened on click. I'm clueless that how will it further proceed

I've a product.php page which has to redirect to single .php




Why is splash not rendering entire SemanticScholar search query result webpage?

I am trying to use splash to render a search query in SemanticScholar. This was my HTTP request to a dockerized installation of splash. However, it doesn't fully render the webpage (see below). Specifically, the list of publications are never displayed. What could the issue be?

http://127.0.0.1:8050/info?wait=0.5&images=1&expand=1&timeout=90.0&url=https%3A%2F%2Fwww.semanticscholar.org%2Fsearch%3Fq%3DAmplification%2520Hell%253A%2520Revisiting%2520Network%2520Protocols%2520for%2520DDoS%2520Abuse.%26sort%3Drelevance&lua_source=function+main%28splash%2C+args%29%0D%0A++assert%28splash%3Ago%28args.url%29%29%0D%0A++assert%28splash%3Await%280.5%29%29%0D%0A++return+%7B%0D%0A++++html+%3D+splash%3Ahtml%28%29%2C%0D%0A++++png+%3D+splash%3Apng%28%29%2C%0D%0A++++har+%3D+splash%3Ahar%28%29%2C%0D%0A++%7D%0D%0Aend

enter image description here




How to read and update a specific field data

I'm doing a small pos system and i want to update the database when I add quantity to an existing item. To do that i need to read the current quantity of that item and then add the new quantity to that value and save data. How can I do that?

this is by sample db:-

Items -LcvTOFQvltop-X8ktBV itemCode:"sc001" itemName:"Nokia 1100" itemPrice:"3500.00" quantity:"7"

for example if I want to add 3 more of this item to the stock I want to update the quantity as 10




installing WHMCS on a Django website gives error page not found

am trying to install whmcs on my django website in a directory www.mysite.com/billing but after installing it and going to the urlmysite.com/billing

returns 404 page not found. Is there a way to add the billing URL inside urls.py

and install it to work successfully. help .




Making a Navigation like shown, I don't know how to go about this

So I need help making this navigation. https://imgur.com/p2HEO60 it's on the side. I'm not sure how to go about this. I'm assuming I make objects with CSS and then some sort of animation?? If someone can please explain how to I should do it, I would be greatful. Thanks!




Calling one page in another makes website slow?

I am making a website where I have to keep track of logged in users. So in every php document I have written code to connect to database. If I write the database connecting code in one php document and call it in other php documents, will it make my page slow?

Instead of putting all features in one page, what if I design features in different pages and call all features in one page? Will it slow down loading speed of website?




Tensorflowjs works in our web application browser but not in mobile web browser

I have build a working functioning tensforflow.js web application and deployed to Firebase. However, when I go to website on my phone, the camera does not respond when capturing and image as well as throwing an error: Any guidance to troubleshoot this problem is a appreciated. Thanks




Trying to run tensorflow.js in mobile browser and running into WebGL issue

Tensorflowjs works in our web browser but not in mobile web browser. Any help is Uncaught (in promise) Error: Unable to create WebGL Texture tf-core.esm.js:4675




Architecture for notification or announcement system for web application

I have a dashboard for employees, I want to make announcement or notification system where admin can easily send information or update. I can easily achieve it by showing banner with title of the announcement and "Click here" button at the end that will open model/pop-up with Detail of the announcement. This is an easy to implement solution but it will create problem when there are multiple announcements going on at the same time.

Alternate to this is a notification system like Facebook or Stackoverflow. This solution is scalable as we can add more types of notifications like system generated. I am looking for both UX and code architecture suggestions. I am up for firebase, mysql, DynamoDB or any other option. Please suggest what is the best architecture for the same.

Below are the key features:

  1. Scalable

  2. Admin can send announcement to all users, to specific team or a specific user.

  3. Clicking on the notification may open model/popup or a link.

  4. Obviously has the count of new notifications/announcement for each user.




Can we replace ASP.NET MVC with ASP.NET Web API

I am new to the ASP.NET Web API and while learning, a question comes in mind that can i replace ASP.NET MVC with ASP.NET WEB API .For instance let's say I am creating small application by using below technologies.

UI Will be in : ASP.NET/HTML Controls, JavaScript,CSS. Server side code : ASP.NET MVC. Back End : SQL Server.

Now Can i use WEB API instead of ASP.NET MVC and my new stack will be like

UI : HTML , JavaScript,CSS. Server side code: ASP.NET WEB API. Back End : SQL Server.




C# Web exception unexpected EOF

I am attempting to download a json web page from imdb to find an actor.

        try
        {
            using (WebClient wc = new WebClient())
            {
                string content = wc.DownloadString("https://v2.sg.media-imdb.com/suggests/names/b/brad.json");
            }
        }
        catch (WebException x)
        {
            x.ToString();
        }

Whenever I attempt to make the download.

The exception given is:

The underlying connection was closed: An unexpected error occurred on a send.

And the inner web exception is:

Received an unexpected EOF or 0 bytes from the transport stream.

From what I've read. This happens because one of imdb's servers is misconfigured.

To try and solve this, I used

System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(3072);

To set the security protocol to Tls12 which does solve the issue on my PC.

However, when I try to use it on my second PC. That line throws the exception:

System.NotSupported: The requested security protocol is not supported

Which I assume means that it doesn't have tls12 support on that PC.

I have the .NET Framework 4.5.1 installed on that PC and I cannot install .NET Framework 4.7 because it fails in the installation.

I assume the security protocol comes with 4.7, but I don't see that confirmed on MSDN.

How can I get the web page to download on this second PC?

Is there a way for me to manually install the Tls12 protocol?

Is there an alternative using HttpWebRequest or some standalone executable instead?




Redirect on spring boot

I wrote login system on spring-boot but there is a problem when I want to login, spring take login and password from form but cannot redirect to the account page.

Controller

Error

 @PostMapping(value = "user/login")
public String login(Model model, HttpSession session, @RequestParam("login") String login, @RequestParam("password") String password) {
    try {
        User user = userService.checkLogin(login, password);
        if (user == null) {
            model.addAttribute("err", "Login Valid login and password");
            return "/login";
        } else {
            if (user.getRole().equals(userService.Role_Admin)) {
                userService.addUserInSession(user, session);

                return "/admin/account";
            } else if (user.getRole().equals(userService.Role_Student)) {
                userService.addUserInSession(user, session);
                return "/student/account";
            } else {
                model.addAttribute("err", "Invalid User Role");
                return "/login";
            }
        } } catch (UserException ex) {
        model.addAttribute("err", ex.getMessage());
        return "/login";
    }

}




I have a problem with my blogger site.When in my mobile mode

When I click on the point A the drop down menu appears, but when I tap on point B(see photo) it doesn't and appears but it redirects to a blank page.the photo link is attached

https://drive.google.com/file/d/1cCCO7XthdYpuLoStj-jqgFuc6Ckssubs/view

The Dropdown menu should also appear by clicking the text(JEE)

here is the XML code of my template

https://drive.google.com/open?id=1WTVVltq1ucpOnIRWW_qyw84y6w9VZBeE