Programs & Examples On #Apic

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Getting "Cannot call a class as a function" in my React Project

For me, it was because I'd accidentally deleted my render method !

I had a class with a componentWillReceiveProps method I didn't need anymore, immediately preceding a short render method. In my haste removing it, I accidentally removed the entire render method as well.

This was a PAIN to track down, as I was getting console errors pointing at comments in completely irrelevant files as being the "source" of the problem.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Override constructor of DbContext Try this :-

public DataContext(DbContextOptions<DataContext> option):base(option) {}

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

Forward X11 failed: Network error: Connection refused

Other answers are outdated, or incomplete, or simply don't work.

You need to also specify an X-11 server on the host machine to handle the launch of GUId programs. If the client is a Windows machine install Xming. If the client is a Linux machine install XQuartz.

Now suppose this is Windows connecting to Linux. In order to be able to launch X11 programs as well over putty do the following:

- Launch XMing on Windows client
- Launch Putty
    * Fill in basic options as you know in session category
    * Connection -> SSH -> X11
        -> Enable X11 forwarding
        -> X display location = :0.0
        -> MIT-Magic-Cookie-1
        -> X authority file for local display = point to the Xming.exe executable

Of course the ssh server should have permitted Desktop Sharing "Allow other user to view your desktop".

MobaXterm and other complete remote desktop programs work too.

Bootstrap 4 datapicker.js not included

Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html

It's a flexible datepicker widget in the Bootstrap style.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

The important part is this:

Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];

due to:

nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl

According to this log, Spring could not find your MemberPointSummaryDAOImpl class.

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).

SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I got the same problem and I have read that this happened in Samsung phones only...But the reality showed that this happens in a lot of brands.

After testing I realized that this happens only when you scroll fast the RecyclerView and then you go back either with the back button or the Up button. So I put inside Up button and onBackpressed the below snippet:

someList = new ArrayList<>();
mainRecyclerViewAdapter = new MainRecyclerViewAdapter(this, someList, this);
recyclerViewMain.setAdapter(mainRecyclerViewAdapter);
finish();

With this solution you just load a new Arraylist to the adapter and new adapter to recyclerView and then you finish activity.

Hope it helps someone

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

I was getting this error too and the reason ended up being wrong call url. I am leaving this answer here, if someone else happens to mix the urls and getting this error. Took me hours to realize I had wrong URL.

Error I got (HTTP code 400):

{
    "error": "unsupported_grant_type",
    "error_description": "grant type not supported"
}

I was calling:

https://MY_INSTANCE.lightning.force.com

While the correct URL would have been:

https://MY_INSTANCE.cs110.my.salesforce.com

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

I found this question because I was having issues with the OPTIONS request most browsers send. My app was routing the OPTIONS requests and using my IoC to construct lots of objects and some were throwing exceptions on this odd request type for various reasons.

Basically put in an ignore route for all OPTIONS requests if they are causing you problems:

var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "{*pathInfo}", constraints);

More info: Stop Web API processing OPTIONS requests

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

That problem happens when you try to access from a different domain or different port.

If you're using Visual Studio, then go to Tools > NuGet Package Manager > Package Manager Console. There you have to install the NuGet Package Microsoft.AspNet.WebApi.Cors

Install-Package Microsoft.AspNet.WebApi.Cors

Then, in PROJECT > App_Start > WebApiConfig, enable CORS

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        
        //Enable CORS. Note that the domain doesn't have / in the end.
        config.EnableCors(new EnableCorsAttribute("https://tiagoperes.eu",headers:"*",methods:"*"));

        ....

    }
}

Once installed successfully, build the solution and that should suffice

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

How to return a file (FileContentResult) in ASP.NET WebAPI

Instead of returning StreamContent as the Content, I can make it work with ByteArrayContent.

[HttpGet]
public HttpResponseMessage Generate()
{
    var stream = new MemoryStream();
    // processing the stream.

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.ToArray())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CertificationCard.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}

Make sure that the controller has a parameterless public constructor error

What's happening is that you're bitten by this problem. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.

You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.

But of course, the configuration error comes from you adding the second constructor to your DbContext. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.

So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the DbContext. DbContext is a special type that shouldn't be auto-wired. It is a framework type and you should therefore fallback to registering it using a factory delegate:

container.Register<DashboardDbContext>(
    new InjectionFactory(c => new DashboardDbContext())); 

Failed to serialize the response in Web API with Json

Just put following lines in global.asax:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Import

using System.Data.Entity;

Vagrant error : Failed to mount folders in Linux guest

vagrant plugin install vagrant-vbguest
vagrant destroy #clean rhel/yum repos
vagrant up

And on the config file:

config.vbguest.auto_update = false #important so that any changes to the base image don't affect on reload

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Disable password authentication for SSH

Run

service ssh restart

instead of

/etc/init.d/ssh restart

This might work.

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

None of these solutions worked for me. I had a tangle of Nuget packages that couldn't update because of circular dependencies on each other.

I would up having to fix this the old-fashioned way. I created a new MVC/web api project and manually copied System.Web.Http and System.Web.Http.WebHost from the new project into the Nuget folders of the exisitng solution. From there I updated the references by, OMG, "browsing" and fixed the problem.

How to pass json POST data to Web API method as an object?

Microsoft gave a good example of doing this:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

First validate the request

if (ModelState.IsValid)

and than use the serialized data.

Content = new StringContent(update.Status)

Here 'Status' is a field in the complex type. Serializing is done by .NET, no need to worry about that.

Web API Put Request generates an Http 405 Method Not Allowed error

You can remove webdav module manually from GUI for the particular in IIS.
1) Goto the IIs.
2) Goto the respective site.
3) Open "Handler Mappings"
4) Scroll downn and select WebDav module. Right click on it and delete it.

Note: this will also update your web.config of the web app.

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Enable CORS in Web API 2

CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfig Register method, have the following code:

    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
    

In the web.config, the following handler must be the first one in the pipeline:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!

ImportError: No module named apiclient.discovery

apiclient is not in the list of third party library supplied by the appengine runtime: http://developers.google.com/appengine/docs/python/tools/libraries27 .

You need to copy apiclient into your project directory & you need to copy these uritemplate & httplib2 too.

Note: Any third party library that are not supplied in the documentation list must copy to your appengine project directory

How to get the selected date value while using Bootstrap Datepicker?

Generally speaking,

$('#startdate').data('date') 

is best because

$('#startdate').val()

not work if you have a datepicker "inline"

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

To summarize the conversation in the comments:

  • There is no need to use simplejson library, the same library is included with Python as the json module.

  • There is no need to decode a response from UTF8 to unicode, the simplejson / json .loads() method can handle UTF8 encoded data natively.

  • pycurl has a very archaic API. Unless you have a specific requirement for using it, there are better choices.

requests offers the most friendly API, including JSON support. If you can, replace your call with:

import requests

return requests.get(url).json()

All ASP.NET Web API controllers return 404

I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.

Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.

POST string to ASP.NET Web Api application - returns null

i meet this problem, and find this article. http://www.jasonwatmore.com/post/2014/04/18/Post-a-simple-string-value-from-AngularJS-to-NET-Web-API.aspx

The solution I found was to simply wrap the string value in double quotes in your js post

works like a charm! FYI

Best practice to call ConfigureAwait for all server-side code

The biggest draw back I've found with using ConfigureAwait(false) is that the thread culture is reverted to the system default. If you've configured a culture e.g ...

<system.web>
    <globalization culture="en-AU" uiCulture="en-AU" />    
    ...

and you're hosting on a server whose culture is set to en-US, then you will find before ConfigureAwait(false) is called CultureInfo.CurrentCulture will return en-AU and after you will get en-US. i.e.

// CultureInfo.CurrentCulture ~ {en-AU}
await xxxx.ConfigureAwait(false);
// CultureInfo.CurrentCulture ~ {en-US}

If your application is doing anything which requires culture specific formatting of data, then you'll need to be mindful of this when using ConfigureAwait(false).

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

How to set downloading file name in ASP.NET Web API

If you want to ensure that the file name is properly encoded but also avoid the WebApi HttpResponseMessage you can use the following:

Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());

You may use either ContentDisposition or ContentDispositionHeaderValue. Calling ToString on an instance of either will do the encoding of file names for you.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

NOTE : this is just an abbreviation of this answer above

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Add the following class

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  4. Add Application_Start method if not there already (in global.asax.cs file)

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  5. Right click controllers folder > add new item > web > Add Web API controller

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }  
        }
    }
    

Optional query string parameters in ASP.NET Web API

Use initial default values for all parameters like below

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

User Authentication in ASP.NET Web API

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

That's because you are getting confused about these two concepts:

  • Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

    • Who is the user?
    • Is the user really who he/she represents himself to be?
  • Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

    • Is user X authorized to access resource R?
    • Is user X authorized to perform operation P?
    • Is user X authorized to perform operation P on resource R?

The Authorize attribute in MVC is used to apply access rules, for example:

 [System.Web.Http.Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

The above rule will allow only users in the Admin and Super User roles to access the method

These rules can also be set in the web.config file, using the location element. Example:

  <location path="Home/AdministratorsOnly">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

However, before those authorization rules are executed, you have to be authenticated to the current web site.

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

From here, we could split the problem in two:

  • Authenticate users when consuming the Web API services within the same Web application

    This would be the simplest approach, because you would rely on the Authentication in ASP.Net

    This is a simple example:

    Web.config

    <authentication mode="Forms">
      <forms
        protection="All"
        slidingExpiration="true"
        loginUrl="account/login"
        cookieless="UseCookies"
        enableCrossAppRedirects="false"
        name="cookieName"
      />
    </authentication>
    

    Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:

        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    
  • Cross - platform authentication

    This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)

    For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.

    <authentication mode="Windows" />
    

    If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.

    For more info, take a loot to the following articles:

Multiple HttpPost method in Web API controller

Best and simplest explanation I have seen on this topic - http://www.binaryintellect.net/articles/9db02aa1-c193-421e-94d0-926e440ed297.aspx

  • Edited -

