Programs & Examples On #Adobe

Adobe Systems is a software company headquartered in San Jose, California, USA. It is best known for the technology behind PDF, Photoshop, and Flash.

Adobe Acrobat Pro make all pages the same dimension

With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.

CSS div element - how to show horizontal scroll bars only?

This solution is without height/width specification for the father div so it will be responsive to window resizing and most useful cause horizontal scrollbars appears just if needed.

.container{
    padding:20px;
    border:dotted 1px;
    white-space:nowrap;
    overflow-x:auto;
}

.box{
    width:100px;
    height:180px;
    background-color: red;
    margin:10px;
    display:inline-block
}

Take a look at DEMO

How to call a View Controller programmatically?

You can call ViewController this way, If you want with NavigationController

enter image description here

1.In current Screen : Load new screen

VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];

2.1 In Loaded View : add below in .h file

@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>

2.2 In Loaded View : add below in .m file

  @implementation VerifyExpViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.delegate = self;
    [self setNavigationBar];
}
-(void)setNavigationBar
{
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}

-(void)onBackButtonTap:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
    //todo for save button
}

@end

Hope this will be useful for someone there :)

Forbidden You don't have permission to access / on this server

Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use

Require all granted

instead of

Order allow,deny
Allow from all

The Order and Allow directives are deprecated in Apache 2.4.

How to set a variable to current date and date-1 in linux?

you should man date first

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

Create Word Document using PHP in Linux

real Word documents

If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative is:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

Make sure you don't use external stylesheets. Everything should be in the same file.

Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type header along does not constitute a real file format conversion.

Upgrading Node.js to latest version

brew upgrade node

will upgrade to the latest version of the node

How can I pass variable to ansible playbook in the command line?

Reading the docs I find the section Passing Variables On The Command Line, that gives this example:

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

Others examples demonstrate how to load from JSON string (=1.2) or file (=1.3)

isPrime Function for Python Language

def is_prime(n):
if (n==2 or n==3): return True
if(n<=1 or n%2==0 or n%3==0 ): return False
for i in range(6,int((n**0.5)) + 2,6):
    if(n%(i-1)==0 or n%(i+1)==0):
        return False
return True

How to use jQuery with TypeScript

I believe you may need the Typescript typings for JQuery. Since you said you're using Visual Studio, you could use Nuget to get them.

https://www.nuget.org/packages/jquery.TypeScript.DefinitelyTyped/

The command in Nuget Package Manager Console is

Install-Package jquery.TypeScript.DefinitelyTyped

Update: As noted in the comment this package hasn't been updated since 2016. But you can still visit their Github page at https://github.com/DefinitelyTyped/DefinitelyTyped and download the types. Navigate the folder for your library and then download the index.d.ts file there. Pop it anywhere in your project directory and VS should use it right away.

AngularJS - Create a directive that uses ng-model

I took a combo of all answers, and now have two ways of doing this with the ng-model attribute:

  • With a new scope which copies ngModel
  • With the same scope which does a compile on link

_x000D_
_x000D_
var app = angular.module('model', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
  $scope.name = "Felipe";_x000D_
  $scope.label = "The Label";_x000D_
});_x000D_
_x000D_
app.directive('myDirectiveWithScope', function() {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {_x000D_
      ngModel: '=',_x000D_
    },_x000D_
    // Notice how label isn't copied_x000D_
    template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myDirectiveWithChildScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    // Notice how label is visible in the scope_x000D_
    template: '<div class="some"><label>{{label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      $('input',element).attr('ng-model', model);_x000D_
      return $compile(element)($scope);_x000D_
    }_x000D_
  };_x000D_
});_x000D_
app.directive('myDirectiveWithoutScope', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',_x000D_
    replace: true,_x000D_
    link: function ($scope, element) {_x000D_
      // element will be the div which gets the ng-model on the original directive_x000D_
      var model = element.attr('ng-model');_x000D_
      return $compile($('input',element).attr('ng-model', model))($scope);_x000D_
    }_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirectiveIsolate', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: {},_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirectiveChild', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    scope: true,_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});_x000D_
app.directive('myReplacedDirective', function($compile) {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    template: '<input class="some">',_x000D_
    replace: true_x000D_
  };_x000D_
});
_x000D_
.some {_x000D_
  border: 1px solid #cacaca;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>_x000D_
<div ng-app="model" ng-controller="MainCtrl">_x000D_
  This scope value <input ng-model="name">, label: "{{label}}"_x000D_
  <ul>_x000D_
    <li>With new isolate scope (label from parent):_x000D_
      <my-directive-with-scope ng-model="name"></my-directive-with-scope>_x000D_
    </li>_x000D_
    <li>With new child scope:_x000D_
      <my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>_x000D_
    </li>_x000D_
    <li>Same scope:_x000D_
      <my-directive-without-scope ng-model="name"></my-directive-without-scope>_x000D_
    </li>_x000D_
    <li>Replaced element, isolate scope:_x000D_
      <my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>_x000D_
    </li>_x000D_
    <li>Replaced element, child scope:_x000D_
      <my-replaced-directive-child ng-model="name"></my-replaced-directive-child>_x000D_
    </li>_x000D_
    <li>Replaced element, same scope:_x000D_
      <my-replaced-directive ng-model="name"></my-replaced-directive>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope._x000D_
  <p>Also notice how removing jQuery makes it so only the new-isolate-scope version works._x000D_
  <p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure I like the compiling at link time. However, if you're just replacing the element with another you don't need to do that.

All in all I prefer the first one. Simply set scope to {ngModel:"="} and set ng-model="ngModel" where you want it in your template.

Update: I inlined the code snippet and updated it for Angular v1.2. Turns out that isolate scope is still best, especially when not using jQuery. So it boils down to:

  • Are you replacing a single element: Just replace it, leave the scope alone, but note that replace is deprecated for v2.0:

    app.directive('myReplacedDirective', function($compile) {
      return {
        restrict: 'E',
        template: '<input class="some">',
        replace: true
      };
    });
    
  • Otherwise use this:

    app.directive('myDirectiveWithScope', function() {
      return {
        restrict: 'E',
        scope: {
          ngModel: '=',
        },
        template: '<div class="some"><input ng-model="ngModel"></div>'
      };
    });
    

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

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

Working with SQL views in Entity Framework Core

EF Core supports the views, here is the details.

This feature was added in EF Core 2.1 under the name of query types. In EF Core 3.0 the concept was renamed to keyless entity types. The [Keyless] Data Annotation became available in EFCore 5.0.

It is working not that much different than normal entities; but has some special points. According documentation:

  • Cannot have a key defined.
  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Are never discovered by convention.
  • Only support a subset of navigation mapping capabilities, specifically:
  • They may never act as the principal end of a relationship.
  • They may not have navigations to owned entities
  • They can only contain reference navigation properties pointing to regular entities.
  • Entities cannot contain navigation properties to keyless entity types.
  • Need to be configured with a [Keyless] data annotation or a .HasNoKey() method call.
  • May be mapped to a defining query. A defining query is a query declared in the model that acts as a data source for a keyless entity type

It is working like below:

public class Blog
{
   public int BlogId { get; set; }
   public string Name { get; set; }
   public string Url { get; set; }
   public ICollection<Post> Posts { get; set; }
}

public class Post
{
   public int PostId { get; set; }
   public string Title { get; set; }
   public string Content { get; set; }
   public int BlogId { get; set; }
}

If you don't have an existing View at database you should create like below:

db.Database.ExecuteSqlRaw(
@"CREATE VIEW View_BlogPostCounts AS 
    SELECT b.Name, Count(p.PostId) as PostCount 
    FROM Blogs b
    JOIN Posts p on p.BlogId = b.BlogId
    GROUP BY b.Name");

And than you should have a class to hold the result from the database view:

  public class BlogPostsCount
  {
     public string BlogName { get; set; }
     public int PostCount { get; set; }
  }

And than configure the keyless entity type in OnModelCreating using the HasNoKey:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder
          .Entity<BlogPostsCount>(eb =>
          {
             eb.HasNoKey();
             eb.ToView("View_BlogPostCounts");
             eb.Property(v => v.BlogName).HasColumnName("Name");
          });
    }

And just configure the DbContext to include the DbSet:

public DbSet<BlogPostsCount> BlogPostCounts { get; set; }

Using the Web.Config to set up my SQL database connection string?

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class form_city : System.Web.UI.Page
{
    connection con = new connection();
    DataTable dtable;
    string status = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBoxWatermarkExtender1.WatermarkText = "Enter State Name !";        
        if (!IsPostBack)
        {
            status = "Active";
            fillgrid();
            Session.Add("ope", "Listing");
        }
    }
    protected void fillgrid()
    {
        //Session.Add("ope", "Listing");
        string query = "select *";
        query += "from State_Detail where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        grdList.DataSource = dtable;
        grdList.DataBind();
        lbtnBack.Visible = false;
    }
    protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdList.PageIndex = e.NewPageIndex;
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";
        fillgrid();
    }
    public string GetImage(string status)
    {
        if (status == "Active")
            return "~/images/green_acti.png";
        else
            return "~/images/red_acti.png";
    }
    protected void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string st = "Inactive";
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.RowIndex].Values[0]);
        string query = "update State_Detail set Status='" + st + "'";
        query += " where State_Id=" + State_Id;
        con.sqlInsUpdDel(query);
        status = "Active";
        fillgrid();
    }    
    protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            string query = "select * ";
            query += "from State_Detail where State_Id=" + e.CommandArgument;
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            lbtnBack.Visible = true;
        }
    }
    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        Session.Add("ope", "Listing");
        if (txtDepId.Text != "")
        {
            string query = "select * from State_Detail where State_Name like '" + txtDepId.Text + "%'";
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            txtDepId.Text = "";
        }
    }
    protected void grdList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.NewEditIndex].Values[0]);
        Session.Add("ope", "Edit");
        Session.Add("State_Id", State_Id);
        Response.Redirect("form_state.aspx");
    }

    protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
    {
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";

        string query = "select * from State_Detail";
        query += " where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        DataView dview = new DataView(dtable);
        dview.Sort = e.SortExpression + " asc";
        grdList.DataSource = dview;
        grdList.DataBind();
    }
}
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "Status")))%>' AlternateText='<%# Bind("Status") %>' runat="server" />