I got it working with only Route, and did not need RoutePrefix.

For example, in the controller

[HttpPost]
[Route("[action]")]
public IActionResult PostCustomer
([FromBody]CustomerOrder obj)
{
}

and

[HttpPost]
[Route("[action]")]
public IActionResult PostCustomerAndOrder
([FromBody]CustomerOrder obj)
{
}

Then, the function name goes in jquery as either -

options.url = "/api/customer/PostCustomer";

or

options.url = "/api/customer/PostCustomerAndOrder";

ASP.NET Web Api: The requested resource does not support http method 'GET'

If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")].

Returning http status code from Web Api controller

Change the GetXxx API method to return HttpResponseMessage and then return a typed version for the full response and the untyped version for the NotModified response.

    public HttpResponseMessage GetComputingDevice(string id)
    {
        ComputingDevice computingDevice =
            _db.Devices.OfType<ComputingDevice>()
                .SingleOrDefault(c => c.AssetId == id);

        if (computingDevice == null)
        {
            return this.Request.CreateResponse(HttpStatusCode.NotFound);
        }

        if (this.Request.ClientHasStaleData(computingDevice.ModifiedDate))
        {
            return this.Request.CreateResponse<ComputingDevice>(
                HttpStatusCode.OK, computingDevice);
        }
        else
        {
            return this.Request.CreateResponse(HttpStatusCode.NotModified);
        }
    }

*The ClientHasStale data is my extension for checking ETag and IfModifiedSince headers.

The MVC framework should still serialize and return your object.

NOTE

I think the generic version is being removed in some future version of the Web API.

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

How to use System.Net.HttpClient to post a complex type?

In case someone like me didn't really understand what all above are talking about, I give an easy example which is working for me. If you have a web api which url is "http://somesite.com/verifyAddress", it is a post method and it need you to pass it an address object. You want to call this api in your code. Here what you can do.

    public Address verifyAddress(Address address)
    {
        this.client = new HttpClient();
        client.BaseAddress = new Uri("http://somesite.com/");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var urlParm = URL + "verifyAddress";
        response = client.PostAsJsonAsync(urlParm,address).Result;
        var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<Address>().Result : null;
        return dataObjects;
    }

Custom method names in ASP.NET Web API

By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.

If you want to have different action names than the standard ones you could modify your route definition in global.asax:

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

Now you can navigate to /api/users/getauthenticate to authenticate the user.

Single controller with multiple GET methods in ASP.NET Web API

I find attributes to be cleaner to use than manually adding them via code. Here is a simple example.

[RoutePrefix("api/example")]
public class ExampleController : ApiController
{
    [HttpGet]
    [Route("get1/{param1}")] //   /api/example/get1/1?param2=4
    public IHttpActionResult Get(int param1, int param2)
    {
        Object example = null;
        return Ok(example);
    }

}

You also need this in your webapiconfig

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

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

Some Good Links http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api This one explains routing better. http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Difference between ApiController and Controller in ASP.NET MVC

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}

How to refresh token with Google API client?

This here works very good, maybe it could help anybody:

index.php

session_start();

require_once __DIR__.'/client.php';

if(!isset($obj->error) && isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in)) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Google API Token Test</title>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
search('Music Mix 2010');
function search(q) {
    $.ajax({
        type: 'GET',
        url: 'action.php?q='+q,
        success: function(data) {
            if(data == 'refresh') location.reload();
            else $('#response').html(JSON.stringify(JSON.parse(data)));
        }
    });
}
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
<?php
}
else header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/oauth2callback.php', FILTER_SANITIZE_URL));
?>

oauth2callback.php

require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri('https://'.filter_var($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'], FILTER_SANITIZE_URL));
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

if(isset($_GET['code']) && $_GET['code']) {
    $client->authenticate(filter_var($_GET['code'], FILTER_SANITIZE_STRING));
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $_SESSION['access_token']['refresh_token'];
    setcookie('refresh_token', $_SESSION['refresh_token'], time()+60*60*24*180, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);
    header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']), FILTER_SANITIZE_URL));
    exit();
}
else header('Location: '.filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
exit();

?>

client.php

// https://developers.google.com/api-client-library/php/start/installation
require_once __DIR__.'/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

// Delete Cookie Token
#setcookie('refresh_token', @$_SESSION['refresh_token'], time()-1, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);

// Delete Session Token
#unset($_SESSION['refresh_token']);

if(isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
    $client->refreshToken($_SESSION['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}
elseif(isset($_COOKIE['refresh_token']) && $_COOKIE['refresh_token']) {
    $client->refreshToken($_COOKIE['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}

$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.urlencode(@$_SESSION['access_token']['access_token']);
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Google API Token Test');
$json = curl_exec($curl_handle);
curl_close($curl_handle);

$obj = json_decode($json);

?>

action.php

session_start();

require_once __DIR__.'/client.php';

if(isset($obj->error)) {
    echo 'refresh';
    exit();
}
elseif(isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in) && isset($_GET['q']) && !empty($_GET['q'])) {
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google_Service_YouTube($client);
    $response = $service->search->listSearch('snippet', array('q' => filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS), 'maxResults' => '1', 'type' => 'video'));
    echo json_encode($response['modelData']);
    exit();
}
?>

PHP Fatal Error Failed opening required File

I was having the exact same issue, I triple checked the include paths, I also checked that pear was installed and everything looked OK and I was still getting the errors, after a few hours of going crazy looking at this I realized that in my script had this:

include_once "../Mail.php";

instead of:

include_once ("../Mail.php");

Yup, the stupid parenthesis was missing, but there was no generated error on this line of my script which was odd to me

VB.Net: Dynamically Select Image from My.Resources

Sometimes you must change the name (or check to get it automatically from compiler).

Example:

Filename = amp2-rot.png

It is not working as:

PictureBoxName.Image = resources.GetObject("amp2-rot.png")

It works, just as amp2_rot for me:

 PictureBox_L1.Image = My.Resources.Resource.amp2_rot

Why is setTimeout(fn, 0) sometimes useful?

This is an old questions with old answers. I wanted to add a new look at this problem and to answer why is this happens and not why is this useful.

So you have two functions:

var f1 = function () {    
   setTimeout(function(){
      console.log("f1", "First function call...");
   }, 0);
};

var f2 = function () {
    console.log("f2", "Second call...");
};

and then call them in the following order f1(); f2(); just to see that the second one executed first.

And here is why: it is not possible to have setTimeout with a time delay of 0 milliseconds. The Minimum value is determined by the browser and it is not 0 milliseconds. Historically browsers sets this minimum to 10 milliseconds, but the HTML5 specs and modern browsers have it set at 4 milliseconds.

If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.

Also from mozilla:

To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here.

P.S. information is taken after reading the following article.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

If you are just interested in the use of Access-Control-Allow-Origin:*

You can do that with this .htaccess file at the site root.

Header set Access-Control-Allow-Origin "*"

Some useful information here: http://enable-cors.org/server_apache.html

Pygame Drawing a Rectangle

With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:

pygame.draw.rect draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect object:

pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)

pygame.draw.circle draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):

pygame.draw.circle(window, color, (x, y), radius)

pygame.draw.polygon draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):

pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])

Minimal example:

import pygame

pygame.init()

window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill((255, 255, 255))

    pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
    pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
    pygame.draw.polygon(window, (255, 255, 0), 
        [(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])

    pygame.display.flip()

pygame.quit()
exit()

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

Replacing backslashes with forward slashes with str_replace() in php

Single quoted php string variable works.

$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);

How to modify a global variable within a function in bash?

A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.

This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.

For example, you could have:

# Usage read_value path_to_tmp_file
function read_value {
  cat "${1}"
}

# Usage: set_value path_to_tmp_file the_value
function set_value {
  echo "${2}" > "${1}"
}
#----

# Original code:

function test1() {
  e=4
  set_value "${tmp_file}" "${e}"
  echo "hello"
}


# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)

# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"

# Run test1
test1

# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"

The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync command to persist the contents on the disk between one write and read operations.

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

How to set time zone in codeigniter?

Put it in config/config.php, It will work for whole application or index.php of codeigniter.

How to grep for two words existing on the same line?

The main issue is that you haven't supplied the first grep with any input. You will need to reorder your command something like

grep "word1" logs | grep "word2"

If you want to count the occurences, then put a '-c' on the second grep.

How do I copy the contents of one ArrayList into another?

Straightforward way to make deep copy of original list is to add all element from one list to another list.

ArrayList<Object> originalList = new ArrayList<Object>();
ArrayList<Object> duplicateList = new ArrayList<Object>();

for(Object o : originalList) {
    duplicateList.add(o);
}

Now If you make any changes to originalList it will not impact duplicateList.

Getting SyntaxError for print with keyword argument end=' '

In python 2.7 here is how you do it

mantra = 'Always look on the bright side of life'
for c in mantra: print c,

#output
A l w a y s   l o o k   o n   t h e   b r i g h t   s i d e   o f   l i f e

In python 3.x

myjob= 'hacker'
for c in myjob: print (c, end=' ')
#output 
h a c k e r 

ImportError: No module named 'Tkinter'

Tkinter should come with the latest Python, I don't think it comes with Python2. I had the same problem but once. I upgraded to Python 3.8 Tkinter was installed.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

LOAD DATA INFILE Error Code : 13

I use Ubuntu 12.04, I had to create the table, then do one of these:

Using local gives an error (mysql 5.5):

> LOAD DATA LOCAL INFILE "file.csv" INTO table inverter FIELDS TERMINATED BY ',';
ERROR 1148 (42000): The used command is not allowed with this MySQL version

LOAD DATA INFILE command is disabled by default for security reasons, re-enable it here and it should work: https://stackoverflow.com/a/16286112/445131

You can import the csv-file using mysqlimport:

mysqlimport -u root -p --fields-terminated-by=',' --local dbname tablename.csv

Note the csv-file must have same name before the extension as the table.

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

Send HTML in email via PHP

You can easily send the email with HTML content via PHP. Use the following script.

<?php
$to = '[email protected]';
$subject = "Send HTML Email Using PHP";

$htmlContent = '
<html>
<body>
    <h1>Send HTML Email Using PHP</h1>
    <p>This is a HTMl email using PHP by CodexWorld</p>
</body>
</html>';

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Additional headers
$headers .= 'From: CodexWorld<[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Send email
if(mail($to,$subject,$htmlContent,$headers)):
    $successMsg = 'Email has sent successfully.';
else:
    $errorMsg = 'Email sending fail.';
endif;
?>

Source code and live demo can be found from here - Send Beautiful HTML Email using PHP

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Use cell's color as condition in if statement (function)

The only easy solution that I have applied is to recreate the primary condition that do the highlights as an IF condition and use it on the IF formula. Something like this. Depending on the highlight condition the formula will change but I think that should be recreated (es. highlight greater than 20).

=IF(B3>20,(B3)," ")

Create numpy matrix filled with NaNs

Another option is to use numpy.full, an option available in NumPy 1.8+

a = np.full([height, width, 9], np.nan)

This is pretty flexible and you can fill it with any other number that you want.

Easier way to create circle div than using an image?

_x000D_
_x000D_
.circle {_x000D_
 height: 20rem;_x000D_
 width: 20rem;_x000D_
 border-radius: 50%;_x000D_
 background-color: #EF6A6A;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.

Android replace the current fragment with another fragment

it's very simple how to replace with Fragment.

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

For Windows Platform:

try Running the 64 Bit exe version of IntelliJ from a path similar to following.

note that it is available beside the default idea.exe

"C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0\bin\idea64.exe"

link

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error

UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates

It works:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phon','phon','phone','phone1','phone','phone1','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

it doesn't work:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phone','phone','phone','phone','phone','phone','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

source: https://stackoverflow.com/a/37021196/6088984

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Try Boolean() and isNaN() (for number type) to check a variable has a value or not.

_x000D_
_x000D_
function isEmpty(val) {
  return typeof val === 'number' ? isNaN(val) : !Boolean(val);
}

var emptyVals = [undefined, null, false, NaN, ''];
emptyVals.forEach(v => console.log(isEmpty(v)));
_x000D_
_x000D_
_x000D_

How to redirect docker container logs to a single file?

If you work on Windows and use PowerShell (like me), you could use the following line to capture the stdout and stderr:

 docker logs <containerId> | Out-File 'C:/dev/mylog.txt'

I hope it helps someone!

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

Non-const and const reference binding follow different rules

These are the rules of the C++ language:

  • an expression consisting of a literal number (12) is a "rvalue"
  • it is not permitted to create a non-const reference with a rvalue: int &ri = 12; is ill-formed
  • it is permitted to create a const reference with a rvalue: in this case, an unnamed object is created by the compiler; this object will persist as long as the reference itself exist.

You have to understand that these are C++ rules. They just are.

It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.

But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.

How can I declare and define multiple variables in one line using C++?

template <typename ...A>
constexpr auto assign(A& ...a) noexcept
{
  return [&](auto&& ...v) noexcept(noexcept(
    ((a = std::forward<decltype(v)>(v)), ...)))
    {
      ((a = std::forward<decltype(v)>(v)), ...);
    };
}

int column, row, index;

assign(column, row, index)(0, 0, 0);

using extern template (C++11)

Wikipedia has the best description

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

  template class std::vector<MyClass>;

C++11 now provides this syntax:

  extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.

The warning: nonstandard extension used...

Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.

Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.

How to redirect and append both stdout and stderr to a file with Bash?

In Bash you can also explicitly specify your redirects to different files:

cmd >log.out 2>log_error.out

Appending would be:

cmd >>log.out 2>>log_error.out

How can I add the new "Floating Action Button" between two widgets/layouts

Seems like the cleanest way in this example is to:

  • Use a RelativeLayout
  • Position the 2 adjacent views one below the other
  • Align the FAB to the parent right/end and add a right/end margin
  • Align the FAB to the bottom of the header view and add a negative margin, half the size of the FAB including shadow

Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="120dp"
    />

    <View
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/header"
    />

    <fully.qualified.name.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/header"
        android:layout_marginBottom="-32dp"
        android:layout_marginRight="20dp"
    />

</RelativeLayout>

FAB Layout example

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Asp.net - Add blank item at top of dropdownlist

it looks like you are adding a blank item, and then databinding, which would empty the list; try inserting the blank item after databinding

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

The main differences are:

1) OFFLINE index rebuild is faster than ONLINE rebuild.

2) Extra disk space required during SQL Server online index rebuilds.

3) SQL Server locks acquired with SQL Server online index rebuilds.

  • This schema modification lock blocks all other concurrent access to the table, but it is only held for a very short period of time while the old index is dropped and the statistics updated.