unix sort descending order

To list files based on size in asending order.

find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}'  | sort -n\

How to convert string to integer in PowerShell

Once you have selected the highest value, which is "12" in my example, you can then declare it as integer and increment your value:

$FileList = "1", "2", "11"
$foldername = [int]$FileList[2] + 1
$foldername

Disable firefox same origin policy

In about:config add content.cors.disable (empty string).

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

convert htaccess to nginx

Use this: http://winginx.com/htaccess

Online converter, nice way and time saver ;)

What's the difference between a POST and a PUT HTTP REQUEST?

The difference between POST and PUT is that PUT is idempotent, that means, calling the same PUT request multiple times will always produce the same result(that is no side effect), while on the other hand, calling a POST request repeatedly may have (additional) side effects of creating the same resource multiple times.

GET : Requests using GET only retrieve data , that is it requests a representation of the specified resource

POST : It sends data to the server to create a resource. The type of the body of the request is indicated by the Content-Type header. It often causes a change in state or side effects on the server

PUT : Creates a new resource or replaces a representation of the target resource with the request payload

PATCH : It is used to apply partial modifications to a resource

DELETE : It deletes the specified resource

TRACE : It performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism

OPTIONS : It is used to describe the communication options for the target resource, the client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server.

HEAD : It asks for a response identical to that of a GET request, but without the response body

CONNECT : It establishes a tunnel to the server identified by the target resource , can be used to access websites that use SSL (HTTPS)

Git says remote ref does not exist when I delete remote branch

Given that the remote branch is remotes/origin/test you can use two ways:

git push origin --delete test

and

git branch -D -r origin/test

How do you implement a Stack and a Queue in JavaScript?

A little late answer but i think this answer should be here. Here is an implementation of Queue with O(1) enqueue and O(1) dequeue using the sparse Array powers.

Sparse Arrays in JS are mostly disregarded but they are in fact a gem and we should put their power in use at some critical tasks.

So here is a skeleton Queue implementation which extends the Array type and does it's things in O(1) all the way.

_x000D_
_x000D_
class Queue extends Array {
  constructor(){
    super()
    Object.defineProperty(this,"head",{ value       : 0
                                      , writable    : true
                                      , enumerable  : false
                                      , configurable: false
                                      });
  }
  enqueue(x) {
    this.push(x);
    return this;
  }
  dequeue() {
    var first;
    return this.head < this.length ? ( first = this[this.head]
                                     , delete this[this.head++]
                                     , first
                                     )
                                   : void 0; // perfect undefined
  }
  peek() {
    return this[this.head];
  }
}

var q = new Queue();
console.log(q.dequeue());      // doesn't break
console.log(q.enqueue(10));    // add 10
console.log(q.enqueue("DIO")); // add "DIO" (Last In Line cCc R.J.DIO reis cCc)
console.log(q);                // display q
console.log(q.dequeue());      // lets get the first one in the line
console.log(q.dequeue());      // lets get DIO out from the line
_x000D_
.as-console-wrapper {
  max-height: 100% !important;
}
_x000D_
_x000D_
_x000D_

So do we have a potential memory leak here? No i don't think so. JS sparse arrays are non contiguous. Accordingly deleted items shouln't be a part of the array's memory footprint. Let the GC do it's job for you. It's free of charge.

One potential problem is that, the length property grows indefinitely as you keep enqueueing items to the queue. However still one may implement an auto refreshing (condensing) mechanism to kick in once the length reaches to a certain value.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Plot multiple lines in one graph

The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How to determine the current iPhone/device model?

I made this "pure Swift" extension on UIDevice.

This version works in Swift 2 or higher If you use an earlier version please use an older version of my answer.

If you are looking for a more elegant solution you can use my µ-framework DeviceKit published on GitHub (also available via CocoaPods, Carthage and Swift Package Manager).

Here's the code:

import UIKit

public extension UIDevice {

    static let modelName: String = {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity
            #if os(iOS)
            switch identifier {
            case "iPod5,1":                                 return "iPod touch (5th generation)"
            case "iPod7,1":                                 return "iPod touch (6th generation)"
            case "iPod9,1":                                 return "iPod touch (7th generation)"
            case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
            case "iPhone4,1":                               return "iPhone 4s"
            case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
            case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
            case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
            case "iPhone7,2":                               return "iPhone 6"
            case "iPhone7,1":                               return "iPhone 6 Plus"
            case "iPhone8,1":                               return "iPhone 6s"
            case "iPhone8,2":                               return "iPhone 6s Plus"
            case "iPhone8,4":                               return "iPhone SE"
            case "iPhone9,1", "iPhone9,3":                  return "iPhone 7"
            case "iPhone9,2", "iPhone9,4":                  return "iPhone 7 Plus"
            case "iPhone10,1", "iPhone10,4":                return "iPhone 8"
            case "iPhone10,2", "iPhone10,5":                return "iPhone 8 Plus"
            case "iPhone10,3", "iPhone10,6":                return "iPhone X"
            case "iPhone11,2":                              return "iPhone XS"
            case "iPhone11,4", "iPhone11,6":                return "iPhone XS Max"
            case "iPhone11,8":                              return "iPhone XR"
            case "iPhone12,1":                              return "iPhone 11"
            case "iPhone12,3":                              return "iPhone 11 Pro"
            case "iPhone12,5":                              return "iPhone 11 Pro Max"
            case "iPhone12,8":                              return "iPhone SE (2nd generation)"
            case "iPhone13,1":                              return "iPhone 12 mini"
            case "iPhone13,2":                              return "iPhone 12"
            case "iPhone13,3":                              return "iPhone 12 Pro"
            case "iPhone13,4":                              return "iPhone 12 Pro Max"
            case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
            case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad (3rd generation)"
            case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad (4th generation)"
            case "iPad6,11", "iPad6,12":                    return "iPad (5th generation)"
            case "iPad7,5", "iPad7,6":                      return "iPad (6th generation)"
            case "iPad7,11", "iPad7,12":                    return "iPad (7th generation)"
            case "iPad11,6", "iPad11,7":                    return "iPad (8th generation)"
            case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
            case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
            case "iPad11,3", "iPad11,4":                    return "iPad Air (3rd generation)"
            case "iPad13,1", "iPad13,2":                    return "iPad Air (4th generation)"
            case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad mini"
            case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad mini 2"
            case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad mini 3"
            case "iPad5,1", "iPad5,2":                      return "iPad mini 4"
            case "iPad11,1", "iPad11,2":                    return "iPad mini (5th generation)"
            case "iPad6,3", "iPad6,4":                      return "iPad Pro (9.7-inch)"
            case "iPad7,3", "iPad7,4":                      return "iPad Pro (10.5-inch)"
            case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch) (1st generation)"
            case "iPad8,9", "iPad8,10":                     return "iPad Pro (11-inch) (2nd generation)"
            case "iPad6,7", "iPad6,8":                      return "iPad Pro (12.9-inch) (1st generation)"
            case "iPad7,1", "iPad7,2":                      return "iPad Pro (12.9-inch) (2nd generation)"
            case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)"
            case "iPad8,11", "iPad8,12":                    return "iPad Pro (12.9-inch) (4th generation)"
            case "AppleTV5,3":                              return "Apple TV"
            case "AppleTV6,2":                              return "Apple TV 4K"
            case "AudioAccessory1,1":                       return "HomePod"
            case "AudioAccessory5,1":                       return "HomePod mini"
            case "i386", "x86_64":                          return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
            default:                                        return identifier
            }
            #elseif os(tvOS)
            switch identifier {
            case "AppleTV5,3": return "Apple TV 4"
            case "AppleTV6,2": return "Apple TV 4K"
            case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
            default: return identifier
            }
            #endif
        }

        return mapToDevice(identifier: identifier)
    }()

}

You call it like this:

let modelName = UIDevice.modelName

For real devices it returns e.g. "iPad Pro 9.7 Inch", for simulators it returns "Simulator " + Simulator identifier, e.g. "Simulator iPad Pro 9.7 Inch"

Check if a value exists in pandas dataframe index

df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 

adding line break

Try using \n when concatenating strings, as in this example:

var name = "Raihan";
var ID = "1234";
Console.WriteLine(name + "\n" + ID);

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

How do I get the coordinates of a mouse click on a canvas element?

I'm not sure what's the point of all these answers that loop through parent elements and do all kinds of weird stuff.

The HTMLElement.getBoundingClientRect method is designed to to handle actual screen position of any element. This includes scrolling, so stuff like scrollTop is not needed:

(from MDN) The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle

Normal image

The very simplest approach was already posted here. This is correct as long as no wild CSS rules are involved.

Handling stretched canvas/image

When image pixel width isn't matched by it's CSS width, you'll need to apply some ratio on pixel values:

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();
  var top = rect.top;
  var bottom = rect.bottom;
  var left = rect.left;
  var right = rect.right;
  //Recalculate mouse offsets to relative offsets
  x = event.clientX - left;
  y = event.clientY - top;
  //Also recalculate offsets of canvas is stretched
  var width = right - left;
  //I use this to reduce number of calculations for images that have normal size 
  if(this.width!=width) {
    var height = bottom - top;
    //changes coordinates by ratio
    x = x*(this.width/width);
    y = y*(this.height/height);
  } 
  //Return as an array
  return [x,y];
}

As long as the canvas has no border, it works for stretched images (jsFiddle).

Handling CSS borders

If the canvas has thick border, the things get little complicated. You'll literally need to subtract the border from the bounding rectangle. This can be done using .getComputedStyle. This answer describes the process.

The function then grows up a little:

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();
  var top = rect.top;
  var bottom = rect.bottom;
  var left = rect.left;
  var right = rect.right;
  //Subtract border size
  // Get computed style
  var styling=getComputedStyle(this,null);
  // Turn the border widths in integers
  var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);
  var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);
  var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);
  var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);
  //Subtract border from rectangle
  left+=leftBorder;
  right-=rightBorder;
  top+=topBorder;
  bottom-=bottomBorder;
  //Proceed as usual
  ...
}

I can't think of anything that would confuse this final function. See yourself at JsFiddle.

Notes

If you don't like modifying the native prototypes, just change the function and call it with (canvas, event) (and replace any this with canvas).

What's the difference between ViewData and ViewBag?

One main difference I noticed between ViewData and ViewBag is:

ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.

ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.

Ex: Controller code.

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

View Code.

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId &nbsp;&nbsp;&nbsp;@item.productName</li>
            }
        </ul>

OutPut Screen.

enter image description here

GET parameters in the URL with CodeIgniter

This worked for me :

<?php
$url = parse_url($_SERVER['REQUEST_URI']);
parse_str($url['query'], $params);
?>

$params array contains the parameters passed after the ? character

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Probably you didn't add your room class to child RoomDatabase child class in @Database(entities = {your_classes})

'python' is not recognized as an internal or external command

i solved this by running CMD in administration mode, so try this.

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

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

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

What is the naming convention in Python for variable and function names?

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"

How to pad zeroes to a string?

width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005

See the print documentation for all the exciting details!

Update for Python 3.x (7.5 years later)

That last line should now be:

print("%0*d" % (width, x))

I.e. print() is now a function, not a statement. Note that I still prefer the Old School printf() style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.

What is the difference between Step Into and Step Over in a debugger

You can't go through the details of the method by using the step over. If you want to skip the current line, you can use step over, then you only need to press the F6 for only once to move to the next line. And if you think there's someting wrong within the method, use F5 to examine the details.

Vue template or render function not defined yet I am using neither?

The reason you're receiving that error is that you're using the runtime build which doesn't support templates in HTML files as seen here vuejs.org

In essence what happens with vue loaded files is that their templates are compile time converted into render functions where as your base function was trying to compile from your html element.

How to create Drawable from resource

Get Drawable from vector resource irrespective of, whether its vector or not:

AppCompatResources.getDrawable(context, R.drawable.icon);

Note:
ContextCompat.getDrawable(context, R.drawable.icon); will produce android.content.res.Resources$NotFoundException for vector resource.

Mocking methods of local scope objects with Mockito

You can do this by creating a factory method in MyObject:

class MyObject {
    public static MyObject create() {
      return new MyObject();
    }
}

then mock that with PowerMock.

However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.

In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:

void method1(MyObject obj1) {
   obj1.method1();
}

passing in the dependency, which you can easily mock for the unit test.

How to find index of STRING array in Java from a given value?

for (int i = 0; i < Types.length; i++) {
    if(TYPES[i].equals(userString)){
        return i;
    }
}
return -1;//not found

You can do this too:

return Arrays.asList(Types).indexOf(userSTring);

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

angularjs ng-style: background-image isn't working

If we have a dynamic value that needs to go in a css background or background-image attribute, it can be just a bit more tricky to specify.

Let’s say we have a getImage() function in our controller. This function returns a string formatted similar to this: url(icons/pen.png). If we do, the ngStyle declaration is specified the exact same way as before:

ng-style="{ 'background-image': getImage() }"

Make sure to put quotes around the background-image key name. Remember, this must be formatted as a valid Javascript object key.

Vue.js data-bind style backgroundImage not working

Based on my knowledge, if you put your image folder in your public folder, you can just do the following:

   <div :style="{backgroundImage: `url(${project.imagePath})`}"></div>

If you put your images in the src/assets/, you need to use require. Like this:

   <div :style="{backgroundImage: 'url('+require('@/assets/'+project.image)+')'}">. 
   </div>

One important thing is that you cannot use an expression that contains the full URL like this project.image = '@/assets/image.png'. You need to hardcode the '@assets/' part. That was what I've found. I think the reason is that in Webpack, a context is created if your require contains expressions, so the exact module is not known on compile time. Instead, it will search for everything in the @/assets folder. More info could be found here. Here is another doc explains how the Vue loader treats the link in single file components.

How to re-enable right click so that I can inspect HTML elements in Chrome?

I built upon @Chema solution and added resetting pointer-events and user-select. If they are set to none for an image, right-clicking it does not invoke the context menu for the image with options to view or save it.

javascript:function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll('body'); removeContextMenuOnAll('img'); removeContextMenuOnAll('td'); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); enablePointerEvents(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener('contextmenu', bringBackDefault, true); el.addEventListener('dragstart', bringBackDefault, true); el.addEventListener('selectstart', bringBackDefault, true); el.addEventListener('click', bringBackDefault, true); el.addEventListener('mousedown', bringBackDefault, true); el.addEventListener('mouseup', bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener('contextmenu', bringBackDefault, true); el.removeEventListener('dragstart', bringBackDefault, true); el.removeEventListener('selectstart', bringBackDefault, true); el.removeEventListener('click', bringBackDefault, true); el.removeEventListener('mousedown', bringBackDefault, true); el.removeEventListener('mouseup', bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } function enablePointerEvents(el) {  if (!el) return; el.style.pointerEvents='auto'; el.style.webkitTouchCallout='default'; el.style.webkitUserSelect='auto'; el.style.MozUserSelect='auto'; el.style.msUserSelect='auto'; el.style.userSelect='auto'; enablePointerEvents(el.parentElement); } enableContextMenu();

batch file to list folders within a folder to one level

print all folders name where batch script file is kept

for /d %%d in (*.*) do (
    set test=%%d
    echo !test!
)
pause

const char* concatenation

Using std::string:

#include <string>

std::string result = std::string(one) + std::string(two);

The data-toggle attributes in Twitter Bootstrap

From the Bootstrap Docs:

<!--Activate a modal without writing JavaScript. Set data-toggle="modal" on a 
controller element, like a button, along with a data-target="#foo" or href="#foo" 
to target a specific modal to toggle.-->

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

Xcode 'CodeSign error: code signing is required'

Another possibility - When you Build for Archive make sure your Archive choice in your scheme is set for Distribution, not Release.

Go to Product -> Edit Scheme This brings up a new dialog.

Select Archive on the left. Make sure the build configuration is Distribution.

Search for a particular string in Oracle clob column

Use dbms_lob.instr and dbms_lob.substr, just like regular InStr and SubstStr functions.
Look at simple example:

SQL> create table t_clob(
  2    id number,
  3    cl clob
  4  );

Tabela zosta¦a utworzona.

SQL> insert into t_clob values ( 1, ' xxxx abcd xyz qwerty 354657 [] ' );

1 wiersz zosta¦ utworzony.

SQL> declare
  2    i number;
  3  begin
  4    for i in 1..400 loop
  5        update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
  6    end loop;
  7    update t_clob set cl = cl || ' CALCULATION=[N]NEW.PRODUCT_NO=[T9856] OLD.PRODUCT_NO=[T9852].... -- with other text ';
  8    for i in 1..400 loop
  9        update t_clob set cl = cl || ' xxxx abcd xyz qwerty 354657 [] ';
 10    end loop;
 11  end;
 12  /

Procedura PL/SQL zosta¦a zako?czona pomytlnie.

SQL> commit;

Zatwierdzanie zosta¦o uko?czone.
SQL> select length( cl ) from t_clob;

LENGTH(CL)
----------
     25717

SQL> select dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) from t_clob;

DBMS_LOB.INSTR(CL,'NEW.PRODUCT_NO=[')
-------------------------------------
                                12849

SQL> select dbms_lob.substr( cl, 5,dbms_lob.instr( cl, 'NEW.PRODUCT_NO=[' ) + length( 'NEW.PRODUCT_NO=[') ) new_product
  2  from t_clob;

NEW_PRODUCT
--------------------------------------------------------------------------------
T9856

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

How to get < span > value?

You need to change your code as below:-

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

After doing this you will get the tag value in alert.

Android ClassNotFoundException: Didn't find class on path

I faced this problem when I tried to build and install my app to a Android 8.1.0 (API 26)phone.

The only reason is that I added android:hasCode="false" to the application tag in the manifest file. However, it worked on API 24 with the same code when I tried several months ago (STRANGE?).

After removing that attribute, the problem disappears.

Python: Adding element to list while iterating

make copy of your original list, iterate over it, see the modified code below

for a in myarr[:]:
      if somecond(a):
          myarr.append(newObj())

How to mount the android img file under linux?

See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files

First you need to "uncompress" userdata.img with simg2img, then you can mount it via the loop device.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

@media (min-width:992px)
    {
        .container{width:960px}
    }
@media (min-width:1200px)
    {
        .container{width:960px}
    }

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

Parsing JSON objects for HTML table

This code will help a lot

function isObject(data){
    var tb = document.createElement("table");

    if(data !=null) {
        var keyOfobj = Object.keys(data);
        var ValOfObj = Object.values(data);

        for (var i = 0; i < keyOfobj.length; i++) {
            var tr = document.createElement('tr');
            var td = document.createElement('td');
            var key = document.createTextNode(keyOfobj[i]);

            td.appendChild(key);
            tr.appendChild(td);
            tb.appendChild(tr);

            if(typeof(ValOfObj[i]) == "object") {

                if(ValOfObj[i] !=null) {
                    tr.setAttribute("style","font-weight: bold");   
                    isObject(ValOfObj[i]);
                } else {
                    var td = document.createElement('td');
                    var value = document.createTextNode(ValOfObj[i]);

                    td.appendChild(value);
                    tr.appendChild(td);
                    tb.appendChild(tr);
                }
            } else {
                var td = document.createElement('td');
                var value = document.createTextNode(ValOfObj[i]);

                td.appendChild(value);
                tr.appendChild(td);
                tb.appendChild(tr);
            }
        }
    }
}

Flattening a shallow list in Python

def is_iterable(item):
   return isinstance(item, list) or isinstance(item, tuple)


def flatten(items):
    for i in items:
        if is_iterable(item):
            for m in flatten(i):
                yield m
        else:
            yield i

Test:

print list(flatten2([1.0, 2, 'a', (4,), ((6,), (8,)), (((8,),(9,)), ((12,),(10)))]))

How can I programmatically get the MAC address of an iphone

A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...

- (NSString *)getLocalIPAddress
{
    NSArray *ipAddresses = [[NSHost currentHost] addresses];
    NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.allowsFloats = NO;

    for (NSString *potentialIPAddress in sortedIPAddresses)
    {
        if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
            continue;
        }

        NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];

        BOOL isMatch = YES;

        for (NSString *ipPart in ipParts) {
            if (![numberFormatter numberFromString:ipPart]) {
                isMatch = NO;
                break;
            }
        }
        if (isMatch) {
            return potentialIPAddress;
        }
    }

    // No IP found
    return @"?.?.?.?";
}

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