HintPath vs ReferencePath in Visual Studio

Look in the file Microsoft.Common.targets

The answer to the question is in the file Microsoft.Common.targets for your target framework version.

For .Net Framework version 4.0 (and 4.5 !) the AssemblySearchPaths-element is defined like this:

    <!--
    The SearchPaths property is set to find assemblies in the following order:

        (1) Files from current project - indicated by {CandidateAssemblyFiles}
        (2) $(ReferencePath) - the reference path property, which comes from the .USER file.
        (3) The hintpath from the referenced item itself, indicated by {HintPathFromItem}.
        (4) The directory of MSBuild's "target" runtime from GetFrameworkPath.
            The "target" runtime folder is the folder of the runtime that MSBuild is a part of.
        (5) Registered assembly folders, indicated by {Registry:*,*,*}
        (6) Legacy registered assembly folders, indicated by {AssemblyFolders}
        (7) Resolve to the GAC.
        (8) Treat the reference's Include as if it were a real file name.
        (9) Look in the application's output folder (like bin\debug)
    -->
<AssemblySearchPaths Condition=" '$(AssemblySearchPaths)' == ''">
  {CandidateAssemblyFiles};
  $(ReferencePath);
  {HintPathFromItem};
  {TargetFrameworkDirectory};
  {Registry:$(FrameworkRegistryBase),$(TargetFrameworkVersion),$(AssemblyFoldersSuffix)$(AssemblyFoldersExConditions)};
  {AssemblyFolders};
  {GAC};
  {RawFileName};
  $(OutDir)
</AssemblySearchPaths>

For .Net Framework 3.5 the definition is the same, but the comment is wrong. The 2.0 definition is slightly different, it uses $(OutputPath) instead of $(OutDir).

On my machine I have the following versions of the file Microsoft.Common.targets:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets

This is with Visual Studio 2008, 2010 and 2013 installed on Windows 7.

The fact that the output directory is searched can be a bit frustrating (as the original poster points out) because it may hide an incorrect HintPath. The solution builds OK on your local machine, but breaks when you build on in a clean folder structure (e.g. on the build machine).

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Get string after character

For the text after the first = and before the next =

cut -d "=" -f2 <<< "$your_str"

or

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

For all text after the first = regardless of if there are multiple =

cut -d "=" -f2- <<< "$your_str"

How to implement my very own URI scheme on Android

As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.

Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here

Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html

How to remove special characters from a string?

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

Java FileOutputStream Create File if not exists

Just Giving an alternative way to create the file only if doesn't exists using Path and Files.

Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
    Files.createFile(path);
Files.write(path, ("").getBytes());

PowerShell equivalent to grep -f

PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe

105:-a---        2006-11-02     13:34      49680 twunk_16.exe
106:-a---        2006-11-02     13:34      31232 twunk_32.exe
109:-a---        2006-09-18     23:43     256192 winhelp.exe
110:-a---        2006-11-02     10:45       9216 winhlp32.exe

PS) grep /?

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Is JavaScript guaranteed to be single-threaded?

Well, Chrome is multiprocess, and I think every process deals with its own Javascript code, but as far as the code knows, it is "single-threaded".

There is no support whatsoever in Javascript for multi-threading, at least not explicitly, so it does not make a difference.

Incorrect syntax near ''

You can identify the encoding used for the file (in this case sql file) using an editor (I used Visual studio code). Once you open the file, it shows you the encoding of the file at the lower right corner on the editor.

encoding

I had this issue when I was trying to check-in a file that was encoded UTF-BOM (originating from a non-windows machine) that had special characters appended to individual string characters

You can change the encoding of your file as follows:

In the bottom bar of VSCode, you'll see the label UTF-8 With BOM. Click it. A popup opens. Click Save with encoding. You can now pick a new encoding for that file (UTF-8)

Right way to convert data.frame to a numeric matrix, when df also contains strings?

data.matrix(SFI)

From ?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

"The semaphore timeout period has expired" error for USB connection

This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

How to hide a navigation bar from first ViewController in Swift?

In Swift 3, you can use isNavigationBarHidden Property also to show or hide navigation bar

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Hide the navigation bar for current view controller
    self.navigationController?.isNavigationBarHidden = true;
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // Show the navigation bar on other view controllers
   self.navigationController?.isNavigationBarHidden = false;
}

how to run or install a *.jar file in windows?

The UnsupportedClassVersionError means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

gc() can help

saving data as .RData, closing, re-opening R, and loading the RData can help.

see my answer here: https://stackoverflow.com/a/24754706/190791 for more details

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors.

What's the difference between StaticResource and DynamicResource in WPF?

Found all answers useful, just wanted to add one more use case.

In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.

As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.

Error Installing Homebrew - Brew Command Not Found

You can use this:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" 

to install homebrew.

Multiple files upload (Array) with CodeIgniter 2.0

For CodeIgniter 3

<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
      enctype="multipart/form-data">
    <div class="form-group">
        <label for="">title</label>
        <input type="text" name="title" id="title" class="form-control">
    </div>
    <div class="form-group">
        <label for="">File</label>
        <input type="file" name="files" id="files" class="form-control">
    </div>
    <input type="submit" value="Submit" class="btn btn-primary">
</form>