Python "SyntaxError: Non-ASCII character '\xe2' in file"

If it helps anybody, for me that happened because I was trying to run a Django implementation in python 3.4 with my python 2.7 command

How to print out the method name and line number and conditionally disable NSLog?

For some time I've been using a site of macros adopted from several above. Mine focus on logging in the Console, with the emphasis on controlled & filtered verbosity; if you don't mind a lot of log lines but want to easily switch batches of them on & off, then you might find this useful.

First, I optionally replace NSLog with printf as described by @Rodrigo above

#define NSLOG_DROPCHAFF//comment out to get usual date/time ,etc:2011-11-03 13:43:55.632 myApp[3739:207] Hello Word

#ifdef NSLOG_DROPCHAFF
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#endif

Next, I switch logging on or off.

#ifdef DEBUG
#define LOG_CATEGORY_DETAIL// comment out to turn all conditional logging off while keeping other DEBUG features
#endif

In the main block, define various categories corresponding to modules in your app. Also define a logging level above which logging calls won't be called. Then define various flavours of NSLog output

#ifdef LOG_CATEGORY_DETAIL

    //define the categories using bitwise leftshift operators
    #define kLogGCD (1<<0)
    #define kLogCoreCreate (1<<1)
    #define kLogModel (1<<2)
    #define kLogVC (1<<3)
    #define kLogFile (1<<4)
    //etc

    //add the categories that should be logged...
    #define kLOGIFcategory kLogModel+kLogVC+kLogCoreCreate

    //...and the maximum detailLevel to report (use -1 to override the category switch)
    #define kLOGIFdetailLTEQ 4

    // output looks like this:"-[AppDelegate myMethod] log string..."
    #   define myLog(category,detailLevel,format, ...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"%s " format), __PRETTY_FUNCTION__, ##__VA_ARGS__);}

    // output also shows line number:"-[AppDelegate myMethod][l17]  log string..."
    #   define myLogLine(category,detailLevel,format, ...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"%s[l%i] " format), __PRETTY_FUNCTION__,__LINE__ ,##__VA_ARGS__);}

    // output very simple:" log string..."
    #   define myLogSimple(category,detailLevel,format, ...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"" format), ##__VA_ARGS__);}

    //as myLog but only shows method name: "myMethod: log string..."
    // (Doesn't work in C-functions)
    #   define myLog_cmd(category,detailLevel,format,...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"%@: " format), NSStringFromSelector(_cmd), ##__VA_ARGS__);}

    //as myLogLine but only shows method name: "myMethod>l17: log string..."
    #   define myLog_cmdLine(category,detailLevel,format, ...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"%@>l%i: " format), NSStringFromSelector(_cmd),__LINE__ , ##__VA_ARGS__);}

    //or define your own...
   // # define myLogEAGLcontext(category,detailLevel,format, ...) if(detailLevel<0 || ((category&kLOGIFcategory)&&detailLevel<= kLOGIFdetailLTEQ)) {NSLog((@"%s>l%i (ctx:%@)" format), __PRETTY_FUNCTION__,__LINE__ ,[EAGLContext currentContext], ##__VA_ARGS__);}

#else
    #   define myLog_cmd(...)
    #   define myLog_cmdLine(...)
    #   define myLog(...)
    #   define myLogLine(...)
    #   define myLogSimple(...)
    //#   define myLogEAGLcontext(...)
#endif

Thus, with current settings for kLOGIFcategory and kLOGIFdetailLTEQ, a call like

myLogLine(kLogVC, 2, @"%@",self);

will print but this won't

myLogLine(kLogGCD, 2, @"%@",self);//GCD not being printed

nor will

myLogLine(kLogGCD, 12, @"%@",self);//level too high

If you want to override the settings for an individual log call, use a negative level:

myLogLine(kLogGCD, -2, @"%@",self);//now printed even tho' GCD category not active.

I find the few extra characters of typing each line are worth as I can then

  1. Switch an entire category of comment on or off (e.g. only report those calls marked Model)
  2. report on fine detail with higher level numbers or just the most important calls marked with lower numbers

I'm sure many will find this a bit of an overkill, but just in case someone finds it suits their purposes..

How to add time to DateTime in SQL

The following is simple and works on SQL Server 2008 (SP3) and up:

PRINT @@VERSION
PRINT GETDATE()
PRINT GETDATE() + '01:00:00'
PRINT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE()))) + '01:00:00'

With output:

Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (X64) 
Mar 15 2017  6:17PM
Mar 15 2017  7:17PM
Mar 15 2017  1:00AM

How to keep the spaces at the end and/or at the beginning of a String?

It does not work with xml:space="preserve"

so I did it the quickest way =>

I simply added a +" "+ where I needed it ...

String message_all_pairs_found = getString(R.string.Toast_Memory_GameWon_part1)+" "+total_flips+" "+getString(R.string.Toast_Memory_GameWon_part2);

Rename Files and Directories (Add Prefix)

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

What is setBounds and how do I use it?

setBounds is used to define the bounding rectangle of a component. This includes it's position and size.

The is used in a number of places within the framework.

  • It is used by the layout manager's to define the position and size of a component within it's parent container.
  • It is used by the paint sub system to define clipping bounds when painting the component.

For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.

Export pictures from excel file into jpg using VBA

This code:

Option Explicit

Sub ExportMyPicture()

     Dim MyChart As String, MyPicture As String
     Dim PicWidth As Long, PicHeight As Long

     Application.ScreenUpdating = False
     On Error GoTo Finish

     MyPicture = Selection.Name
     With Selection
           PicHeight = .ShapeRange.Height
           PicWidth = .ShapeRange.Width
     End With

     Charts.Add
     ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
     Selection.Border.LineStyle = 0
     MyChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)

     With ActiveSheet
           With .Shapes(MyChart)
                 .Width = PicWidth
                 .Height = PicHeight
           End With

           .Shapes(MyPicture).Copy

           With ActiveChart
                 .ChartArea.Select
                 .Paste
           End With

           .ChartObjects(1).Chart.Export Filename:="MyPic.jpg", FilterName:="jpg"
           .Shapes(MyChart).Cut
     End With

     Application.ScreenUpdating = True
     Exit Sub

Finish:
     MsgBox "You must select a picture"
End Sub

was copied directly from here, and works beautifully for the cases I tested.

Casting a number to a string in TypeScript

window.location.hash is a string, so do this:

var page_number: number = 3;
window.location.hash = String(page_number); 

Python constructor and default value

Mutable default arguments don't generally do what you want. Instead, try this:

class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList 
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList 

Exit Shell Script Based on Process Exit Code

In Bash this is easy. Just tie them together with &&:

command1 && command2 && command3

You can also use the nested if construct:

if command1
   then
       if command2
           then
               do_something
           else
               exit
       fi
   else
       exit
fi

python date of the previous month

Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

from datetime import datetime, timedelta

d = datetime(2012, 3, 31) # A problem date as an example

# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
    # try to go back to same day last month
    one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
    pass
print("one_month_ago: {0}".format(one_month_ago))

Output:

one_month_ago: 2012-02-29 00:00:00

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Just to help anyone with this problem (locking requests when executing another one from the same session)...

Today I started to solve this issue and, after some hours of research, I solved it by removing the Session_Start method (even if empty) from the Global.asax file.

This works in all projects I've tested.

Python and pip, list all versions of a package that's available?

For pip >= 20.3 use:

pip install --use-deprecated=legacy-resolver pylibmc==