public function insertdatanew()
{
    $this->load->library('upload');
    $files = $_FILES;
    $cpt = count($_FILES['filesdua']['name']);

    for ($i = 0; $i < $cpt; $i++) {
        $_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
        $_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
        $_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
        $_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
        $_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];

        // fungsi uploud
        $config['upload_path']          = './uploads/testing/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 0;
        $config['max_width']            = 0;
        $config['max_height']           = 0;
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('filesdua')) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);

            // $this->load->view('welcome_message', $error);
        } else {

            // menambil nilai value yang di upload  
            $data = array('upload_data' => $this->upload->data());
            $nilai = $data['upload_data']; 
            $filename = $nilai['file_name'];
            var_dump($filename);

            // $this->load->view('upload_success', $data);
        }
    }
    // var_dump($cpt);
}

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Eclipse can't find / load main class

I found the way to fix this problem was to rename the project. If you give it a name with strange characters (in my case, :), it will have trouble locating your class. I don't know if this rule applies to numbers, but try renaming the project or making a new one and copying the files. Name it without any numbers or special characters.

Evaluate list.contains string in JSTL

If you are using Spring Framework, you can use Spring TagLib and SpEL:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="mylist.contains(myValue)" />
<c:if test="${containsValue}">style='display:none;'</c:if>

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

Convert hex to binary

>>> bin( 0xABC123EFFF )

'0b1010101111000001001000111110111111111111'

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

SQL Error: ORA-00933: SQL command not properly ended

Your query should look like

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

You can check the below question for help

MySQL dump by query

MySQL Workbench also has this feature neatly in the GUI. Simply run a query, click the save icon next to Export/Import:

enter image description here

Then choose "SQL INSERT statements (*.sql)" in the list.

enter image description here

Enter a name, click save, confirm the table name and you will have your dump file.

Can an html element have multiple ids?

My understanding has always been:

  • ID's are single use and are only applied to one element...

    • Each is attributed as a Unique Identifier to (only) one single element.
  • Classes can be used more than once...

    • They can therefore be applied to more than one element, and similarly yet different, there can be more than one class (i.e. multiple classes) per element.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Your syntax is wrong... The correct coding is:

 <?php
mysql_connect("localhost","root","");
mysql_select_db("form1");
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");
while($rows = mysql_fetch_array($query))
{

   $rows = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment']
   echo $rows.'</br>'.$address.'</br>'.$email.'</br>'.$subject.'</br>'.$comment;
}
   ?>

Recursive sub folder search and return files in a list python

This seems to be the fastest solution I could come up with, and is faster than os.walk and a lot faster than any glob solution.

  • It will also give you a list of all nested subfolders at basically no cost.
  • You can search for several different extensions.
  • You can also choose to return either full paths or just the names for the files by changing f.path to f.name (do not change it for subfolders!).

Args: dir: str, ext: list.
Function returns two lists: subfolders, files.

See below for a detailed speed anaylsis.

def run_fast_scandir(dir, ext):    # dir: str, ext: list
    subfolders, files = [], []

    for f in os.scandir(dir):
        if f.is_dir():
            subfolders.append(f.path)
        if f.is_file():
            if os.path.splitext(f.name)[1].lower() in ext:
                files.append(f.path)


    for dir in list(subfolders):
        sf, f = run_fast_scandir(dir, ext)
        subfolders.extend(sf)
        files.extend(f)
    return subfolders, files


subfolders, files = run_fast_scandir(folder, [".jpg"])

In case you need the file size, you can also create a sizes list and add f.stat().st_size like this for a display of MiB:

sizes.append(f"{f.stat().st_size/1024/1024:.0f} MiB")

Speed analysis

for various methods to get all files with a specific file extension inside all subfolders and the main folder.

tl;dr:

  • fast_scandir clearly wins and is twice as fast as all other solutions, except os.walk.
  • os.walk is second place slighly slower.
  • using glob will greatly slow down the process.
  • None of the results use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026

**Results:**
fast_scandir    took  499 ms. Found files: 16596. Found subfolders: 439
os.walk         took  589 ms. Found files: 16596
find_files      took  919 ms. Found files: 16596
glob.iglob      took  998 ms. Found files: 16596
glob.glob       took 1002 ms. Found files: 16596
pathlib.rglob   took 1041 ms. Found files: 16596
os.walk-glob    took 1043 ms. Found files: 16596

Tests were done with W7x64, Python 3.8.1, 20 runs. 16596 files in 439 (partially nested) subfolders.
find_files is from https://stackoverflow.com/a/45646357/2441026 and lets you search for several extensions.
fast_scandir was written by myself and will also return a list of subfolders. You can give it a list of extensions to search for (I tested a list with one entry to a simple if ... == ".jpg" and there was no significant difference).


# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob, iglob
from pathlib import Path


directory = r"<folder>"
RUNS = 20


def run_os_walk():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [os.path.join(dp, f) for dp, dn, filenames in os.walk(directory) for f in filenames if
                  os.path.splitext(f)[1].lower() == '.jpg']
    print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")


def run_os_walk_glob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [y for x in os.walk(directory) for y in glob(os.path.join(x[0], '*.jpg'))]
    print(f"os.walk-glob\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")


def run_glob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = glob(os.path.join(directory, '**', '*.jpg'), recursive=True)
    print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")


def run_iglob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = list(iglob(os.path.join(directory, '**', '*.jpg'), recursive=True))
    print(f"glob.iglob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")


def run_pathlib_rglob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = list(Path(directory).rglob("*.jpg"))
    print(f"pathlib.rglob\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")


def find_files(files, dirs=[], extensions=[]):
    # https://stackoverflow.com/a/45646357/2441026

    new_dirs = []
    for d in dirs:
        try:
            new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
        except OSError:
            if os.path.splitext(d)[1].lower() in extensions:
                files.append(d)

    if new_dirs:
        find_files(files, new_dirs, extensions )
    else:
        return


def run_fast_scandir(dir, ext):    # dir: str, ext: list
    # https://stackoverflow.com/a/59803793/2441026

    subfolders, files = [], []

    for f in os.scandir(dir):
        if f.is_dir():
            subfolders.append(f.path)
        if f.is_file():
            if os.path.splitext(f.name)[1].lower() in ext:
                files.append(f.path)


    for dir in list(subfolders):
        sf, f = run_fast_scandir(dir, ext)
        subfolders.extend(sf)
        files.extend(f)
    return subfolders, files



if __name__ == '__main__':
    run_os_walk()
    run_os_walk_glob()
    run_glob()
    run_iglob()
    run_pathlib_rglob()


    a = time.time_ns()
    for i in range(RUNS):
        files = []
        find_files(files, dirs=[directory], extensions=[".jpg"])
    print(f"find_files\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(files)}")


    a = time.time_ns()
    for i in range(RUNS):
        subf, files = run_fast_scandir(directory, [".jpg"])
    print(f"fast_scandir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(files)}. Found subfolders: {len(subf)}")

add a temporary column with a value

select field1, field2, '' as newfield from table1

This Will Do you Job

How do I close a single buffer (out of many) in Vim?

You can map next and previous to function keys too, making cycling through buffers a breeze

map <F2> :bprevious<CR>
map <F3> :bnext<CR>

from my vimrc

Getting the index of a particular item in array

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());

How to check the version of GitLab?

cd /opt/gitlab

cat version-manifest.txt

Example:

gitlab-ctl 6.8.2-omnibus
gitlab-rails v6.8.2

Current gitlab version is 6.8.2

Screenshot of the console

How to configure log4j with a properties file

I believe the log4j.properties directory it needs to be in the java classpath. In your case adding the CWD to the classpath should work.

could not access the package manager. is the system running while installing android application

Check your project build is in Debug mode not Release, I had some problem for debugging always I forget to change Release mode to Debug (Xamarin Users)

How to get number of video views with YouTube API?

look at yt:statistics tag. It provides viewCount, videoWatchCount, favoriteCount etc.

Find an object in SQL Server (cross-database)

There is a schema called INFORMATION_SCHEMA schema which contains a set of views on tables from the SYS schema that you can query to get what you want.

A major upside of the INFORMATION_SCHEMA is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA is that you have to write one query for each type of object.

The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.

You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.

One could search in a database as follows:

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'

Now, if you wanted to restrict this to only search for tables and stored procs, you would do

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'
    and Type in ('U', 'P')

If you look up object types, you will find a whole list for views, triggers, etc.

Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:

If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.

If you only want to search specific databases, use the "USE DBName" and then search command.

You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:

Declare @ObjectName VarChar (100)

Set @ObjectName = '%Customer%'

Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

Proper way to return JSON using node or Express

For the header half of the question, I'm gonna give a shout out to res.type here:

res.type('json')

is equivalent to

res.setHeader('Content-Type', 'application/json')

Source: express docs:

Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

I think we can understand the difference between these two by seeing a Java8 example code:

  interface Something{}

  interface OneWhoCanProvideSomething {
     Something getSomething();
  }

  interface OneWhoCanProvideCreatorsOfSomething{
     OneWhoCanProvideSomething getCreator();
  }


public class AbstractFactoryExample {

    public static void main(String[] args) {
        //I need something
        //Let's create one
        Something something = new Something() {};

        //Or ask someone (FACTORY pattern)
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;

        //Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
        OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;

        //Same thing, but you don't need to write you own interfaces
        Supplier<Something> supplierOfSomething = () -> null;
        Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
    }

}

Now the question is which way of creation should you use and why: The first way (no pattern, just plain constructor): creating by yourself is not a good idea, you have to do all the work, and your client code is tied to the particular implementation.

The second way (using Factory pattern): provides you the benefit that you can pass any type of implementation, which can provide different type of something based on some condition (maybe a parameter passed to creational method).

The third way (using Abstract Factory pattern): This gives you more flexibility. You can find different types of creators of something based on some condition (maybe a parameter passed).

Note that you can always get away with Factory pattern by combining two conditions together (which slightly increases code complexity, and coupling), I guess that's why we rarely see real life use cases of Abstract Factory pattern.

moment.js, how to get day of week number

If you are specifically looking for the 1-7 approach...

This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

_x000D_
_x000D_
console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

matplotlib has no attribute 'pyplot'

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