For updates see: https://github.com/pypa/pip/issues/9139

For pip >= 9.0 use:

$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from 
  versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

– all the available versions will be printed without actually downloading or installing any additional packages.

For pip < 9.0 use:

pip install pylibmc==blork

where blork can be any string that is not a valid version number.

How can I determine the direction of a jQuery scroll event?

I had problems with elastic scrolling (scroll bouncing, rubber-banding). Ignoring the down-scroll event if close to the page top worked for me.

var position = $(window).scrollTop();
$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    var downScroll = scroll > position;
    var closeToTop = -120 < scroll && scroll < 120;
    if (downScroll && !closeToTop) {
        // scrolled down and not to close to top (to avoid Ipad elastic scroll-problems)
        $('.top-container').slideUp('fast');
        $('.main-header').addClass('padding-top');
    } else {
        // scrolled up
        $('.top-container').slideDown('fast');
        $('.main-header').removeClass('padding-top');
    }
    position = scroll;
});

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

Flask Download a File

To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.

Example:

from flask import Flask
from flask import send_file
app = Flask(__name__)

@app.route('/download')
def downloadFile ():
    #For windows you need to use drive name [ex: F:/Example.pdf]
    path = "/Examples.pdf"
    return send_file(path, as_attachment=True)

if __name__ == '__main__':
    app.run(port=5000,debug=True) 

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

Excel CSV. file with more than 1,048,576 rows of data

Split the CSV into two files in Notepad. It's a pain, but you can just edit each of them individually in Excel after that.

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

Extension methods must be defined in a non-generic static class

change

public class LinqHelper

to

public static class LinqHelper

Following points need to be considered when creating an extension method:

  1. The class which defines an extension method must be non-generic, static and non-nested
  2. Every extension method must be a static method
  3. The first parameter of the extension method should use the this keyword.

JPA - Returning an auto generated id after persist()

Another option compatible to 4.0:

Before committing the changes, you can recover the new CayenneDataObject object(s) from the collection associated to the context, like this:

CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();

then access the ObjectId for each one in the collection, like:

ObjectId objectId = dataObject.getObjectId();

Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot(), it contains also the column name(s) associated to the PK as key(s):

objectId.getIdSnapshot().values()

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

django import error - No module named core.management

Store the python python path in a variable and execute.This would include the otherwise missing packages.

python_path= `which python` 
$python_path manage.py runserver

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Get folder up one level

The parent directory of an included file would be

dirname(getcwd())

e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php

then by calling /file/index.php

getcwd() is /var/www/html/folder  
__DIR__ is /var/www/html/folder/inc  
so dirname(__DIR__) is /var/www/html/folder

but what we want is /var/www/html which is dirname(getcwd())

need to add a class to an element

You are missing a closing h2 tag. It should be:

<h2><!-- Content --></h2> 

Use string.Contains() with switch()

This will work in C# 8 using a switch expresion

var message = "Some test message";

message = message switch
{
    string a when a.Contains("test") => "yes",
    string b when b.Contains("test2") => "yes for test2",
    _ => "nothing to say"
};

For further references https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression

get next sequence value from database using hibernate

Your idea with the SequenceGenerator fake entity is good.

@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
        @org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")

It is important to use the parameter with the key name "sequence_name". Run a debugging session on the hibernate class SequenceStyleGenerator, the configure(...) method at the line final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment ); to see more details about how the sequence name is computed by Hibernate. There are some defaults in there you could also use.

After the fake entity, I created a CrudRepository:

public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}

In the Junit, I call the save method of the SequenceRepository.

SequenceGenerator sequenceObject = new SequenceGenerator(); SequenceGenerator result = sequenceRepository.save(sequenceObject);

If there is a better way to do this (maybe support for a generator on any type of field instead of just Id), I would be more than happy to use it instead of this "trick".

How to fix Invalid AES key length?

Things to know in general:

  1. Key != Password
    • SecretKeySpec expects a key, not a password. See below
  2. It might be due to a policy restriction that prevents using 32 byte keys. See other answer on that

In your case

The problem is number 1: you are passing the password instead of the key.

AES only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.

There are different ways to derive the key from a passphrase. Java provides a PBKDF2 implementation for such a purpose.

I used erickson's answer to paint a complete picture (only encryption, since the decryption is similar, but includes splitting the ciphertext):

SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);

KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = f.generateSecret(spec).getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encValue = c.doFinal(valueToEnc.getBytes());

byte[] finalCiphertext = new byte[encValue.length+2*16];
System.arraycopy(ivBytes, 0, finalCiphertext, 0, 16);
System.arraycopy(salt, 0, finalCiphertext, 16, 16);
System.arraycopy(encValue, 0, finalCiphertext, 32, encValue.length);

return finalCiphertext;

Other things to keep in mind:

  • Always use a fully qualified Cipher name. AES is not appropriate in such a case, because different JVMs/JCE providers may use different defaults for mode of operation and padding. Use AES/CBC/PKCS5Padding. Don't use ECB mode, because it is not semantically secure.
  • If you don't use ECB mode then you need to send the IV along with the ciphertext. This is usually done by prefixing the IV to the ciphertext byte array. The IV is automatically created for you and you can get it through cipherInstance.getIV().
  • Whenever you send something, you need to be sure that it wasn't altered along the way. It is hard to implement a encryption with MAC correctly. I recommend you to use an authenticated mode like CCM or GCM.

Is there any way to change input type="date" format?

It is impossible to change the format

We have to differentiate between the over the wire format and the browser's presentation format.

Wire format

The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd. See section 5.6 of the RFC 3339 specification for more details.

This format is used by the value HTML attribute and DOM property and is the one used when doing an ordinary form submission.

Presentation format

Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.

Desktop devices

For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us will be shown 01/30/2019 instead of the format they are accustomed to: 30-01-2019.

Internet Explorer 9, 10, and 11 display a text input field with the wire format.

Mobile devices

Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.

Placing a textview on top of imageview in android

you can try this too. I use just framelayout.

 <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/cover"
                android:gravity="bottom">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Hello !"
                    android:id="@+id/welcomeTV"
                    android:textColor="@color/textColor"
                    android:layout_gravity="left|bottom" />
            </FrameLayout>

How can I apply styles to multiple classes at once?

If you use as following, your code can be more effective than you wrote. You should add another feature.

.abc, .xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a.abc, a.xyz {
margin-left:20px;
width: 100px;
height: 100px;
} 

OR

a {
margin-left:20px;
width: 100px;
height: 100px;
} 

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

Submit Button Image

It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../> to always specify alt="" attribute for this input field.

Blind people don't know what button will do if it doesn't contain meaningful alt="" or value="".

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

Total memory in Mb:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
echo $((x/1024))

or:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo) ; echo $((x/1024))

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

If you want this behaviour everywhere in your app and don't want to add anything to individual viewDidAppear etc. then you should create a subclass

class QFNavigationController:UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        interactivePopGestureRecognizer?.delegate = self
        delegate = self
    }

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        interactivePopGestureRecognizer?.isEnabled = false
    }

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        interactivePopGestureRecognizer?.isEnabled = true
    }

    // IMPORTANT: without this if you attempt swipe on
    // first view controller you may be unable to push the next one
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return viewControllers.count > 1
    }

}

Now, whenever you use QFNavigationController you get the desired experience.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:

var someval = document.getElementById('something')
if (someval && someval.value <> '') {

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

Make the console wait for a user input to close

I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
    Console c = System.console();
    if (c != null) {
        // printf-like arguments
        if (message != null)
            c.format(message, args);
        c.format("\nPress ENTER to proceed.\n");
        c.readLine();
    }
}

Set the value of an input field

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

Run php function on button click

You can use isset().

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" />

</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(isset($_POST('submit')))
{
   testfun();
}

?>

Populating a ComboBox using C#

Define a class

public class Language
{
     public string Name { get; set; }
     public string Value { get; set; }
}

then...

//Build a list
var dataSource = new List<Language>();
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });
dataSource.Add(new Language() { Name = "blah", Value = "blah" });

//Setup data binding
this.comboBox1.DataSource = dataSource;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Value";

// make it readonly
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Bash: infinite sleep (infinite blocking)

This approach will not consume any resources for keeping process alive.

while :; do sleep 1; done & kill -STOP $! && wait $!

Breakdown

  • while :; do sleep 1; done & Creates a dummy process in background
  • kill -STOP $! Stops the background process
  • wait $! Wait for the background process, this will be blocking forever, cause background process was stopped before

Why does integer division in C# return an integer and not a float?

Might be useful:

double a = 5.0/2.0;   
Console.WriteLine (a);      // 2.5

double b = 5/2;   
Console.WriteLine (b);      // 2

int c = 5/2;   
Console.WriteLine (c);      // 2

double d = 5f/2f;   
Console.WriteLine (d);      // 2.5

API pagination best practices

If you've got pagination you also sort the data by some key. Why not let API clients include the key of the last element of the previously returned collection in the URL and add a WHERE clause to your SQL query (or something equivalent, if you're not using SQL) so that it returns only those elements for which the key is greater than this value?

Stop Chrome Caching My JS Files