How to implement class constructor in Visual Basic?

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

Random number from a range in a Bash Script

According to the bash man page, $RANDOM is distributed between 0 and 32767; that is, it is an unsigned 15-bit value. Assuming $RANDOM is uniformly distributed, you can create a uniformly-distributed unsigned 30-bit integer as follows:

$(((RANDOM<<15)|RANDOM))

Since your range is not a power of 2, a simple modulo operation will only almost give you a uniform distribution, but with a 30-bit input range and a less-than-16-bit output range, as you have in your case, this should really be close enough:

PORT=$(( ((RANDOM<<15)|RANDOM) % 63001 + 2000 ))

Run Stored Procedure in SQL Developer?

Open the procedure in SQL Developer and run it from there. SQL Developer displays the SQL that it runs.

BEGIN
  PROCEEDURE_NAME_HERE();
END;

How to get C# Enum description from value?

I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:

public static string DescriptionAttr<T>(this T source)
{
    FieldInfo fi = source.GetType().GetField(source.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0) return attributes[0].Description;
    else return source.ToString();
}

Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:

string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();

What can I use for good quality code coverage for C#/.NET?

There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.

Could not load file or assembly '***.dll' or one of its dependencies

Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:

{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64

But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value

C:\Program Files\Java\jre1.8.0_171\bin\server

for Java's path, and put it on top of the Path items.

This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.

C:\Program Files\Java\jre1.8.0_181\bin\server

How to display table data more clearly in oracle sqlplus

Ahhh, the stupid linesize ... Here is what I do in my profile.sql - works only on unixes:

echo SET LINES $(tput cols) > $HOME/.login_tmp.sql
@$HOME/.login_tmp.sql

if you find an equivalent for tput on Windows, it might work there as well

How do I keep two side-by-side divs the same height?

I was having the same problem so i created this small function using jquery as jquery is part of every web application nowadays.

function fEqualizeHeight(sSelector) {
    var sObjects = $(sSelector);

    var iCount = sObjects.length;

    var iHeights = [];

    if (iCount > 0) {
        $(sObjects).each(function () {
            var sHeight = $(this).css('height');
            var iHeight = parseInt(sHeight.replace(/px/i,''));
            iHeights.push(iHeight);
        });

        iHeights.sort(function (a, b) {
            return a - b
        });

        var iMaxHeight = iHeights.pop();

        $(sSelector).each(function () {
            $(this).css({
                'height': iMaxHeight + 'px'
            });
        });
    }
}

You can call this function on page ready event

$(document).ready(function(){
   fEqualizeHeight('.columns');
});

I hope this works for you.

How to reformat JSON in Notepad++?

simply go to this link download the dll copy and paste the dll to the plugins folder at notepad++, \Notepad++\plugins restart the notepad++, and it should be shown in the list

jsformatter

NOTE: this dll supports 64 bit notepade++

How to Import .bson file format on mongodb

In mongodb 3.0 or above, we can specify database name to restore. Assuming that you are standing at the root directory that contains bson files

./
a.bson
b.metadata.bson
...

The script would be

for FILENAME in *; do mongorestore -d <db_name> -c "${FILENAME%.*}" $FILENAME; done

Best,

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Declaring a variable and setting its value from a SELECT query in Oracle

ORA-01422: exact fetch returns more than requested number of rows

if you don't specify the exact record by using where condition, you will get the above exception

DECLARE
     ID NUMBER;
BEGIN
     select eid into id from employee where salary=26500;
     DBMS_OUTPUT.PUT_LINE(ID);
END;

Want custom title / image / description in facebook share link from a flash app

I have a Joomla Module that displays stuff... and I want to be able to share that stuff on facebook and not the Page's Title Meta Description... so my workaround is to have a secret .php file on the server that gets executed when it detects the FB's

$_SERVER['HTTP_USER_AGENT']

if($_SERVER['HTTP_USER_AGENT'] != 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)') {
    echo 'Direct Access';
} else {
    echo 'FB Accessed';
}

and pass variables with the URL that formats that particular page with the title and meta desciption of the item I want to share from my joomla module...

a name="fb_share" share_url="MYURL/sharer.php?title=TITLE&desc=DESC"

hope this helps...

How to resize Twitter Bootstrap modal dynamically based on the content

Simple Css work for me

.modal-dialog { 
max-width : 100% ;
}

Can I run Keras model on gpu?

Of course. if you are running on Tensorflow or CNTk backends, your code will run on your GPU devices defaultly.But if Theano backends, you can use following

Theano flags:

"THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py"

Unexpected end of file error

If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:

  • In the Solution Explorer pane of the project, right-click the project name, and then click Properties.
  • In the left pane, click the C/C++ folder.
  • Click the Precompiled Headers node.
  • In the right pane, click Create/Use Precompiled Header, and then click Not Using Precompiled Headers.

Properties file with a list as the value for an individual key

The comma separated list option is the easiest but becomes challenging if the values could include commas.

Here is an example of the a.1, a.2, ... approach:

for (String value : getPropertyList(prop, "a"))
{
    System.out.println(value);
}

public static List<String> getPropertyList(Properties properties, String name) 
{
    List<String> result = new ArrayList<String>();
    for (Map.Entry<Object, Object> entry : properties.entrySet())
    {
        if (((String)entry.getKey()).matches("^" + Pattern.quote(name) + "\\.\\d+$"))
        {
            result.add((String) entry.getValue());
        }
    }
    return result;
}

How to use Greek symbols in ggplot2?

Simplest solution: Use Unicode Characters

No expression or other packages needed.
Not sure if this is a newer feature for ggplot, but it works. It also makes it easy to mix Greek and regular text (like adding '*' to the ticks)

Just use unicode characters within the text string. seems to work well for all options I can think of. Edit: previously it did not work in facet labels. This has apparently been fixed at some point.

library(ggplot2)
ggplot(mtcars, 
       aes(mpg, disp, color=factor(gear))) + 
  geom_point() + 
  labs(title="Title (\u03b1 \u03a9)", # works fine
       x= "\u03b1 \u03a9 x-axis title",    # works fine
       y= "\u03b1 \u03a9 y-axis title",    # works fine
       color="\u03b1 \u03a9 Groups:") +  # works fine
  scale_x_continuous(breaks = seq(10, 35, 5), 
                     labels = paste0(seq(10, 35, 5), "\u03a9*")) + # works fine; to label the ticks
  ggrepel::geom_text_repel(aes(label = paste(rownames(mtcars), "\u03a9*")), size =3) + # works fine 
  facet_grid(~paste0(gear, " Gears \u03a9"))

Created on 2019-08-28 by the reprex package (v0.3.0)

How to show google.com in an iframe?

As it has been outlined here, because Google is sending an "X-Frame-Options: SAMEORIGIN" response header you cannot simply set the src to "http://www.google.com" in a iframe.

If you want to embed Google into an iframe you can do what sudopeople suggested in a comment above and use a Google custom search link like the following. This worked great for me (left 'q=' blank to start with blank search).

<iframe id="if1" width="100%" height="254" style="visibility:visible" src="http://www.google.com/custom?q=&btnG=Search"></iframe>

EDIT:

This answer no longer works. For information, and instructions on how to replace an iframe search with a google custom search element check out: https://support.google.com/customsearch/answer/2641279

How to calculate distance from Wifi router using Signal Strength?

To calculate the distance you need signal strength and frequency of the signal. Here is the java code:

public double calculateDistance(double signalLevelInDb, double freqInMHz) {
    double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(signalLevelInDb)) / 20.0;
    return Math.pow(10.0, exp);
}

The formula used is:

distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20)

Example: frequency = 2412MHz, signalLevel = -57dbm, result = 7.000397427391188m

This formula is transformed form of Free Space Path Loss(FSPL) formula. Here the distance is measured in meters and the frequency - in megahertz. For other measures you have to use different constant (27.55). Read for the constants here.

For more information read here.

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How do you embed binary data in XML?

If you have control over the XML format, you should turn the problem inside out. Rather than attaching the binary XML you should think about how to enclose a document that has multiple parts, one of which contains XML.

The traditional solution to this is an archive (e.g. tar). But if you want to keep your enclosing document in a text-based format or if you don't have access to an file archiving library, there is also a standardized scheme that is used heavily in email and HTTP which is multipart/* MIME with Content-Transfer-Encoding: binary.

For example if your servers communicate through HTTP and you want to send a multipart document, the primary being an XML document which refers to a binary data, the HTTP communication might look something like this:

POST / HTTP/1.1
Content-Type: multipart/related; boundary="qd43hdi34udh34id344"
... other headers elided ...

--qd43hdi34udh34id344
Content-Type: application/xml

<myxml>
    <data href="cid:data.bin"/>
</myxml>
--qd43hdi34udh34id344
Content-Id: <data.bin>
Content-type: application/octet-stream
Content-Transfer-Encoding: binary

... binary data ...
--qd43hdi34udh34id344--

As in above example, the XML refer to the binary data in the enclosing multipart by using a cid URI scheme which is an identifier to the Content-Id header. The overhead of this scheme would be just the MIME header. A similar scheme can also be used for HTTP response. Of course in HTTP protocol, you also have the option of sending a multipart document into separate request/response.

If you want to avoid wrapping your data in a multipart is to use data URI:

<myxml>
    <data href="data:application/something;charset=utf-8;base64,dGVzdGRhdGE="/>
</myxml>

But this has the base64 overhead.

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

How do I disable the resizable property of a textarea?

If you need deep support, you can use an old school technique:

textarea {
    max-width: /* desired fixed width */ px;
    min-width: /* desired fixed width */ px;
    min-height: /* desired fixed height */ px;
    max-height: /* desired fixed height */ px;
}

What's the best/easiest GUI Library for Ruby?

There's a discussion here that might be useful.

From my own (limited) exposure, I'd say that shoes was the most fun and probably the "easiest" to get into. Be warned, however, that figuring out what was wrong when something breaks can be tricky (at least, it was for me).

For a real-world application that I was planning to deploy to real-world users, I think I'd go with wxruby.