The problem is that Chrome needs to have must-revalidate in the Cache-Control` header in order to re-check files to see if they need to be re-fetched.

You can always SHIFT-F5 and force Chrome to refresh, but if you want to fix this problem on the server, include this response header:

Cache-Control: must-revalidate

This tells Chrome to check with the server, and see if there is a newer file. IF there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.

If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.

Here is a blog post that discusses the issue further.

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @yourBirthDate DATETIME = '1987-05-25'
SELECT YEAR(DATEADD(DAY, DATEDIFF(DAY, @yourBirthDate, GETDATE()), CAST('0001-01-01' AS DATETIME2))) - 1

How can I create download link in HTML?

i know i am late but this is what i got after 1 hour of search

 <?php 
      $file = 'file.pdf';

    if (! file) {
        die('file not found'); //Or do something 
    } else {
       if(isset($_GET['file'])){  
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($file); }
    }

    ?>

and for downloadable link i did this

<a href="index.php?file=file.pdf">Download PDF</a>

Access VBA | How to replace parts of a string with another string

You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:

Public Function strReplace(varValue As Variant) as Variant

    Select Case varValue

        Case "Avenue"
            strReplace = "Ave"

        Case "North"
            strReplace = "N"

        Case Else
            strReplace = varValue

    End Select

End Function

Then your SQL would read something like:

SELECT strReplace(Address) As Add FROM Tablename

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

Change color of Button when Mouse is over

<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
     <Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
     <Border.Style>
         <Style TargetType="Border">
             <Style.Triggers>
                 <Trigger Property="IsMouseOver" Value="True">
                     <Setter Property="Background" Value="#FF6A6A" />
                 </Trigger>
             </Style.Triggers>
         </Style>
      </Border.Style>
      <StackPanel Orientation="Horizontal">
           <Image  RenderOptions.BitmapScalingMode="HighQuality"   Source="//ImageName.png"   />
      </StackPanel>
      </Border>
  </Button>

Get selected text from a drop-down list (select box) using jQuery

var e = document.getElementById("dropDownId");
var div = e.options[e.selectedIndex].text;

How to search JSON tree with jQuery

I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angular project. They have taken care of every possible cases.

/* Seach in Object */

var comparator = function(obj, text) {
if (obj && text && typeof obj === 'object' && typeof text === 'object') {
    for (var objKey in obj) {
        if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
                comparator(obj[objKey], text[objKey])) {
            return true;
        }
    }
    return false;
}
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};

var search = function(obj, text) {
if (typeof text == 'string' && text.charAt(0) === '!') {
    return !search(obj, text.substr(1));
}
switch (typeof obj) {
    case "boolean":
    case "number":
    case "string":
        return comparator(obj, text);
    case "object":
        switch (typeof text) {
            case "object":
                return comparator(obj, text);
            default:
                for (var objKey in obj) {
                    if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
                        return true;
                    }
                }
                break;
        }
        return false;
    case "array":
        for (var i = 0; i < obj.length; i++) {
            if (search(obj[i], text)) {
                return true;
            }
        }
        return false;
    default:
        return false;
}
};

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

How to create an array from a CSV file using PHP and the fgetcsv function

convertToArray(file_get_content($filename));

function convertToArray(string $content): array
{
   $data = str_getcsv($content,"\n");
   array_walk($data, function(&$a) use ($data) {
       $a = str_getcsv($a);
   });

   return $data;
}

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

How do I get the current username in Windows PowerShell?

Now that PowerShell Core (aka v6) has been released, and people may want to write cross-platform scripts, many of the answers here will not work on anything other than Windows.

[Environment]::UserName appears to be the best way of getting the current username on all platforms supported by PowerShell Core if you don't want to add platform detection and special casing to your code.

How do I create a sequence in MySQL?

This is a solution suggested by the MySQl manual:

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

Create a table to hold the sequence counter and initialize it:

    mysql> CREATE TABLE sequence (id INT NOT NULL);
    mysql> INSERT INTO sequence VALUES (0);

Use the table to generate sequence numbers like this:

    mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
    mysql> SELECT LAST_INSERT_ID();

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

It sounds like possibly one or more of the columns being selected with:

   e.eval, e.batch_no, e.crsnum, e.lect_code, e.prof_course

has AllowDBNull set to False in your Dataset defintion.

MySQL command line client for Windows

You can choose only install the client during server install. The website only offers to let you download the full installer (grab whatever version you want from http://www.mysql.com/downloads/mysql/).

In the install wizard, when prompted for installation type (typical, minimal, custom), choose 'Custom'. On the next screen, select to NOT install the server, and proceed with the rest of the install as normal.

When you're done, you should see just the relevant client programs (mysql, mysqldump, etc) in C:\Program Files\MySQL..\bin

Add a Progress Bar in WebView

pass your url in this method

private void startWebView(String url) {

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        progressDialog = new ProgressDialog(ContestActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();

            }
        });
        webView.loadUrl(url);
    }

How do I set a JLabel's background color?

You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.

      JLabel lb = new JLabel("Test");
      lb.setBackground(Color.red);
      lb.setOpaque(true); <--This line of code must be set to true or otherwise the 

From the JavaDocs

setOpaque

public void setOpaque(boolean isOpaque)
  If true the component paints every pixel within its bounds. Otherwise, 
  the component may not paint some or all of its pixels, allowing the underlying 
  pixels to show through.
  The default value of this property is false for JComponent. However, 
  the default value for this property on most standard JComponent subclasses 
   (such as JButton and JTree) is look-and-feel dependent.

Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()

set font size in jquery

Not saying this is better, just another way:

$("#elem")[0].style.fontSize="20px";

Selecting text in an element (akin to highlighting with your mouse)

An Updated version that works in chrome:

function SelectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    
    if (doc.body.createTextRange) { // ms
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);

    }
}

$(function() {
    $('p').click(function() {
        SelectText("selectme");

    });
});

http://jsfiddle.net/KcX6A/326/

data.table vs dplyr: can one do something well the other can't or does poorly?

Reading Hadley and Arun's answers one gets the impression that those who prefer dplyr's syntax would have in some cases to switch over to data.table or compromise for long running times.

But as some have already mentioned, dplyr can use data.table as a backend. This is accomplished using the dtplyr package which recently had it's version 1.0.0 release. Learning dtplyr incurs practically zero additional effort.

When using dtplyr one uses the function lazy_dt() to declare a lazy data.table, after which standard dplyr syntax is used to specify operations on it. This would look something like the following:

new_table <- mtcars2 %>% 
  lazy_dt() %>%
  filter(wt < 5) %>% 
  mutate(l100k = 235.21 / mpg) %>% # liters / 100 km
  group_by(cyl) %>% 
  summarise(l100k = mean(l100k))

  new_table

#> Source: local data table [?? x 2]
#> Call:   `_DT1`[wt < 5][, `:=`(l100k = 235.21/mpg)][, .(l100k = mean(l100k)), 
#>     keyby = .(cyl)]
#> 
#>     cyl l100k
#>   <dbl> <dbl>
#> 1     4  9.05
#> 2     6 12.0 
#> 3     8 14.9 
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

The new_table object is not evaluated until calling on it as.data.table()/as.data.frame()/as_tibble() at which point the underlying data.table operation is executed.

I've recreated a benchmark analysis done by data.table author Matt Dowle back at December 2018 which covers the case of operations over large numbers of groups. I've found that dtplyr indeed enables for the most part those who prefer the dplyr syntax to keep using it while enjoying the speed offered by data.table.

Memory address of an object in C#

Getting the address of an arbitrary object in .NET is not possible, but can be done if you change the source code and use mono. See instructions here: Get Memory Address of .NET Object (C#)

MySQL direct INSERT INTO with WHERE clause

If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:

INSERT INTO tbl_member 
(Field1,Field2,Field3,...) 
SELECT a.Field1,a.Field2,a.Field3,... 
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a 
LEFT JOIN tbl_member AS b 
ON a.Field1 = b.Field1 
WHERE b.Field1 IS NULL

The record to be inserted is in the new value fields.

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

Are there constants in JavaScript?

For a while, I specified "constants" (which still weren't actually constants) in object literals passed through to with() statements. I thought it was so clever. Here's an example:

with ({
    MY_CONST : 'some really important value'
}) {
    alert(MY_CONST);
}

In the past, I also have created a CONST namespace where I would put all of my constants. Again, with the overhead. Sheesh.

Now, I just do var MY_CONST = 'whatever'; to KISS.

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.

Also on my site, I have

  1. Some lists of useful resources (see sidebar bottom right) on
    • ical Spec RFC 5545
    • ical Testing Resources
  2. Some notes recorded on my journey working with .ics over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful.

.ics areas that need careful handling:

  • 'all day' events
  • types of dates (timezone, UTC, or local 'floating') - nb to understand distinction
  • interoperability of recurrence rules

Is it possible to use JavaScript to change the meta-tags of the page?

Yes, it is.

E.g. to set the meta-description:

document.querySelector('meta[name="description"]').setAttribute("content", _desc);

Uint8Array to string in Javascript

If you can't use the TextDecoder API because it is not supported on IE:

  1. You can use the FastestSmallestTextEncoderDecoder polyfill recommended by the Mozilla Developer Network website;
  2. You can use this function also provided at the MDN website:

_x000D_
_x000D_
function utf8ArrayToString(aBytes) {_x000D_
    var sView = "";_x000D_
    _x000D_
    for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {_x000D_
        nPart = aBytes[nIdx];_x000D_
        _x000D_
        sView += String.fromCharCode(_x000D_
            nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */_x000D_
                /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */_x000D_
                (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */_x000D_
                (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */_x000D_
                (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */_x000D_
                (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */_x000D_
                (nPart - 192 << 6) + aBytes[++nIdx] - 128_x000D_
            : /* nPart < 127 ? */ /* one byte */_x000D_
                nPart_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    return sView;_x000D_
}_x000D_
_x000D_
let str = utf8ArrayToString([50,72,226,130,130,32,43,32,79,226,130,130,32,226,135,140,32,50,72,226,130,130,79]);_x000D_
_x000D_
// Must show 2H2 + O2 ? 2H2O_x000D_
console.log(str);
_x000D_
_x000D_
_x000D_

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

Simplest way to detect a mobile device in PHP

PHP device detection from 51Degrees.com does exactly what you want - detects mobile devices and various properties associated with detected devices. It is simple to use and requires no maintenance. Set up is done in 4 easy steps:

  1. Download the Zip file from http://sourceforge.net/projects/fiftyone/.
  2. Unzip the file into a directory in your PHP server.
  3. Then add the following code to your PHP page:
  4. require_once 'path/to/core/51Degrees.php';
    require_once 'path/to/core/51Degrees_usage.php';
    
  5. All available device information will be contained in $_51d array:
  6. if ($_51d['IsMobile'])
    {
        //Start coding for a mobile device here.
    }
    

51Degrees device detector does not use regular expressions for detections. Only important parts of HTTP headers are used to match devices. Which makes this solution the fastest (5 000 000 detections per second on mediocre hardware) and most accurate (99.97% accuracy) as hundreds of new devices are added to the database weekly (Supported device types include consoles, smart TVs, e-readers, tablets and more).

Software is open source distributed under Mozilla Public License 2 and compatible with commercial and open source projects. As a bonus 51Degrees solution also contains a complementary PHP image optimiser that can automatically resize images for mobile devices.

By default 51Degrees PHP device detector uses Lite data file which is free and contains over 30000 devices and 50 properties for each device. Lite file is updated once every 3 month. If you want to have a higher level of details about requesting mobile devices, then Premium and Enterprise data files are available. Premium contains well over 70000 devices and 100 properties for each device with weekly updates. Enterprise is updated daily and contains over 150000 devices with 150 properties for each.

Full list of device properties.
Compare data files.

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                popuMenu.inflate(R.menu.bottom_nav_menu);
                popuMenu.show();
            }
        },100);

How to extract the nth word and count word occurrences in a MySQL string?

As others have said, mysql does not provide regex tools for extracting sub-strings. That's not to say you can't have them though if you're prepared to extend mysql with user-defined functions:

https://github.com/mysqludf/lib_mysqludf_preg

That may not be much help if you want to distribute your software, being an impediment to installing your software, but for an in-house solution it may be appropriate.

How to create timer in angular2

Another solution is to use TimerObservable

TimerObservable is a subclass of Observable.

import {Component, OnInit, OnDestroy} from '@angular/core';
import {Subscription} from "rxjs";
import {TimerObservable} from "rxjs/observable/TimerObservable";

@Component({
  selector: 'app-component',
  template: '{{tick}}',
})
export class Component implements OnInit, OnDestroy {

  private tick: string;
  private subscription: Subscription;

  constructor() {
  }

  ngOnInit() {
    let timer = TimerObservable.create(2000, 1000);
    this.subscription = timer.subscribe(t => {
      this.tick = t;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

P.S.: Don't forget to unsubsribe.

Increasing the Command Timeout for SQL command

Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.

How to convert an int value to string in Go?

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

You can concat strings simply by +'ing them, or by using the Join function of the strings package.

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

How to import set of icons into Android Studio project

Newer versions of Android support vector graphics, which is preferred over PNG icons. Android Studio 2.1.2 (and probably earlier versions) comes with Vector Asset Studio, which will automatically create PNG files for vector graphics that you add.

The Vector Asset Studio supports importing vector icons from the SDK, as well as your own SVG files.

This article describes Vector Asset Studio: https://developer.android.com/studio/write/vector-asset-studio.html

Summary for how to add a vector graphic with PNG files (partially copied from that URL):

  1. In the Project window, select the Android view.
  2. Right-click the res folder and select New > Vector Asset.
  3. The Material Icon radio button should be selected; then click Choose
  4. Select your icon, tweak any settings you need to tweak, and Finish.
  5. Depending on your settings (see article), PNGs are generated during build at the app/build/generated/res/pngs/debug/ folder.

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Current date and time as string

Using C++ in MS Visual Studio 2015 (14), I use:

#include <chrono>

string NowToString()
{
  chrono::system_clock::time_point p = chrono::system_clock::now();
  time_t t = chrono::system_clock::to_time_t(p);
  char str[26];
  ctime_s(str, sizeof str, &t);
  return str;
}

How to add a custom button to the toolbar that calls a JavaScript function?

You can add the button image as follows:

CKEDITOR.plugins.add('showtime',   //name of our plugin
{    
    requires: ['dialog'], //requires a dialog window
    init:function(a) {
  var b="showtime";
  var c=a.addCommand(b,new CKEDITOR.dialogCommand(b));
  c.modes={wysiwyg:1,source:1}; //Enable our plugin in both modes
  c.canUndo=true;
 
  //add new button to the editor
  a.ui.addButton("showtime",
  {
   label:'Show current time',
   command:b,
   icon:this.path+"showtime.png"   //path of the icon
  });
  CKEDITOR.dialog.add(b,this.path+"dialogs/ab.js") //path of our dialog file
 }
});

Here is the actual plugin with all steps described.

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

How can I get the line number which threw exception?

You could include .PDB symbol files associated to the assembly which contain metadata information and when an exception is thrown it will contain full information in the stacktrace of where this exception originated. It will contain line numbers of each method in the stack.

Parse Json string in C#

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

One such example is the one everybody uses: JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>> with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

Note: ValueDescription being this class:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}

Using OR & AND in COUNTIFS

You could just add a few COUNTIF statements together:

=COUNTIF(A1:A196,"yes")+COUNTIF(A1:A196,"no")+COUNTIF(J1:J196,"agree")

This will give you the result you need.

EDIT

Sorry, misread the question. Nicholas is right that the above will double count. I wasn't thinking of the AND condition the right way. Here's an alternative that should give you the correct results, which you were pretty close to in the first place:

=SUM(COUNTIFS(A1:A196,{"yes","no"},J1:J196,"agree"))

Converting EditText to int? (Android)

I had the same problem myself. I'm not sure if you got it to work though, but what I had to was:

EditText cypherInput;
cypherInput = (EditText)findViewById(R.id.input_cipherValue);
int cypher = Integer.parseInt(cypherInput.getText().toString());

The third line of code caused the app to crash without using the .getText() before the .toString().

Just for reference, here is my XML:

<EditText
    android:id="@+id/input_cipherValue"
    android:inputType="number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

How can I convince IE to simply display application/json rather than offer to download it?

I had a similar problem. I was using the "$. GetJSON" jQuery and everything worked perfectly in Firefox and Chrome.

But it did not work in IE. So I tried to directly access the URL of json, but in IE it asked if I wanted to download the file.

After much searching I saw that there must be a header in the result with a content-type, in my case, the content-type was:

header("Content-type: text/html; charset=iso-8859-1");

But when the page that made the request receives this json, in IE, you have to be specified SAME CONTENT-TYPE, in my case was:

$.getJSON (
"<? site_url php echo (" ajax / tipoMenu ")?>"
{contentType: 'text / html; charset = utf-8'},
function (result) {

hugs

How can I convert a PFX certificate file for use with Apache on a linux server?

SSLSHopper has some pretty thorough articles about moving between different servers.

http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html

Just pick the relevant link at bottom of this page.

Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.

Using IF ELSE statement based on Count to execute different Insert statements

Depending on your needs, here are a couple of ways:

IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = 'SOME VALUE')
    --INSERT SOMETHING
ELSE
    --INSERT SOMETHING ELSE

Or a bit longer

DECLARE @retVal int

SELECT @retVal = COUNT(*) 
FROM TABLE
WHERE COLUMN = 'Some Value'

IF (@retVal > 0)
BEGIN
    --INSERT SOMETHING
END
ELSE
BEGIN
    --INSERT SOMETHING ELSE
END 

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

Selecting with complex criteria from pandas.DataFrame

And remember to use parenthesis!

Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

4 < 5 & 6 > 4

evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

df.loc[(df['A'] > 10) & (df['B'] < 15)]

instead of

df.loc[df['A'] > 10 & df['B'] < 15]

which would result in

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

iframe to Only Show a Certain Part of the Page

An <iframe> gives you a complete window to work with. The most direct way to do what you want is to have your server give you a complete page that only contains the fragment you want to show.

As an alternative, you could just use a simple <div> and use the jQuery "load" function to load the whole page and pluck out just the section you want:

$('#target-div').load('http://www.mywebsite.com/portfolio.php #portfolio-sports');

There may be other things you need to do, and a significant difference is that the content will become part of the main page instead of being segregated into a separate window.

assigning column names to a pandas series

You can create a dict and pass this as the data param to the dataframe constructor:

In [235]:

df = pd.DataFrame({'Gene':s.index, 'count':s.values})
df
Out[235]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

Alternatively you can create a df from the series, you need to call reset_index as the index will be used and then rename the columns:

In [237]:

df = pd.DataFrame(s).reset_index()
df.columns = ['Gene', 'count']
df
Out[237]:
   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

Ruby on Rails: How do I add placeholder text to a f.text_field?

Here is a much cleaner syntax if using rails 4+

<%= f.text_field :attr, placeholder: "placeholder text" %>

So rails 4+ can now use this syntax instead of the hash syntax

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

What are the differences between a pointer variable and a reference variable in C++?

  1. A pointer can be re-assigned:

    int x = 5;
    int y = 6;
    int *p;
    p = &x;
    p = &y;
    *p = 10;
    assert(x == 5);
    assert(y == 10);
    

    A reference cannot be re-bound, and must be bound at initialization:

    int x = 5;
    int y = 6;
    int &q; // error
    int &r = x;
    
  2. A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary & operator and a certain amount of space that can be measured with the sizeof operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.

    int x = 0;
    int &r = x;
    int *p = &x;
    int *p2 = &r;
    
    assert(p == p2); // &x == &r
    assert(&p != &p2);
    
  3. You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.

    int x = 0;
    int y = 0;
    int *p = &x;
    int *q = &y;
    int **pp = &p;
    
    **pp = 2;
    pp = &q; // *pp is now q
    **pp = 4;
    
    assert(y == 4);
    assert(x == 2);
    
  4. A pointer can be assigned nullptr, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to nullptr, but this is undefined and will not behave consistently.

    /* the code below is undefined; your compiler may optimise it
     * differently, emit warnings, or outright refuse to compile it */
    
    int &r = *static_cast<int *>(nullptr);
    
    // prints "null" under GCC 10
    std::cout
        << (&r != nullptr
            ? "not null" : "null")
        << std::endl;
    
    bool f(int &r) { return &r != nullptr; }
    
    // prints "not null" under GCC 10
    std::cout
        << (f(*static_cast<int *>(nullptr))
            ? "not null" : "null")
        << std::endl;
    

    You can, however, have a reference to a pointer whose value is nullptr.

  5. Pointers can iterate over an array; you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.

  6. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access its members whereas a reference uses a ..

  7. References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)

  8. Const references can be bound to temporaries. Pointers cannot (not without some indirection):

    const int &x = int(12); // legal C++
    int *y = &int(12); // illegal to take the address of a temporary.
    

    This makes const & more convenient to use in argument lists and so forth.

jquery function val() is not equivalent to "$(this).value="?

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I encountered the LNK2019 error while working on a DLL project in Visual Studio 2013.

I added a new configuration to the project. But instead of having the "Configuration Type" as "Dynamic Library", visual studio added it as "Application". This resulted in the LNK2019 error.

Fixed the LNK2019 error by going to Project -> Properties -> Configuration Properties -> General and changing "Configuration Type" to "Dynamic Library (.dll)" and "Target Extension" to ".dll".

Yes, the original question talks about a console/application project, which is a different problem than my answer. But I believe adding this answer might help someone (like me) that stumbles upon this thread.

Can't type in React input text field

In a class component context...

If the changeHandler method is a normal function:

handleChange(e){
    this.setState({[e.target.name]:[e.target.value]});
}

it can be used such as this...onChange={(e)=>this.handleChange(e)}

<input type="text" name="any" value={this.state.any} onChange={(e)=>this.handleChange(e)}></input>

If the changeHandler method is an arrow function:

handle = (e) =>{
        this.setState({[e.target.name]:[e.target.value]});
    }

it can be used like this... onChange={this.handle}

 <input type="text" name="any2" value={this.state.any2} onChange={this.handle} ></input>

And this solved my "Can't type in React input text field" problem.

How to resize html canvas element?

I just had the same problem as you, but found out about the toDataURL method, which proved useful.

The gist of it is to turn your current canvas into a dataURL, change your canvas size, and then draw what you had back into your canvas from the dataURL you saved.

So here's my code:

var oldCanvas = canvas.toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
    canvas.height += 100;
    ctx.drawImage(img, 0, 0);
}

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

View/edit ID3 data for MP3 files

ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.

Does Google Chrome work with Selenium IDE (as Firefox does)?

There is not a Google Chrome extension comparable to Selenium IDE.

Scirocco is only a partial (and reportedly unreliable) implementation.

There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.

Sahi and TestComplete can also record, but neither are free, and are not browser plugins.

iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.

It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.

I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?

Why am I getting the message, "fatal: This operation must be run in a work tree?"

If none of the above usual ways help you, look at the call trace underneath this error message ("fatal: This operation . . .") and locate the script and line which is raising the actual error. Once you locate that error() call, disable it and see if the operation you are trying completes even with some warnings/messages - ignore them for now. If so, finally after completing it might mention the part of the operation that was not completed successfully. Now, address this part separately as applicable.

Relating above logic to my case, I was getting this error message "fatal: This operation . . ." when I was trying to get the Android-x86 code with repo sync . . .. and the call trace showed raise GitError("cannot initialize work tree") as the error() call causing the above error message ("fatal: . . ."). So, after commenting that GitError() in .repo/repo/project.py, repo sync . . . continued and finally indicated error for three projects that were not properly synced. I just deleted their *.git folders from their relevant paths in the Android-x86 source tree locally and ran repo sync . . . again and tasted success!

How to compile LEX/YACC files on Windows?

Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:

choco install winflexbison

...which at the time of writing contains Bison 2.7 & Flex 2.6.3.

There is also winflexbison3 which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I solved this by using the /sm flag to specify to look in the machine store instead of the default, which is My (Local User) store. Also, it can help to turn on debug for signtool by using /debug.

Hive: how to show all partitions of a table?

You can see Hive MetaStore tables,Partitions information in table of "PARTITIONS". You could use "TBLS" join "Partition" to query special table partitions.

Passing an array as a function parameter in JavaScript

const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);

See MDN docs for Function.prototype.apply().


If the environment supports ECMAScript 6, you can use a spread argument instead:

call_me(...args);

Where is SQL Server Management Studio 2012?

You can get SSMS Express tools from here or full SQL Server Eval tools from here. MSDN/TechNet Downloads is currently the only place to get RTM versions (non-eval) of the SSMS 2012 toolset.

Note the first link now(dec 2017) points to 'Microsoft® SQL Server® 2012 Service Pack 2 (SP2) Express'. ssms 2014 and 2017 are still available.

Push origin master error on new repository

I had the same issue. I deleted the .git folder then followed the following commands

  1. $ git init
  2. $ git add .
  3. $ git remote add origin [email protected]:project/project.git
  4. $ git commit -m "Initial version"
  5. $ git push origin master

Nested or Inner Class in PHP

You cannot do this in PHP. However, there are functional ways to accomplish this.

For more details please check this post: How to do a PHP nested class or nested methods?

This way of implementation is called fluent interface: http://en.wikipedia.org/wiki/Fluent_interface

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

How can I enable cURL for an installed Ubuntu LAMP stack?

You don't have to give version numbers. Just run:

sudo apt-get install php-curl

It worked for me. Don't forgot to restart the server:

sudo service apache2 restart

How to get the Android Emulator's IP address?

Use this method you will be getting 100% correct ip address for your android emulator

To get the ip address of yoor emulator

Go to adb shell and type this command

adb shell
ifconfig eth0

enter image description here

After running this command I am getting

IP : 10.0.2.15

Mask : 255.255.255.0

Which works for me . I am also working for an networking application.

How to convert dataframe into time series?

Input. We will start with the text of the input shown in the question since the question did not provide the csv input:

Lines <- "Dates   Bajaj_close Hero_close
3/14/2013   1854.8  1669.1
3/15/2013   1850.3  1684.45
3/18/2013   1812.1  1690.5
3/19/2013   1835.9  1645.6
3/20/2013   1840    1651.15
3/21/2013   1755.3  1623.3
3/22/2013   1820.65 1659.6
3/25/2013   1802.5  1617.7
3/26/2013   1801.25 1571.85
3/28/2013   1799.55 1542"

zoo. "ts" class series normally do not represent date indexes but we can create a zoo series that does (see zoo package):

library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")

Alternately, if you have already read this into a data frame DF then it could be converted to zoo as shown on the second line below:

DF <- read.table(text = Lines, header = TRUE)
z <- read.zoo(DF, format = "%m/%d/%Y")

In either case above z ia a zoo series with a "Date" class time index. One could also create the zoo series, zz, which uses 1, 2, 3, ... as the time index:

zz <- z
time(zz) <- seq_along(time(zz))

ts. Either of these could be converted to a "ts" class series:

as.ts(z)
as.ts(zz)

The first has a time index which is the number of days since the Epoch (January 1, 1970) and will have NAs for missing days and the second will have 1, 2, 3, ... as the time index and no NAs.

Monthly series. Typically "ts" series are used for monthly, quarterly or yearly series. Thus if we were to aggregate the input into months we could reasonably represent it as a "ts" series:

z.m <- as.zooreg(aggregate(z, as.yearmon, mean), freq = 12)
as.ts(z.m)

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Is there a real solution to debug cordova apps

Here's the solution using Phonegap Build. Add the following to your config.xml to be able to inspect with Chrome Remote Webview Debugging.

First, make sure your widget tag contains xmlns:android="http://schemas.android.com/apk/res/android"

<widget 
    xmlns="http://www.w3.org/ns/widgets" 
    xmlns:gap="http://phonegap.com/ns/1.0" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="me.app.id" 
    version="1.0.0">

Then add the following

<gap:config-file platform="android" parent="/manifest">
     <application android:debuggable="true" />
</gap:config-file>

It works for me on Nexus 5, Phonegap 3.7.0.

<preference name="phonegap-version" value="3.7.0" />

Build the app in Phonegap Build, install the APK, connect the phone to the USB, enable USB debugging on you phone then visit chrome://inspect.

Source: https://www.genuitec.com/products/gapdebug/learning-center/configuration/

change the date format in laravel view page

In Laravel you can add a function inside app/Helper/helper.php like

function formatDate($date = '', $format = 'Y-m-d'){
    if($date == '' || $date == null)
        return;

    return date($format,strtotime($date));
}

And call this function on any controller like this

$start_date = formatDate($start_date,'Y-m-d');

Hope it helps!

Send file using POST from a Python script

Looks like python requests does not handle extremely large multi-part files.

The documentation recommends you look into requests-toolbelt.

Here's the pertinent page from their documentation.