Creating for loop until list.length

In Python you can iterate over the list itself:

for item in my_list:
   #do something with item

or to use indices you can use xrange():

for i in xrange(1,len(my_list)):    #as indexes start at zero so you 
                                    #may have to use xrange(len(my_list))
    #do something here my_list[i]

There's another built-in function called enumerate(), which returns both item and index:

for index,item in enumerate(my_list):
    # do something here

examples:

In [117]: my_lis=list('foobar')

In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']

In [119]: for item in my_lis:
    print item
   .....:     
f
o
o
b
a
r

In [120]: for i in xrange(len(my_lis)):
    print my_lis[i]
   .....:     
f
o
o
b
a
r

In [122]: for index,item in enumerate(my_lis):
    print index,'-->',item
   .....:     
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r

PHP + MySQL transactions examples

I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:

function transaction ($con, $Q){
        mysqli_query($con, "START TRANSACTION");

        for ($i = 0; $i < count ($Q); $i++){
            if (!mysqli_query ($con, $Q[$i])){
                echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
                break;
            }   
        }

        if ($i == count ($Q)){
            mysqli_query($con, "COMMIT");
            return 1;
        }
        else {
            mysqli_query($con, "ROLLBACK");
            return 0;
        }
    }

ASP.net vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

Android: keep Service running when app is killed

All the answers seem correct so I'll go ahead and give a complete answer here.

Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart following that.

Now lets jump into code.


Create your Service in YourService.java

Note the onCreate() method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.

The this.sendBroadcast(broadcastIntent); in the onDestroy() method is the statement which asynchronously sends a broadcast with the action name "restartservice". We'll be using this later as a trigger to restart our service.

Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log while incrementing itself every time it prints.

public class YourService extends Service {
public int counter=0;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


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


    @Override
    public void onDestroy() {
        super.onDestroy();
        stoptimertask();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
    }



    private Timer timer;
    private TimerTask timerTask;
    public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                Log.i("Count", "=========  "+ (counter++));
            }
        };
        timer.schedule(timerTask, 1000, 1000); //
    }

    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

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

Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java

The broadcast with the action name "restartservice" which you just defined in YourService.java is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver in Android.

We override the built-in onRecieve() method in BroadcastReceiver to add the statement which will restart the service. The startService() will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService() for higher versions and show a continuous notification to keep the service running.

public class Restarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Broadcast Listened", "Service tried to stop");
        Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, YourService.class));
        } else {
            context.startService(new Intent(context, YourService.class));
        }
    }
}

Define your MainActivity.java to call the service on app start.

Here we define a separate isMyServiceRunning() method to check the current status of the background service. If the service is not running, we start it by using startService().

Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.

Note that in onDestroy() we are dedicatedly calling stopService(), so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy() method in YourService.java

public class MainActivity extends AppCompatActivity {
    Intent mServiceIntent;
    private YourService mYourService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mYourService = new YourService();
        mServiceIntent = new Intent(this, mYourService.getClass());
        if (!isMyServiceRunning(mYourService.getClass())) {
            startService(mServiceIntent);
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                Log.i ("Service status", "Running");
                return true;
            }
        }
        Log.i ("Service status", "Not running");
        return false;
    }


    @Override
    protected void onDestroy() {
        //stopService(mServiceIntent);
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        super.onDestroy();
    }
}

Finally register them in your AndroidManifest.xml

All of the above three classes need to be separately registered in AndroidManifest.xml.

Note that we define an intent-filter with the action name as "restartservice" where the Restarter.java is registered as a receiver. This ensures that our custom BroadcastReciever is called whenever the system encounters a broadcast with the given action name.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <receiver
        android:name="Restarter"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="restartservice" />
        </intent-filter>
    </receiver>

    <activity android:name="MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="YourService"
        android:enabled="true" >
    </service>
</application>

This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop the app from Application Settings.

UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy() of the service is called, which might not be the case certain times, which I was unaware of. Thanks.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

Getting IPV4 address from a sockaddr structure

You can use getnameinfo for Windows and for Linux.

Assuming you have a good (i.e. it's members have appropriate values) sockaddr* called pSockaddr:

char clienthost[NI_MAXHOST];  //The clienthost will hold the IP address.
char clientservice[NI_MAXSERV];
int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);

if( theErrorCode != 0 )
{
    //There was an error.
    cout << gai_strerror(e1) << endl;
}else{
    //Print the info.
    cout << "The ip address is = " << clienthost << endl;
    cout << "The clientservice = " << clientservice << endl;
}

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

How do I get formatted JSON in .NET using C#?

All this can be done in one simple line:

string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);

Android Studio : unmappable character for encoding UTF-8

I have the problem with encoding in javadoc generated by intellij idea. The solution is to add

-encoding UTF-8 -docencoding utf-8 -charset utf-8

into command line arguments!

UPDATE: more information about compilation Javadoc in Intellij IDEA see in my post

Declaring a custom android UI element using XML

You can include any layout file in other layout file as-

             <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="30dp" >

                <include
                    android:id="@+id/frnd_img_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_imagefile"/>

                <include
                    android:id="@+id/frnd_video_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_video_lay" />

                <ImageView
                    android:id="@+id/downloadbtn"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:src="@drawable/plus"/>
            </RelativeLayout>

here the layout files in include tag are other .xml layout files in the same res folder.

Vector of Vectors to create matrix

Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link

After initialization there will be no errors, see this link

java.util.NoSuchElementException: No line found

Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.

For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.

Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called

      "java.util.NoSuchElementException: No line found".

If you have to call "sc.nextLine()" n times, then you have to have at least n lines.

Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

Is it possible to start a shell session in a running container (without ssh)

No. This is not possible. Use something like supervisord to get an ssh server if that's needed. Although, I definitely question the need.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I suppose you want to use this image as an icon. As Android is telling you, your image is too large. What you just need to do is scale your image so that Android knows which size of the image to use and when according to screen resolution. To accomplish this, in Android Studio: 1. right click on the res folder, 2. select Image Asset 3. Select icon Type 4. Give the icon a name 5. Select Image on Asset Type 6. Trim your image Click next and finish. In your xml or source code just refer to the image which will now be located either in the layout or mipmap folder according to asset type selected. The error will go away.

How do I run Python code from Sublime Text 2?

Tools -> Build System -> (choose) Python then:

To Run:

      Tools -> Build

      -or-

      Ctrl + B

      CMD + B  (OSX)

This would start your file in the console which should be at the bottom of the editor.

To Stop:

       Ctrl + Break or Tools -> Cancel Build

       Fn + C (OSX)

You can find out where your Break key is here: http://en.wikipedia.org/wiki/Break_key.

Note: CTRL + C will NOT work.

What to do when Ctrl + Break does not work:

Go to:

Preferences -> Key Bindings - User

and paste the line below:

{"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} } 

Now, you can use ctrl+shift+c instead of CTRL+BREAK

Laravel PHP Command Not Found

Add the following to .bashrc file (not .bash_profile).

export PATH="~/.composer/vendor/bin:$PATH" 

at the end of the file and then in terminal run source ~/.bashrc

To verify that:

echo $PATH

(Restart the terminal, Check & Confirm the path is there)

Run the laravel command!

Note: For Ubuntu 16 and above use below:

export PATH="~/.config/composer/vendor/bin:$PATH" 

Replace a value in a data frame based on a conditional (`if`) statement

The easiest way to do this in one command is to use which command and also need not to change the factors into character by doing this:

junk$nm[which(junk$nm=="B")]<-"b"

CSS table-cell equal width

Just using max-width: 0 in the display: table-cell element worked for me:

_x000D_
_x000D_
.table {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.table-cell {_x000D_
  display: table-cell;_x000D_
  max-width: 0px;_x000D_
  border: 1px solid gray;_x000D_
}
_x000D_
<div class="table">_x000D_
  <div class="table-cell">short</div>_x000D_
  <div class="table-cell">loooooong</div>_x000D_
  <div class="table-cell">Veeeeeeery loooooong</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert DataSet to List

Add a new class named as "Helper" and change the property of the class to "public static"

public static class Helper
{
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}

and access this class in your code behind as like below

 DataTable dtt = dsCallList.Tables[0];
 List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>();

Can I convert a boolean to Yes/No in a ASP.NET GridView

It's easy with Format()-Function

Format(aBoolean, "YES/NO")

Please find details here: https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx

Excel vba - convert string to number

If, for example, x = 5 and is stored as string, you can also just:

x = x + 0

and the new x would be stored as a numeric value.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

how to convert JSONArray to List of Object using camel-jackson

I had similar json response coming from client. Created one main list class, and one POJO class.

How should I store GUID in MySQL tables?

For those just stumbling across this, there is now a much better alternative as per research by Percona.

It consists of reorganising the UUID chunks for optimal indexing, then converting into binary for reduced storage.

Read the full article here

Undefined reference to vtable

There is lot of speculation going on in various answers here. I'll below give a fairly minimal code that reproduces this error and explain why it is occuring.

Fairly Minimal Code to Reproduce This Error

IBase.hpp

#pragma once

class IBase {
    public:
        virtual void action() = 0;
};

Derived.hpp

#pragma once

#include "IBase.hpp"

class Derived : public IBase {
    public:
        Derived(int a);
        void action() override;
};

Derived.cpp

#include "Derived.hpp"
Derived::Derived(int a) { }
void Derived::action() {}

myclass.cpp

#include <memory>
#include "Derived.hpp"

class MyClass {

    public:
        MyClass(std::shared_ptr<Derived> newInstance) : instance(newInstance) {

        }

        void doSomething() {
            instance->action();
        }

    private:
        std::shared_ptr<Derived> instance;
};

int main(int argc, char** argv) {
    Derived myInstance(5);
    MyClass c(std::make_shared<Derived>(myInstance));
    c.doSomething();
    return 0;
}

You can compile this using GCC like this:

g++ -std=c++11 -o a.out myclass.cpp Derived.cpp

You can now reproduce the error by removing = 0 in IBase.hpp. I get this error:

~/.../catkin_ws$ g++ -std=c++11 -o /tmp/m.out /tmp/myclass.cpp /tmp/Derived.cpp
/tmp/cclLscB9.o: In function `IBase::IBase(IBase const&)':
myclass.cpp:(.text._ZN5IBaseC2ERKS_[_ZN5IBaseC5ERKS_]+0x13): undefined reference to `vtable for IBase'
/tmp/cc8Smvhm.o: In function `IBase::IBase()':
Derived.cpp:(.text._ZN5IBaseC2Ev[_ZN5IBaseC5Ev]+0xf): undefined reference to `vtable for IBase'
/tmp/cc8Smvhm.o:(.rodata._ZTI7Derived[_ZTI7Derived]+0x10): undefined reference to `typeinfo for IBase'
collect2: error: ld returned 1 exit status

Explanation

Notice that above code does not require any virtual destructors, constructors or any other extra files for compile to be successful (although you should have them).

The way to understand this error is as follows: Linker is looking for constructor of IBase. This it will need it for the constructor of Derived. However as Derived overrides methods from IBase, it has vtable attached to it that will reference IBase. When linker says "undefined reference to vtable for IBase" it basically means that Derived has vtable reference to IBase but it can't find any compiled object code of IBase to look up to. So the bottom line is that class IBase has declarations without implementations. This means a method in IBase is declared as virtual but we forgot to mark it as pure virtual OR provide its definition.

Parting Tip

If all else fails then one way to debug this error is to build minimal program that does compile and then keep changing it so it gets to the state you want. In between, keep compiling to see when it starts to fail.

Note on ROS and Catkin build system

If you were compiling above set of classes in ROS using catkin build system then you will need following lines in CMakeLists.txt:

add_executable(myclass src/myclass.cpp src/Derived.cpp)
add_dependencies(myclass theseus_myclass_cpp)
target_link_libraries(myclass ${catkin_LIBRARIES})

The first line basically says that we want to make an executable named myclass and the code to build this can be found files that follows. One of these files should have main(). Notice that you don't have to specify .hpp files anywhere in CMakeLists.txt. Also you don't have to specify Derived.cpp as library.

C++ How do I convert a std::chrono::time_point to long and back

I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:

auto now = system_clock::now();

//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();

//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();

The first one reads more clearly in my mind going from left to right.

Select multiple columns in data.table by their numeric indices

It's a bit verbose, but i've gotten used to using the hidden .SD variable.

b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]

It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.

Removing items from a list

You need to use Iterator and call remove() on iterator instead of using for loop.

How to create border in UIButton?

You can set the border properties on the CALayer by accessing the layer property of the button.

First, add Quartz

#import <QuartzCore/QuartzCore.h>

Set properties:

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;

See:

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

The CALayer in the link above allows you to set other properties like corner radius, maskToBounds etc...

Also, a good article on button fun:

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php

phpmailer error "Could not instantiate mail function"

An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini

How to search by key=>value in a multidimensional array in PHP

And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):

// if the array is 
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);

//then 
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) ) 
// instead of Array ( [0] => Array ( [id] => 2 ) )

// search array for specific key = value
function search_array($array, $key, $value) {
  $return = array();   
  foreach ($array as $k=>$subarray){  
    if (isset($subarray[$key]) && $subarray[$key] == $value) {
      $return[$k] = $subarray;
      return $return;
    } 
  }
}

Thanks to all who posted here.

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

How can I show/hide component with JSF?

Use the "rendered" attribute available on most if not all tags in the h-namespace.

<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />

Errors in pom.xml with dependencies (Missing artifact...)

SIMPLE..

First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)

How do I "un-revert" a reverted Git commit?

Or you could git checkout -b <new-branch> and git cherry-pick <commit> the before to the and git rebase to drop revert commit. send pull request like before.

Android: How to handle right to left swipe gestures

Kotlin version of @Mirek Rusin is here:

OnSwipeTouchListener.kt :

open class OnSwipeTouchListener(ctx: Context) : OnTouchListener {

    private val gestureDetector: GestureDetector

    companion object {

        private val SWIPE_THRESHOLD = 100
        private val SWIPE_VELOCITY_THRESHOLD = 100
    }

    init {
        gestureDetector = GestureDetector(ctx, GestureListener())
    }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        return gestureDetector.onTouchEvent(event)
    }

    private inner class GestureListener : SimpleOnGestureListener() {


        override fun onDown(e: MotionEvent): Boolean {
            return true
        }

        override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
            var result = false
            try {
                val diffY = e2.y - e1.y
                val diffX = e2.x - e1.x
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight()
                        } else {
                            onSwipeLeft()
                        }
                        result = true
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom()
                    } else {
                        onSwipeTop()
                    }
                    result = true
                }
            } catch (exception: Exception) {
                exception.printStackTrace()
            }

            return result
        }


    }

    open fun onSwipeRight() {}

    open fun onSwipeLeft() {}

    open fun onSwipeTop() {}

    open fun onSwipeBottom() {}
}

Usage:

view.setOnTouchListener(object : OnSwipeTouchListener(context) {

    override fun onSwipeTop() {
        super.onSwipeTop()
    }

    override fun onSwipeBottom() {
        super.onSwipeBottom()
    }

    override fun onSwipeLeft() {
        super.onSwipeLeft()
    }

    override fun onSwipeRight() {
        super.onSwipeRight()
    }
})

the open keyword was the point for me...

Check if string is in a pandas dataframe

it seems that the OP meant to find out whether the string 'Mel' exists in a particular column, not contained in a column, therefore the use of contains is not needed, and is not efficient. A simple equals-to is enough:

(a['Names']=='Mel').any()

How to round the minute of a datetime object

Here is a simpler generalized solution without floating point precision issues and external library dependencies:

import datetime

def time_mod(time, delta, epoch=None):
    if epoch is None:
        epoch = datetime.datetime(1970, 1, 1, tzinfo=time.tzinfo)
    return (time - epoch) % delta

def time_round(time, delta, epoch=None):
    mod = time_mod(time, delta, epoch)
    if mod < (delta / 2):
       return time - mod
    return time + (delta - mod)

In your case:

>>> tm = datetime.datetime(2010, 6, 10, 3, 56, 23)
>>> time_round(tm, datetime.timedelta(minutes=10))
datetime.datetime(2010, 6, 10, 4, 0)

How to initialize an array in Java?

Syntax

 Datatype[] variable = new Datatype[] { value1,value2.... }

 Datatype variable[]  = new Datatype[] { value1,value2.... }

Example :

int [] points = new int[]{ 1,2,3,4 };

HTTP GET Request in Node.js Express

This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.

let http = require("http"),
    https = require("https");

/**
* getJSON:  REST get request returning JSON object(s)
* @param options: http options object
*/
exports.getJSON = function (options) {
    console.log('rest::getJSON');
    let reqHandler = +options.port === 443 ? https : http;

    return new Promise((resolve, reject) => {
        let req = reqHandler.request(options, (res) => {
            let output = '';
            console.log('rest::', options.host + ':' + res.statusCode);
            res.setEncoding('utf8');

            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', () => {
                try {
                    let obj = JSON.parse(output);
                    // console.log('rest::', obj);
                    resolve({
                        statusCode: res.statusCode,
                        data: obj
                    });
                }
                catch (err) {
                    console.error('rest::end', err);
                    reject(err);
                }
            });
        });

        req.on('error', (err) => {
            console.error('rest::request', err);
            reject(err);
        });

        req.end();
    });
};

As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler

router.get('/:id', (req, res, next) => {
    rest.getJSON({
        host: host,
        path: `/posts/${req.params.id}`,
        method: 'GET'
    }).then(({ statusCode, data }) => {
        res.json(data);
    }, (error) => {
        next(error);
    });
});

On error it delegates the error to the server error handling middleware.

How to remove item from a python list in a loop?

The already-mentioned list comprehension approach is probably your best bet. But if you absolutely want to do it in-place (for example if x is really large), here's one way:

x = ["ok", "jj", "uy", "poooo", "fren"]
index=0
while index < len(x):
    if len(x[index]) != 2:
        print "length of %s is: %s" %(x[index], len(x[index]))
        del x[index]
        continue
    index+=1

How do I check if a number is a palindrome?

Simply get the digit count of the number via Math functions and then iterate by using '/' and '%' operations as follows. After x = (x % divider) / 10, we should divide divider by 100 since we made 2 zero operations.

public static boolean isPalindrome(int x) {
            if (x < 0) return false;
            if (x < 10) return true;

            int numDigits = (int)(Math.log10(x)+1);
            int divider = (int) (Math.pow(10, numDigits - 1));
            for (int i = 0; i < numDigits / 2; i++) {
                if (x / divider != x % 10)
                    return false;
                x = (x % divider) / 10;
                divider /= 100;
            }
            return true;
        }

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

How to pass password automatically for rsync SSH command?

Though you've already implemented it by now,

you can also use any expect implementation (you'll find alternatives in Perl, Python: pexpect, paramiko, etc..)

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

Escaping single quotes in JavaScript string for JavaScript evaluation

var str ="fsdsd'4565sd"; str.replace(/'/g,"'")

This worked for me. Kindly try this

enter image description here

jQuery $(document).ready and UpdatePanels?

Update Panel always replaces your Jquery with its inbuilt Scriptmanager's scripts after every load. Its better if you use pageRequestManager's instance methods like this...

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)
    function onEndRequest(sender, args) {
       // your jquery code here
      });

it will work fine ...

Ignore mapping one property with Automapper

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

to be used as follow :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

thanks to Can Gencer for the tip :)

source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

When should we use intern method of String on String literals

Learn Java String Intern - once for all

Strings in java are immutable objects by design. Therefore, two string objects even with same value will be different objects by default. However, if we wish to save memory, we could indicate to use same memory by a concept called string intern.

The below rules would help you understand the concept in clear terms:

  1. String class maintains an intern-pool which is initially empty. This pool must guarantee to contain string objects with only unique values.
  2. All string literals having same value must be considered same memory-location object because they have otherwise no notion of distinction. Therefore, all such literals with same value will make a single entry in the intern-pool and will refer to same memory location.
  3. Concatenation of two or more literals is also a literal. (Therefore rule #2 will be applicable for them)
  4. Each string created as object (i.e. by any other method except as literal) will have different memory locations and will not make any entry in the intern-pool
  5. Concatenation of literals with non-literals will make a non-literal. Thus, the resultant object will have a new memory location and will NOT make an entry in the intern-pool.
  6. Invoking intern method on a string object, either creates a new object that enters the intern-pool or return an existing object from the pool that has same value. The invocation on any object which is not in the intern-pool, does NOT move the object to the pool. It rather creates another object that enters the pool.

Example:

String s1=new String (“abc”);
String s2=new String (“abc”);
If (s1==s2)  //would return false  by rule #4
If (“abc” == “a”+”bc” )  //would return true by rules #2 and #3
If (“abc” == s1 )  //would return false  by rules #1,2 and #4
If (“abc” == s1.intern() )  //would return true  by rules #1,2,4 and #6
If ( s1 == s2.intern() )      //wound return false by rules #1,4, and #6

Note: The motivational cases for string intern are not discussed here. However, saving of memory will definitely be one of the primary objectives.

Xcode 6: Keyboard does not show up in simulator

Simple way is just Press command + k

How to normalize a histogram in MATLAB?

For some Distributions, Cauchy I think, I have found that trapz will overestimate the area, and so the pdf will change depending on the number of bins you select. In which case I do

[N,h]=hist(q_f./theta,30000); % there Is a large range but most of the bins will be empty
plot(h,N/(sum(N)*mean(diff(h))),'+r')

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

Understanding unique keys for array children in React.js

Just add the unique key to the your Components

data.map((marker)=>{
    return(
        <YourComponents 
            key={data.id}     // <----- unique key
        />
    );
})

browser.msie error after update to jQuery 1.9.1

$.browser was deprecated in version 1.3 and removed in 1.9

You can verify this by viewing the documentation.

How stable is the git plugin for eclipse?

There is also gitclipse(based on JavaGit), but seems dead.

How to get JSON from URL in JavaScript?

Define a function like:

fetchRestaurants(callback) {
    fetch(`http://www.restaurants.com`)
       .then(response => response.json())
       .then(json => callback(null, json.restaurants))
       .catch(error => callback(error, null))
}

Then use it like this:

fetchRestaurants((error, restaurants) => {
    if (error) 
        console.log(error)
    else 
        console.log(restaurants[0])

});

C: Run a System Command and Get Output?

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

How can I force WebKit to redraw/repaint to propagate style changes?

I had this problem with a a number of divs that were inserted in another div with position: absolute, the inserted divs had no position attribute. When I changed this to position:relative it worked fine. (was really hard to pinpoint the problem)

In my case the elements where inserted by Angular with ng-repeat.

How to type a new line character in SQL Server Management Studio

You can paste the lines in from a text editor that uses UNIX-style line endings (CR+LF). I use Notepad++. First go to Settings/Preferences/New Document and change the format from Windows to Unix. Then open a new document, type in your lines, and copy them into SSMS.

ImportError: Cannot import name X

In my case, simply missed filename:

from A.B.C import func_a (x)

from A.B.C.D import func_a (O)

where D is file.

Options for HTML scraping?

I've used Beautiful Soup a lot with Python. It is much better than regular expression checking, because it works like using the DOM, even if the HTML is poorly formatted. You can quickly find HTML tags and text with simpler syntax than regular expressions. Once you find an element, you can iterate over it and its children, which is more useful for understanding the contents in code than it is with regular expressions. I wish Beautiful Soup existed years ago when I had to do a lot of screenscraping -- it would have saved me a lot of time and headache since HTML structure was so poor before people started validating it.

Ignore .pyc files in git repository

Thanks @Enrico for the answer.

Note if you're using virtualenv you will have several more .pyc files within the directory you're currently in, which will be captured by his find command.

For example:

./app.pyc
./lib/python2.7/_weakrefset.pyc
./lib/python2.7/abc.pyc
./lib/python2.7/codecs.pyc
./lib/python2.7/copy_reg.pyc
./lib/python2.7/site-packages/alembic/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/api.pyc

I suppose it's harmless to remove all the files, but if you only want to remove the .pyc files in your main directory, then just do

find "*.pyc" -exec git rm -f "{}" \;

This will remove just the app.pyc file from the git repository.

Custom Python list sorting

Even better:

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Taken from: https://docs.python.org/3/howto/sorting.html

asp.net Button OnClick event not firing

In my case I put required="required" inside CKEditor control.
Removing this attribute fixed the issue.
Before

<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server" required="required"></CKEditor:CKEditorControl>

After

<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server"></CKEditor:CKEditorControl>

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

AngularJS access scope from outside js function

This is how I did for my CRUDManager class initialized in Angular controller, which later passed over to jQuery button-click event defined outside the controller:

In Angular Controller:

        // Note that I can even pass over the $scope to my CRUDManager's constructor.
        var crudManager = new CRUDManager($scope, contextData, opMode);

        crudManager.initialize()
            .then(() => {
                crudManager.dataBind();
                $scope.crudManager = crudManager;
                $scope.$apply();
            })
            .catch(error => {
                alert(error);
            });

In jQuery Save button click event outside the controller:

    $(document).on("click", "#ElementWithNgControllerDefined #btnSave", function () {
        var ngScope = angular.element($("#ElementWithNgControllerDefined")).scope();
        var crudManager = ngScope.crudManager;
        crudManager.saveData()
            .then(finalData => {
               alert("Successfully saved!");
            })
            .catch(error => {
               alert("Failed to save.");
            });
    });

This is particularly important and useful when your jQuery events need to be placed OUTSIDE OF CONTROLLER in order to prevent it from firing twice.

Android: Clear Activity Stack

In my case, LoginActivity was closed as well. As a result,

Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK

did not help.

However, setting

Intent.FLAG_ACTIVITY_NEW_TASK

helped me.

Remove by _id in MongoDB console

db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

What is the purpose of .PHONY in a Makefile?

The best explanation is the GNU make manual itself: 4.6 Phony Targets section.

.PHONY is one of make's Special Built-in Target Names. There are other targets that you may be interested in, so it's worth skimming through these references.

When it is time to consider a .PHONY target, make will run its recipe unconditionally, regardless of whether a file with that name exists or what its last-modification time is.

You may also be interested in make's Standard Targets such as all and clean.

Psql list all tables

Connect to the database, then list the tables:

\c liferay
\dt

That's how I do it anyway.

You can combine those two commands onto a single line, if you prefer:

\c liferay \dt

CSS3 animate border color

You can try this also...

_x000D_
_x000D_
button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
}
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
}

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
}
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
}
.draw::after {
  bottom: 0;
  right: 0;
}
.draw:hover {
  color: #60daaa;
}
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
}
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
}
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
}
_x000D_
<section class="buttons">
  <button class="draw">Draw</button>
</section>
_x000D_
_x000D_
_x000D_

Change icon-bar (?) color in bootstrap

Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.

HTML

<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>

  <span class="icon-bar"></span>
  <span class="icon-bar"></span>
  <span class="icon-bar"></span>

  </button>
  <a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
  </a></div>

CSS

    .navbar-toggle, .icon-bar {
    border:1px solid orange;
}

BOOM...

How to change xampp localhost to another folder ( outside xampp folder)?

Please follow @Sourav's advice.

If after restarting the server you get errors, you may need to set your directory options as well. This is done in the <Directory> tag in httpd.conf. Make sure the final config looks like this:

DocumentRoot "C:\alan"
<Directory "C:\alan">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

How to use a different version of python during NPM install?

You can use --python option to npm like so:

npm install --python=python2.7

or set it to be used always:

npm config set python python2.7

Npm will in turn pass this option to node-gyp when needed.

(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )

Javascript - check array for value

Try this:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === value) {
        return i;
      }
    }

    return -1;
  }
}

// example
if ([1, 2, 3].indexOf(2) != -1) {
  // yay!
}

Duplicate / Copy records in the same MySQL table

The way that I usually go about it is using a temporary table. It's probably not computationally efficient but it seems to work ok! Here i am duplicating record 99 in its entirety, creating record 100.

CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;

UPDATE tmp SET id=100 WHERE id = 99;

INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;

Hope that works ok for you!

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

AngularJS not detecting Access-Control-Allow-Origin header?

I was sending requests from angularjs using $http service to bottle running on http://localhost:8090/ and I had to apply CORS otherwise I got request errors like "No 'Access-Control-Allow-Origin' header is present on the requested resource"

from bottle import hook, route, run, request, abort, response

#https://github.com/defnull/bottle/blob/master/docs/recipes.rst#using-the-hooks-plugin

@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'

HTML - Display image after selecting filename

This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

An elegant way to implement this would be to make an extension method, like this:

public static class Extensions
{
    public static List<string> GetSelectedItems(this CheckBoxList cbl)
    {
        var result = new List<string>();

        foreach (ListItem item in cbl.Items)
            if (item.Selected)
                result.Add(item.Value);

        return result;
    }
}

I can then use something like this to compose a string will all values separated by ';':

string.Join(";", cbl.GetSelectedItems());

Render HTML to an image

You can add reference HtmlRenderer to your project and do the following,

string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));

Get the directory from a file path in java (android)

Yes. First, construct a File representing the image path:

File file = new File(a);

If you're starting from a relative path:

file = new File(file.getAbsolutePath());

Then, get the parent:

String dir = file.getParent();

Or, if you want the directory as a File object,

File dirAsFile = file.getParentFile();

Display Adobe pdf inside a div

You could create an image thumbnail, and link it to the actual pdf as an inline popup using something like http://orangoo.com/labs/GreyBox/

Pan & Zoom Image

To zoom relative to the mouse position, all you need is:

var position = e.GetPosition(image1);
image1.RenderTransformOrigin = new Point(position.X / image1.ActualWidth, position.Y / image1.ActualHeight);