Programs & Examples On #Gnome terminal

The default GNOME desktop terminal emulator, allowing users to execute commands using a real UNIX shell while remaining on their graphical desktop.

Clear a terminal screen for real

My favorite human friendly command for this is:

reset

Tested on xterm and VT100. It also helps after an abnormal program termination. Keeps the command buffer, so up-arrow will cycle through previous commands.

How to send a model in jQuery $.ajax() post request to MVC controller method

This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

What is the best IDE for C Development / Why use Emacs over an IDE?

I started off by using IDEs, Microsoft or not. Then, while working on QNX some long time ago, I was forced to do with a text editor + compiler/linker. Now I prefer this simple combination––a syntax highlighting editor + C compiler and linker cli + make––to any IDEs, even if environment allows for them.

The reasons are, for me:

  1. it's everywhere. If you program in C, you do have the compiler, and usually you can get yourself an editor. The first thing I do––I get myself nedit on Linux or Notepad++ on Windows. I would go with vi, but GUI editors provide for a better fonts, and that is important when you look at code all day

  2. you can program remotely, via ssh, when you need to. And it does help a lot sometimes to be able to ssh into the target and do some quick things there

  3. it keeps me close to CLI, preferably UNIX/Linux CLI. So all the commands are on my fingertips, and when I need them I don't have to go read a reference book. And UNIX CLI can do things IDEs often can't––because their developers didn't think you'd need them

  4. most importantly, it is very much like seeing the Matrix in raw code. I operate files, so I'm forced to keep them manageable. I'm finding things in my code manually, which makes me keep it simple and organized. I do Config Management explicitly, so I know when I'm synced and how. I know my Makefiles because I write them, and they only do what I tell them to

    (if you wonder if that works in "really big projects"––it does work, and the bigger the project the more performance it gains me)

  5. when people ask me to look at their code, I don't have to learn the IDE they use

How to push object into an array using AngularJS

Push only work for array .

Make your arrayText object to Array Object.

Try Like this

JS

this.arrayText = [{
  text1: 'Hello',
  text2: 'world',
}];

this.addText = function(text) {
  this.arrayText.push(text);
}
this.form = {
  text1: '',
  text2: ''
};

HTML

<div ng-controller="TestController as testCtrl">
  <form ng-submit="addText(form)">
    <input type="text" ng-model="form.text1" value="Lets go">
    <input type="text" ng-model="form.text2" value="Lets go again">
    <input type="submit" value="add">
  </form>
</div>

Turn off constraints temporarily (MS SQL)

And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.

ALTER TABLE foo CHECK CONSTRAINT ALL

or

ALTER TABLE foo CHECK CONSTRAINT FK_something

then you can run back in and do an update against any checked columns like so:

UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc

And any errors at that point will be due to failure to meet constraints.

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I have similar issue, why should we add external jar files when we are using maven?

I have already included jstl maven dependency then also I encounter error "Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"". Then I include following dependency then error get solve, without including any single external jar file.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

AngularJs .$setPristine to reset form

There is another way to pristine form that is by sending form into the controller. For example:-

In view:-

<form name="myForm" ng-submit="addUser(myForm)" novalidate>
    <input type="text" ng-mode="user.name"/>
     <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
      <span ng-show="myForm.name.$error.required">Name is required.</span>
    </span>

    <button ng-disabled="myForm.$invalid">Add User</button>
</form>

In Controller:-

$scope.addUser = function(myForm) {
       myForm.$setPristine();
};

Java FileOutputStream Create File if not exists

File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

Pass this f to your FileOutputStream constructor.

Java JDBC connection status

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

"Debug certificate expired" error in Eclipse Android plugins

Delete your debug certificate under ~/.android/debug.keystore on Linux and Mac OS X; the directory is something like %USERPROFILE%/.androidon Windows.

The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

node.js execute system command synchronously

I actually had a situation where I needed to run multiple commands one after another from a package.json preinstall script in a way that would work on both Windows and Linux/OSX, so I couldn't rely on a non-core module.

So this is what I came up with:

#cmds.coffee
childproc = require 'child_process'

exports.exec = (cmds) ->
  next = ->
    if cmds.length > 0
      cmd = cmds.shift()
      console.log "Running command: #{cmd}"
      childproc.exec cmd, (err, stdout, stderr) ->
        if err? then console.log err
        if stdout? then console.log stdout
        if stderr? then console.log stderr
        next()
    else
      console.log "Done executing commands."

  console.log "Running the follows commands:"
  console.log cmds
  next()

You can use it like this:

require('./cmds').exec ['grunt coffee', 'nodeunit test/tls-config.js']

EDIT: as pointed out, this doesn't actually return the output or allow you to use the result of the commands in a Node program. One other idea for that is to use LiveScript backcalls. http://livescript.net/

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

Which port(s) does XMPP use?

According to Wikipedia:

5222 TCP     XMPP client connection (RFC 6120)        Official  
5223 TCP     XMPP client connection over SSL          Unofficial
5269 TCP     XMPP server connection (RFC 6120)        Official
5298 TCP UDP XMPP JEP-0174: Link-Local Messaging /    Official
             XEP-0174: Serverless Messaging
8010 TCP     XMPP File transfers                      Unofficial    

The port numbers are defined in RFC 6120 § 14.7.

Enable remote connections for SQL Server Express 2012

I had the same issue with SQL Server 2014 locally installed named instance. Connecting using the FQDN\InstanceName would fail, while connecting using only my hostname\InstanceName worked. For example: connecting using mycomputername\sql2014 worked, but using mycomputername.mydomain.org\sql2014 did not. DNS resolved correctly, TCP/IP was enabled within SQL Configuration Manager, Windows Firewall rules added (and then turned the firewall off for testing to ensure it wasn't blocking anything), but none of those fixed the problem.

Finally, I had to start the "SQL Server Browser" service on the SQL Server and that fixed the connectivity issue.

I had never realized that the SQL Server Browser service actually assisted the SQL Server in making connections; I was under the impression that it simply helped populate the dropdowns when you clicked "browse for more" servers to connect to, but it actually helps align client requests with the correct port # to use, if the port # is not explicitly assigned (similar to how website bindings help alleviate the same issue on an IIS web server that hosts multiple websites).

This connect item is what gave me the clue about the SQL Server Browser service: https://connect.microsoft.com/SQLServer/feedback/details/589901/unable-to-connect-on-localhost-using-fqdn-machine-name

  • when you use wstst05\sqlexpress as a server name, the client code separates the machine name from the instance name and the wstst05 is compared against the netbios name. I see no problem for them to match and the connection is considered local. From there, we retrieve the needed information WITHOUT contacting SQL Browser and connect to the SQL instance via Shared Memory without any problem.
  • when you use wstst05.capatest.local\sqlexpress, the client code fails the comparison of the name (wstst05.capatest.local) to the netbios name (wstst05) and considers the connection "remote". This is by design and we will definitely consider improving this in the future. Anyway, due to considering the connection remote and the fact that it is a named instance, client decides that it needs to use SQLBrowser for name resolution. It attempts to contact SQL Browser on wstst05.capatest.local (UDP port 1434) and apparently that part fails. Hence the error you get.

The reason for the "SQL Server Browser" service from TechNet (emphasis added by me): https://technet.microsoft.com/en-us/library/ms181087(v=sql.120).aspx

From the "Using SQL Server Browser" section:

If the SQL Server Browser service is not running, you are still able to connect to SQL Server if you provide the correct port number or named pipe. For instance, you can connect to the default instance of SQL Server with TCP/IP if it is running on port 1433. However, if the SQL Server Browser service is not running, the following connections do not work:

  • Any component that tries to connect to a named instance without fully specifying all the parameters (such as the TCP/IP port or named pipe).
  • Any component that generates or passes server\instance information that could later be used by other components to reconnect.
  • Connecting to a named instance without providing the port number or pipe.
  • DAC to a named instance or the default instance if not using TCP/IP port 1433.
  • The OLAP redirector service.
  • Enumerating servers in SQL Server Management Studio, Enterprise Manager, or Query Analyzer.

If you are using SQL Server in a client-server scenario (for example, when your application is accessing SQL Server across a network), if you stop or disable the SQL Server Browser service, you must assign a specific port number to each instance and write your client application code to always use that port number. This approach has the following problems:

  • You must update and maintain client application code to ensure it is connecting to the proper port.
  • The port you choose for each instance may be used by another service or application on the server, causing the instance of SQL Server to be unavailable.

And more info from the same article from the "How SQL Server Browser Works" section:

Because only one instance of SQL Server can use a port or pipe, different port numbers and pipe names are assigned for named instances, including SQL Server Express. By default, when enabled, both named instances and SQL Server Express are configured to use dynamic ports, that is, an available port is assigned when SQL Server starts. If you want, a specific port can be assigned to an instance of SQL Server. When connecting, clients can specify a specific port; but if the port is dynamically assigned, the port number can change anytime SQL Server is restarted, so the correct port number is unknown to the client. ... When SQL Server clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance

Dynamically updating css in Angular 2

In Html:

<div [style.maxHeight]="maxHeightForScrollContainer + 'px'">
</div>

In Ts

this.maxHeightForScrollContainer = 200 //your custom maxheight

C# Generics and Type Checking

I hope you find this helpful:

  • typeof(IList<T>).IsGenericType == true
  • typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
  • typeof(IList<int>).GetGenericArguments()[0] == typeof(int)

https://dotnetfiddle.net/5qUZnt

Is it possible to change javascript variable values while debugging in Google Chrome?

To modify a value every time a block of code runs without having to break execution flow:

The "Logpoints" feature in the debugger is designed to let you log arbitrary values to the console without breaking. It evaluates code inside the flow of execution, which means you can actually use it to change values on the fly without stopping.

Right-click a line number and choose "Logpoint," then enter the assignment expression. It looks something like this:

enter image description here

I find it super useful for setting values to a state not otherwise easy to reproduce, without having to rebuild my project with debug lines in it. REMEMBER to delete the breakpoint when you're done!

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

How line ending conversions work with git core.autocrlf between different operating systems

Here is my understanding of it so far, in case it helps someone.

core.autocrlf=true and core.safecrlf = true

You have a repository where all the line endings are the same, but you work on different platforms. Git will make sure your lines endings are converted to the default for your platform. Why does this matter? Let's say you create a new file. The text editor on your platform will use its default line endings. When you check it in, if you don't have core.autocrlf set to true, you've introduced a line ending inconsistency for someone on a platform that defaults to a different line ending. I always set safecrlf too because I would like to know that the crlf operation is reversible. With these two settings, git is modifying your files, but it verifies that the modifications are reversible.

core.autocrlf=false

You have a repository that already has mixed line endings checked in and fixing the incorrect line endings could break other things. Its best not to tell git to convert line endings in this case, because then it will exacerbate the problem it was designed to solve - making diffs easier to read and merges less painful. With this setting, git doesn't modify your files.

core.autocrlf=input

I don't use this because the reason for this is to cover a use case where you created a file that has CRLF line endings on a platform that defaults to LF line endings. I prefer instead to make my text editor always save new files with the platform's line ending defaults.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

In my case when I comment out mirrorlist the error got away but the repo was also not working so I manually point the right baseurl in /etc/yum.repos.d/epel.repo as below

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://iad.mirror.rackspace.com/epel/7Server/x86_64/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://iad.mirror.rackspace.com/epel/7Server/x86_64/debug/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://iad.mirror.rackspace.com/epel/7Server/SRPMS/
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to compare two lists in python?

If you mean lists, try ==:

l1 = [1,2,3]
l2 = [1,2,3,4]

l1 == l2 # False

If you mean array:

l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False

If you want to compare strings (per your comment):

date_string  = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False

How can I declare a global variable in Angular 2 / Typescript?

I don't know the best way, but the easiest way if you want to define a global variable inside of a component is to use window variable to write like this:

window.GlobalVariable = "what ever!"

you don't need to pass it to bootstrap or import it other places, and it is globally accessibly to all JS (not only angular 2 components).

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Reverse a string without using reversed() or [::-1]?

Easiest way to reverse a string:

    backwards = input("Enter string to reverse: ")
    print(backwards[::-1])

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Android, How to limit width of TextView (and add three dots at the end of text)?

you can write this line in xml where you take the textview :

android:singleLine="true"

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

HTML-Tooltip position relative to mouse pointer

One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:

http://codepen.io/c0un7z3r0/pen/LZWXEw

Note that the span that contains the tooltip content is relative to the parent li. The magic is here:

ul#list_of_thrones li > span{
  display:none;
}
ul#list_of_thrones li:hover > span{
  position: absolute;
  display:block;
  ...
}

As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.

I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.

Does java.util.List.isEmpty() check if the list itself is null?

You can use your own isEmpty (for multiple collection) method too. Add this your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}

Oracle Not Equals Operator

As everybody else has said, there is no difference. (As a sanity check I did some tests, but it was a waste of time, of course they work the same.)

But there are actually FOUR types of inequality operators: !=, ^=, <>, and ¬=. See this page in the Oracle SQL reference. On the website the fourth operator shows up as ÿ= but in the PDF it shows as ¬=. According to the documentation some of them are unavailable on some platforms. Which really means that ¬= almost never works.

Just out of curiosity, I'd really like to know what environment ¬= works on.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

Android ListView with Checkbox and all clickable

this code works on my proyect and i can select the listview item and checkbox

<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true" >

    <TextView
        android:id="@+id/label"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4" />

    <CheckBox
        android:id="@+id/check"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:text="" >
    </CheckBox>

</LinearLayout>

How can I run an external command asynchronously from Python?

subprocess.Popen does exactly what you want.

from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

(Edit to complete the answer from comments)

The Popen instance can do various other things like you can poll() it to see if it is still running, and you can communicate() with it to send it data on stdin, and wait for it to terminate.

Call apply-like function on each row of dataframe with multiple arguments from each row

Others have correctly pointed out that mapply is made for this purpose, but (for the sake of completeness) a conceptually simpler method is just to use a for loop.

for (row in 1:nrow(df)) { 
    df$newvar[row] <- testFunc(df$x[row], df$z[row]) 
}

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Actually easiest way to fix this is just move your object before Javascript code it worked to me. I guess in your answer object is loaded after javascript code.

<style type="text/css" >
      #map_canvas {
              width:300px;
            height:300px;
     }

 <div id="map_canvas"> </div> // Here 

<script type="text/javascript">

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);

</script>

<div id="map_canvas"> </div>

Change background colour for Visual Studio

You can also use the Visual Studio Theme Generator. I have only tried this with VS 2005, but the settings it generates may work with newer versions of VS as well.

In case the link goes dead in the future here is a dark theme I generated. Just put this text into a file named VS_2005_dark_theme.vssettings and import it using Tools -> Import and Export Settings:

<UserSettings>
    <ApplicationIdentity version="8.0"/>
    <ToolsOptions>
        <ToolsOptionsCategory name="Environment" RegisteredName="Environment"/>
    </ToolsOptions>
    <Category name="Environment_Group" RegisteredName="Environment_Group">
        <Category name="Environment_FontsAndColors" Category="{1EDA5DD4-927A-43a7-810E-7FD247D0DA1D}" Package="{DA9FB551-C724-11d0-AE1F-00A0C90FFFC3}" RegisteredName="Environment_FontsAndColors" PackageName="Visual Studio Environment Package">
            <PropertyValue name="Version">2</PropertyValue>
            <FontsAndColors Version="2.0">
                <Categories>
                    <Category GUID="{5C48B2CB-0366-4FBF-9786-0BB37E945687}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0000FF00" Background="0x00003700" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{9973EFDF-317D-431C-8BC1-5E88CBFD4F7F}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0057C732" Background="0x0017340E" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0}" FontName="Monaco" FontSize="9" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="00CFCFCF" Background="00383838" BoldFont="No"/>
                            <Item Name="Indicator Margin" Foreground="0x02000000" Background="00383838" BoldFont="No"/>
                            <Item Name="Line Numbers" Foreground="00828282" Background="00383838" BoldFont="No"/>
                            <Item Name="Visible White Space" Foreground="0x00808080" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Compiler Error" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Value" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Selector" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS String Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Element Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Identifier" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Number" Foreground="002FFE60" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Preprocessor Keyword" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Stale Code" Foreground="0x00808080" Background="0x00C0C0C0" BoldFont="No"/>
                            <Item Name="String" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="String (C# Verbatim)" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Task List Shortcut" Foreground="0x00FFFFFF" Background="0x02C0C0C0" BoldFont="No"/>
                            <Item Name="User Keywords" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="User Types" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Warning" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Class" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Name" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Value" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Processing Instruction" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>                            
                            <Item Name="XML @ Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Attribute" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Tag" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Processing Instruction" Foreground="0x0015496C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XSLT Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>                                                                 
                        </Items>
                    </Category>
                </Categories>
            </FontsAndColors>
        </Category>
    </Category>
</UserSettings>

How do I write outputs to the Log in Android?

import android.util.Log;

and then

Log.i("the your message will go here"); 

change cursor to finger pointer

Add an href attribute to make it a valid link & return false; in the event handler to prevent it from causing a navigation;

<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>

(Or make displayData() return false and ..="return displayData(..)

How do I wait for an asynchronously dispatched block to finish?

Generally don't use any of these answers, they often won't scale (there's exceptions here and there, sure)

These approaches are incompatible with how GCD is intended to work and will end up either causing deadlocks and/or killing the battery by nonstop polling.

In other words, rearrange your code so that there is no synchronous waiting for a result, but instead deal with a result being notified of change of state (eg callbacks/delegate protocols, being available, going away, errors, etc.). (These can be refactored into blocks if you don't like callback hell.) Because this is how to expose real behavior to the rest of the app than hide it behind a false façade.

Instead, use NSNotificationCenter, define a custom delegate protocol with callbacks for your class. And if you don't like mucking with delegate callbacks all over, wrap them into a concrete proxy class that implements the custom protocol and saves the various block in properties. Probably also provide convenience constructors as well.

The initial work is slightly more but it will reduce the number of awful race-conditions and battery-murdering polling in the long-run.

(Don't ask for an example, because it's trivial and we had to invest the time to learn objective-c basics too.)

Python/Django: log to console under runserver, log to file under Apache

Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print directly, or use logging instead.

print >>sys.stderr, 'Goodbye, cruel world!'

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

SQL Server 2012 can't start because of a login failure

I had a similar issue that was resolved with the following:

  1. In Services.MSC click on the Log On tab and add the user with minimum privileges and password (on the service that is throwing the login error)
  2. By Starting Sql Server to run as Administrator

If the user is a domain user use Domain username and password

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

HttpClient not supporting PostAsJsonAsync method C#

As already debatted, this method isn't available anymore since .NET 4.5.2. To expand on Jeroen K's answer you can make an extension method:

public static async Task<HttpResponseMessage> PostAsJsonAsync<TModel>(this HttpClient client, string requestUrl, TModel model)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(model);
    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
    return await client.PostAsync(requestUrl, stringContent);
}

Now you are able to call client.PostAsJsonAsync("api/AgentCollection", user).

Creating a BAT file for python script

start xxx.py

You can use this for some other file types.

Setting the number of map tasks and reduce tasks

  • Use -D property=value rather than -D property = value (eliminate extra whitespaces). Thus -D mapred.reduce.tasks=value would work fine.

  • Setting number of map tasks doesnt always reflect the value you have set since it depends on split size and InputFormat used.

  • Setting the number of reduces will definitely override the number of reduces set on cluster/client-side configuration.

Get the string within brackets in Python

You can use

import re

s = re.search(r"\[.*?]", string)
if s:
    print(s.group(0))

How to convert current date into string in java?

tl;dr

LocalDate.now()
         .toString() 

2017-01-23

Better to specify the desired/expected time zone explicitly.

LocalDate.now( ZoneId.of( "America/Montreal" ) )
         .toString() 

java.time

The modern way as of Java 8 and later is with the java.time framework.

Specify the time zone, as the date varies around the world at any given moment.

ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;  // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;

2017-01-23

By default you get a String in standard ISO 8601 format.

For other formats use the java.time.format.DateTimeFormatter class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to print the array?

You could try this:

#include <stdio.h>

int main() 
{  
  int i,j;
  int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
  for(i = 0; i < 3; i++) 
  {
       for(j = 0; j < 3; j++) 
       {
         printf("%d ", my_array[i][j]);
       }
    printf("\n");
  } 
  return 0;
}

Is Java "pass-by-reference" or "pass-by-value"?

Please read this.

Many programming languages allow passing parameters by reference or by value. In Java, we can only pass parameters by value. This imposes some limits and also raises questions. For instance, if the parameter value is changed in the method, what happens to the value following method execution? You may also wonder how Java manages object values in the memory heap. This Java Challenger helps you resolve these and other common questions about object references in Java.

For the more:

https://www.javaworld.com/article/3512039/does-java-pass-by-reference-or-pass-by-value.html

CSS - center two images in css side by side

I understand that this question is old, but there is a good solution for it in HTML5. You can wrap it all in a <figure></figure> tag. The code would look something like this:

<div id="wrapper">
<figure>

<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp- 
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>

<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp- 
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>

</figure>
</div>

and the CSS:

#wrapper{
 text-align:center;
}

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Difference between CMD and ENTRYPOINT by intuition:

  • ENTRYPOINT: command to run when container starts.
  • CMD: command to run when container starts or arguments to ENTRYPOINT if specified.

Yes, it's mixing up.

You can override any of them when running docker run.

Difference between CMD and ENTRYPOINT by example:

docker run -it --rm yourcontainer /bin/bash            <-- /bin/bash overrides CMD
                                                       <-- /bin/bash does not override ENTRYPOINT
docker run -it --rm --entrypoint ls yourcontainer      <-- overrides ENTRYPOINT with ls
docker run -it --rm --entrypoint ls yourcontainer  -la  <-- overrides ENTRYPOINT with ls and overrides CMD with -la

More on difference between CMD and ENTRYPOINT:

Argument to docker run such as /bin/bash overrides any CMD command we wrote in Dockerfile.

ENTRYPOINT cannot be overriden at run time with normal commands such as docker run [args]. The args at the end of docker run [args] are provided as arguments to ENTRYPOINT. In this way we can create a container which is like a normal binary such as ls.

So CMD can act as default parameters to ENTRYPOINT and then we can override the CMD args from [args].

ENTRYPOINT can be overriden with --entrypoint.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

use ob_start(); before session_start(); at top of your page like this

<?php
ob_start();
session_start();

Unexpected token ILLEGAL in webkit

Also for the Google-fodder: check in your text editor whether the .js file is saved as Unicode and consider setting it to ANSI; also check if the linefeeds are set to DOS and consider switching them to Unix (depending on your server, of course).

How to get HQ youtube thumbnails?

Are you referring to the full resolution one?:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

I don't believe you can get 'multiple' images of HQ because the one you have is the one.

Check the following answer out for more information on the URLs: How do I get a YouTube video thumbnail from the YouTube API?

For live videos use https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault_live.jpg

- cornips

Printing Exception Message in java

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

How can I add spaces between two <input> lines using CSS?

Try to minimize the use of <br> as much as you possibly can. HTML is supposed to carry content and structure, <br> is neither. A simple workaround is to wrap your input elements in <p> elements, like so:

<form name="publish" id="publish" action="publishprocess.php" method="post">

    <p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
    <p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>

    <p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
    <p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>

    <p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>

    <p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
    <p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>

    <p>District Restriction:<?php echo $locationtext.$cityname; ?></p>

    <p><input type="submit" id="submit" value="Submit" /></p>
</form>

CodeIgniter - how to catch DB errors?

Try these CI functions

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

UPDATE FOR CODEIGNITER 3

Functions are deprecated, use error() instead:

$this->db->error(); 

What does += mean in Python?

a += b

is in this case the same as

a = a + b

In this case cnt += 1 means that cnt is increased by one.

Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.

Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.

shorthand If Statements: C#

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();

How to get current page URL in MVC 3

Add this extension method to your code:

public static Uri UrlOriginal(this HttpRequestBase request)
{
  string hostHeader = request.Headers["host"];

  return new Uri(string.Format("{0}://{1}{2}",
     request.Url.Scheme, 
     hostHeader, 
     request.RawUrl));
}

And then you can execute it off the RequestContext.HttpContext.Request property.

There is a bug (can be side-stepped, see below) in Asp.Net that arises on machines that use ports other than port 80 for the local website (a big issue if internal web sites are published via load-balancing on virtual IP and ports are used internally for publishing rules) whereby Asp.Net will always add the port on the AbsoluteUri property - even if the original request does not use it.

This code ensures that the returned url is always equal to the Url the browser originally requested (including the port - as it would be included in the host header) before any load-balancing etc takes place.

At least, it does in our (rather convoluted!) environment :)

If there are any funky proxies in between that rewrite the host header, then this won't work either.

Update 30th July 2013

As mentioned by @KevinJones in comments below - the setting I mention in the next section has been documented here: http://msdn.microsoft.com/en-us/library/hh975440.aspx

Although I have to say I couldn't get it work when I tried it - but that could just be me making a typo or something.

Update 9th July 2012

I came across this a little while ago, and meant to update this answer, but never did. When an upvote just came in on this answer I thought I should do it now.

The 'bug' I mention in Asp.Net can be be controlled with an apparently undocumented appSettings value - called 'aspnet:UseHostHeaderForRequest' - i.e:

<appSettings>
  <add key="aspnet:UseHostHeaderForRequest" value="true" />
</appSettings>

I came across this while looking at HttpRequest.Url in ILSpy - indicated by the ---> on the left of the following copy/paste from that ILSpy view:

public Uri Url
{
  get
  {
    if (this._url == null && this._wr != null)
    {
      string text = this.QueryStringText;
      if (!string.IsNullOrEmpty(text))
      {
        text = "?" + HttpEncoder.CollapsePercentUFromStringInternal(text, 
          this.QueryStringEncoding);
      }
 ---> if (AppSettings.UseHostHeaderForRequestUrl)
      {
        string knownRequestHeader = this._wr.GetKnownRequestHeader(28);
        try
        {
          if (!string.IsNullOrEmpty(knownRequestHeader))
          {
            this._url = new Uri(string.Concat(new string[]
            {
              this._wr.GetProtocol(),
              "://",
              knownRequestHeader,
              this.Path,
              text 
            }));
          }
        }
        catch (UriFormatException)
        { }
     }
     if (this._url == null) { /* build from server name and port */
       ...

I personally haven't used it - it's undocumented and so therefore not guaranteed to stick around - however it might do the same thing that I mention above. To increase relevancy in search results - and to acknowledge somebody else who seeems to have discovered this - the 'aspnet:UseHostHeaderForRequest' setting has also been mentioned by Nick Aceves on Twitter

How to get some values from a JSON string in C#?

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

Python - Get path of root project structure

This worked for me using a standard PyCharm project with my virtual environment (venv) under the project root directory.

Code below isnt the prettiest, but consistently gets the project root. It returns the full directory path to venv from the VIRTUAL_ENV environment variable e.g. /Users/NAME/documents/PROJECT/venv

It then splits the path at the last /, giving an array with two elements. The first element will be the project path e.g. /Users/NAME/documents/PROJECT

import os

print(os.path.split(os.environ['VIRTUAL_ENV'])[0])

How do you check if a JavaScript Object is a DOM Object?

This might be of interest:

function isElement(obj) {
  try {
    //Using W3 DOM2 (works for FF, Opera and Chrome)
    return obj instanceof HTMLElement;
  }
  catch(e){
    //Browsers not supporting W3 DOM2 don't have HTMLElement and
    //an exception is thrown and we end up here. Testing some
    //properties that all elements have (works on IE7)
    return (typeof obj==="object") &&
      (obj.nodeType===1) && (typeof obj.style === "object") &&
      (typeof obj.ownerDocument ==="object");
  }
}

It's part of the DOM, Level2.

Update 2: This is how I implemented it in my own library: (the previous code didn't work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).

//Returns true if it is a DOM node
function isNode(o){
  return (
    typeof Node === "object" ? o instanceof Node : 
    o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
  );
}

//Returns true if it is a DOM element    
function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}

How to add jQuery to an HTML page?

Inside of your <head></head> tags add...

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type=radio]').change(function() {

    $('input[type=radio]').each(function(index) {
        $(this).closest('tr').removeClass('selected');
    });

        $(this).closest('tr').addClass('selected');
    });
});
</script>

EDIT: The placement inside of <head></head> is not the only option...this could just as easily be placed RIGHT before the closing </body> tag. I generally try and place my JavaScript inside of head for placement reasons, but it can in some cases slow down page rendering so some will recommend the latter approach (before closing body).

How should I escape strings in JSON?

Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.

What is a raw type and why shouldn't we use it?

I found this page after doing some sample exercises and having the exact same puzzlement.

============== I went from this code as provide by the sample ===============

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

    Map wordMap = new HashMap();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            countWord(wordMap, args[i]);
        }
    } else {
        getWordFrequency(System.in, wordMap);
    }
    for (Iterator i = wordMap.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        System.out.println(entry.getKey() + " :\t" + entry.getValue());
    }

====================== To This code ========================

public static void main(String[] args) throws IOException {
    // replace with TreeMap to get them sorted by name
    Map<String, Integer> wordMap = new HashMap<String, Integer>();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            countWord(wordMap, args[i]);
        }
    } else {
        getWordFrequency(System.in, wordMap);
    }
    for (Iterator<Entry<String, Integer>> i = wordMap.entrySet().iterator(); i.hasNext();) {
        Entry<String, Integer> entry =   i.next();
        System.out.println(entry.getKey() + " :\t" + entry.getValue());
    }

}

===============================================================================

It may be safer but took 4 hours to demuddle the philosophy...

Remove Fragment Page from ViewPager in Android

I hope this can help what you want.

private class MyPagerAdapter extends FragmentStatePagerAdapter {

    //... your existing code

    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_UNCHANGED;
    }
}

Prevent RequireJS from Caching Required Scripts

Quick Fix for Development

For development, you could just disable the cache in Chrome Dev Tools (Disabling Chrome cache for website development). The cache disabling happens only if the dev tools dialog is open, so you need not worry about toggling this option every time you do regular browsing.

Note: Using 'urlArgs' is the proper solution in production so that users get the latest code. But it makes debugging difficult because chrome invalidates breakpoints with every refresh (because its a 'new' file being served each time).

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

Why are C++ inline functions in the header?

This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

How to get these two divs side-by-side?

User float:left property in child div class

check for div structure in detail : http://www.dzone.com/links/r/div_table.html

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)

What are the correct version numbers for C#?

C# 1.0 - Visual Studio .NET 2002

Classes
Structs
Interfaces
Events
Properties
Delegates
Expressions
Statements
Attributes
Literals

C# 1.2 - Visual Studio .NET 2003

Dispose in foreach
foreach over string specialization
C# 2 - Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Getter/setter separate accessibility
Method group conversions (delegates)
Static classes
Delegate inference

C# 3 - Visual Studio 2008

Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expression
Expression trees
Partial methods

C# 4 - Visual Studio 2010

Dynamic binding
Named and optional arguments
Co- and Contra-variance for generic delegates and interfaces
Embedded interop types ("NoPIA")

C# 5 - Visual Studio 2012

    Asynchronous methods
    Caller info attributes

C# 6 - Visual Studio 2015

Draft Specification online
Compiler-as-a-service (Roslyn)
Import of static type members into namespace
Exception filters
Await in catch/finally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator (null-conditional operator, succinct null checking)
String interpolation
nameof operator
Dictionary initializer

C# 7.0 - Visual Studio 2017

Out variables
Pattern matching
Tuples
Deconstruction
Discards
Local Functions
Binary Literals
Digit Separators
Ref returns and locals
Generalized async return types
More expression-bodied members
Throw expressions

C# 7.1 - Visual Studio 2017 version 15.3

Async main
Default expressions
Reference assemblies
Inferred tuple element names
Pattern-matching with generics

C# 7.2 - Visual Studio 2017 version 15.5

Span and ref-like types
In parameters and readonly references
Ref conditional
Non-trailing named arguments
Private protected accessibility
Digit separator after base specifier

C# 7.3 - Visual Studio 2017 version 15.7

System.Enum, System.Delegate and unmanaged constraints.
Ref local re-assignment: Ref locals and ref parameters can now be reassigned with the ref assignment operator (= ref).
Stackalloc initializers: Stack-allocated arrays can now be initialized, e.g. Span<int> x = stackalloc[] { 1, 2, 3 };.
Indexing movable fixed buffers: Fixed buffers can be indexed into without first being pinned.
Custom fixed statement: Types that implement a suitable GetPinnableReference can be used in a fixed statement.
Improved overload candidates: Some overload resolution candidates can be ruled out early, thus reducing ambiguities.
Expression variables in initializers and queries: Expression variables like out var and pattern variables are allowed in field initializers, constructor initializers and LINQ queries.
Tuple comparison: Tuples can now be compared with == and !=.
Attributes on backing fields: Allows [field: …] attributes on an auto-implemented property to target its backing field.

C# 8.0 - .NET Core 3.0 and Visual Studio 2019 version 16.3

Nullable reference types: express nullability intent on reference types with ?, notnull constraint and annotations attributes in APIs, the compiler will use those to try and detect possible null values being dereferenced or passed to unsuitable APIs.
Default interface members: interfaces can now have members with default implementations, as well as static/private/protected/internal members except for state (ie. no fields).
Recursive patterns: positional and property patterns allow testing deeper into an object, and switch expressions allow for testing multiple patterns and producing corresponding results in a compact fashion.
Async streams: await foreach and await using allow for asynchronous enumeration and disposal of IAsyncEnumerable<T> collections and IAsyncDisposable resources, and async-iterator methods allow convenient implementation of such asynchronous streams.
Enhanced using: a using declaration is added with an implicit scope and using statements and declarations allow disposal of ref structs using a pattern.
Ranges and indexes: the i..j syntax allows constructing System.Range instances, the ^k syntax allows constructing System.Index instances, and those can be used to index/slice collections.
Null-coalescing assignment: ??= allows conditionally assigning when the value is null.
Static local functions: local functions modified with static cannot capture this or local variables, and local function parameters now shadow locals in parent scopes.
Unmanaged generic structs: generic struct types that only have unmanaged fields are now considered unmanaged (ie. they satisfy the unmanaged constraint).
Readonly members: individual members can now be marked as readonly to indicate and enforce that they do not modify instance state.
Stackalloc in nested contexts: stackalloc expressions are now allowed in more expression contexts.
Alternative interpolated verbatim strings: @$"..." strings are recognized as interpolated verbatim strings just like $@"...".
Obsolete on property accessors: property accessors can now be individually marked as obsolete.
Permit t is null on unconstrained type parameter

[source] : https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md

How can I simulate mobile devices and debug in Firefox Browser?

I think it's better to use the chrome toggle device toolbar with the chrome inspector. It provides you a user agent switch along with responsive mode. enter image description here

How to get label of select option with jQuery?

Created working Plunker for this. https://plnkr.co/edit/vR9aGoCwoOUL9tevIEen $('#console').append("<br/>"+$('#test_s :selected').text())

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

How do I add records to a DataGridView in VB.Net?

If you want to add the row to the end of the grid use the Add() method of the Rows collection...

DataGridView1.Rows.Add(New String(){Value1, Value2, Value3})

If you want to insert the row at a partiular position use the Insert() method of the Rows collection (as GWLlosa also said)...

DataGridView1.Rows.Insert(rowPosition, New String(){value1, value2, value3})

I know you mentioned you weren't doing databinding, but if you defined a strongly-typed dataset with a single datatable in your project, you could use that and get some nice strongly typed methods to do this stuff rather than rely on the grid methods...

DataSet1.DataTable.AddRow(1, "John Doe", true)

Mouseover or hover vue.js

It's possible to toggle a class on hover strictly within a component's template, however, it's not a practical solution for obvious reasons. For prototyping on the other hand, I find it useful to not have to define data properties or event handlers within the script.

Here's an example of how you can experiment with icon colors using Vuetify.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app'_x000D_
})
_x000D_
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">_x000D_
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <v-app>_x000D_
    <v-toolbar color="black" dark>_x000D_
      <v-toolbar-items>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('pink--text')" @mouseleave="e => e.target.classList.toggle('pink--text')">delete</v-icon>_x000D_
        </v-btn>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('blue--text')" @mouseleave="e => e.target.classList.toggle('blue--text')">launch</v-icon>_x000D_
        </v-btn>_x000D_
        <v-btn icon>_x000D_
          <v-icon @mouseenter="e => e.target.classList.toggle('green--text')" @mouseleave="e => e.target.classList.toggle('green--text')">check</v-icon>_x000D_
        </v-btn>_x000D_
      </v-toolbar-items>_x000D_
    </v-toolbar>_x000D_
  </v-app>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to display custom view in ActionBar?

The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.

But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:

https://stackoverflow.com/a/16517395/614880

His code at bottom worked perfectly for me.

How to read numbers separated by space using scanf

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

How to get domain root url in Laravel 4?

UPDATE (2017-07-12)

A better solution is actually to use Request::getHost()

Previous answer:

I just checked and Request::root(); does return http://www.example.com in my case, no matter which route I'm on. You can then do the following to strip off the http:// part:

if (starts_with(Request::root(), 'http://'))
{
    $domain = substr (Request::root(), 7); // $domain is now 'www.example.com'
}

You may want to double check or post more code (routes.php, controller code, ...) if the problem persists.

Another solution is to simply use $_SERVER['SERVER_NAME'].

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

Add arm64 to the target's valid architectures. Looks like it adds x86-64 architecture to simulator valid architectures as well.

CSS performance relative to translateZ(0)

It forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.

Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).

Note: translate3d(0,0,0) does nothing in terms of what you see. It moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.

Good read here: http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/

How to get the query string by javascript?

Works for me-

function querySt(Key) {

    var url = window.location.href;

    KeysValues = url.split(/[\?&]+/); 

    for (i = 0; i < KeysValues.length; i++) {

            KeyValue= KeysValues[i].split("=");

            if (KeyValue[0] == Key) {

                return KeyValue[1];

        }

    }

}

function GetQString(Key) {     

    if (querySt(Key)) {

         var value = querySt(Key);

         return value;        

    }

 }

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

If some users of the code have different language settings format might not work. Thus I use the following code that gives the time stamp in format "yyymmdd hhMMss" regardless of language.

Function TimeStamp()
Dim iNow
Dim d(1 To 6)
Dim i As Integer


iNow = Now
d(1) = Year(iNow)
d(2) = Month(iNow)
d(3) = Day(iNow)
d(4) = Hour(iNow)
d(5) = Minute(iNow)
d(6) = Second(iNow)

For i = 1 To 6
    If d(i) < 10 Then TimeStamp = TimeStamp & "0"
    TimeStamp = TimeStamp & d(i)
    If i = 3 Then TimeStamp = TimeStamp & " "
Next i

End Function

Difference in make_shared and normal shared_ptr in C++

If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.

How to loop through array in jQuery?

ES6 syntax with arrow function and interpolation:

var data=["a","b","c"];
$(data).each((index, element) => {
        console.log(`current index : ${index} element : ${element}`)
    });

HintPath vs ReferencePath in Visual Studio

My own experience has been that it's best to stick to one of two kinds of assembly references:

  • A 'local' assembly in the current build directory
  • An assembly in the GAC

I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.

Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).

This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D

Hope that helps!

compareTo with primitives -> Integer / int

Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :

Integer a = 3; 

About comparision there is Math.signum(double d).

compare= (int) Math.signum(a-b); 

Date Difference in php on days?

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

Conditional statement in a one line lambda function in python?

In case you want to be lazier:

#syntax lambda x : (false,true)[Condition]

In your case:

rate = lambda(T) : (400*exp(-T),200*exp(-T))[T>200]

SQL Server JOIN missing NULL values

Try using ISNULL function:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
   ON Table1.Col1 = Table2.Col1 
   AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')

Where 'ZZZZ' is some arbitrary value never in the table.

Set Value of Input Using Javascript Function

I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).

Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.

Android Linear Layout - How to Keep Element At Bottom Of View?

Step 1 : Create two view inside a linear layout

Step 2 : First view must set to android:layout_weight="1"

Step 3 : Second view will automatically putted downwards

<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

    <View
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

    <Button
    android:id="@+id/btn_health_advice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>


</LinearLayout>

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

IF formula to compare a date with current date and return result

I think this will cover any possible scenario for what is in O10:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),IF(TODAY()-O10<>1,CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," days"),CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," day")),IF(O10=TODAY(),"Due Today","Overdue")))

For Dates that are before Today, it will tell you how many days the item is due in. If O10 = Today then it will say "Due Today". Anything past Today and it will read overdue. Lastly, if it is blank, the cell will also appear blank. Let me know what you think!

Static class initializer in PHP

If you don't like public static initializer, reflection can be a workaround.

<?php

class LanguageUtility
{
    public static function initializeClass($class)
    {
        try
        {
            // Get a static method named 'initialize'. If not found,
            // ReflectionMethod() will throw a ReflectionException.
            $ref = new \ReflectionMethod($class, 'initialize');

            // The 'initialize' method is probably 'private'.
            // Make it accessible before calling 'invoke'.
            // Note that 'setAccessible' is not available
            // before PHP version 5.3.2.
            $ref->setAccessible(true);

            // Execute the 'initialize' method.
            $ref->invoke(null);
        }   
        catch (Exception $e)
        {
        }
    }
}

class MyClass
{
    private static function initialize()
    {
    }
}

LanguageUtility::initializeClass('MyClass');

?>

Print newline in PHP in single quotes

FYI it is possible to get newlines into strings without double quotes:

printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);

Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.

Dynamic WHERE clause in LINQ

It seems much simpler and simpler to use the ternary operator to decide dynamically if a condition is included

List productList = new List();

        productList =
                db.ProductDetail.Where(p => p.ProductDetailID > 0 //Example prop
                && (String.IsNullOrEmpty(iproductGroupName) ? (true):(p.iproductGroupName.Equals(iproductGroupName)) ) //use ternary operator to make the condition dynamic
                && (ID == 0 ? (true) : (p.ID == IDParam))
                ).ToList();

How to calculate cumulative normal distribution?

Simple like this:

import math
def my_cdf(x):
    return 0.5*(1+math.erf(x/math.sqrt(2)))

I found the formula in this page https://www.danielsoper.com/statcalc/formulas.aspx?id=55

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

Why can't I set text to an Android TextView?

In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.

text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");

hope it will work.

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Why functional languages?

I don't think most realistic people think that functional programming will catch on (becomes the main paradigm like OO). After all, most business problems are not pretty math problems but hairy imperative rules to move data around and display them in various ways, which means it's not a good fit for pure functional programming paradigm (the learning curve of monad far exceeds OO.)

OTOH, functional programming is what makes programming fun. It makes you appreciate the inherent, timeless beauty of succinct expressions of the underlying math of the universe. People say that learning functional programming will make you a better programmer. This is of course highly subjective. I personally don't think that's completely true either.

It makes you a better sentient being.

Split pandas dataframe in two if it has more than 10 rows

Below is a simple function implementation which splits a DataFrame to chunks and a few code examples:

import pandas as pd

def split_dataframe_to_chunks(df, n):
    df_len = len(df)
    count = 0
    dfs = []

    while True:
        if count > df_len-1:
            break

        start = count
        count += n
        #print("%s : %s" % (start, count))
        dfs.append(df.iloc[start : count])
    return dfs


# Create a DataFrame with 10 rows
df = pd.DataFrame([i for i in range(10)])

# Split the DataFrame to chunks of maximum size 2
split_df_to_chunks_of_2 = split_dataframe_to_chunks(df, 2)
print([len(i) for i in split_df_to_chunks_of_2])
# prints: [2, 2, 2, 2, 2]

# Split the DataFrame to chunks of maximum size 3
split_df_to_chunks_of_3 = split_dataframe_to_chunks(df, 3)
print([len(i) for i in split_df_to_chunks_of_3])
# prints [3, 3, 3, 1]

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

Is embedding background image data into CSS as Base64 good or bad practice?

I disagree with the recommendation to create separate CSS files for non-editorial images.

Assuming the images are for UI purposes, it's presentation layer styling, and as mentioned above, if you're doing mobile UI's its definitely a good idea to keep all styling in a single file so it can be cached once.

How to use java.String.format in Scala?

You can use this;

String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");

Output:

a b b c

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

How to run TestNG from command line

After gone throug the various post, this worked fine for me doing on IntelliJ Idea:

java -cp "./lib/*;Path to your test.class"  org.testng.TestNG testng.xml

Here is my directory structure:

/lib
  -- all jar including testng.jar
/out
  --/production/Example1/test.class
/src
 -- test.java
testing.xml

So execute by this command:

java -cp "./lib/*;C:\Users\xyz\IdeaProjects\Example1\out\production\Example1" org.testng.TestNG testng.xml

My project directory Example1 is in the path:

C:\Users\xyz\IdeaProjects\

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Delete last commit in bitbucket

I've had trouble with git revert in the past (mainly because I'm not quite certain how it works.) I've had trouble reverting because of merge problems..

My simple solution is this.

Step 1.

 git clone <your repos URL> .

your project in another folder, then:

Step 2.

git reset --hard <the commit you wanna go to>

then Step 3.

in your latest (and main) project dir (the one that has the problematic last commit) paste the files of step 2

Step 4.

git commit -m "Fixing the previous messy commit" 

Step 5.

Enjoy

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

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

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

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

https://www.codeply.com/go/tgzFAH8vaW

Twitter Bootstrap 3 Sticky Footer

Here is a method that will add a sticky footer that doesn't require any additional CSS or Javascript other than what's already in Bootstrap and won't interfere with your current footer.

Example here: Easy Sticky Footer

Just copy and paste this directly into your code. No fuss no muss.

<div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <p class="navbar-text pull-left">© 2014 - Site Built By Mr. M.
           <a href="http://tinyurl.com/tbvalid" target="_blank" >HTML 5 Validation</a>
      </p>

      <a href="http://youtu.be/zJahlKPCL9g" class="navbar-btn btn-danger btn pull-right">
      <span class="glyphicon glyphicon-star"></span>  Subscribe on YouTube</a>
    </div>
</div>

Manually Set Value for FormBuilder Control

You could try this:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].updateValue(selected.id);
}

For more details, you could have a look at the corresponding JS Doc regarding the second parameter of the updateValue method: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/model.ts#L269.

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

I used the below to solve this problem.

import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);

Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.

Camel Case is usually without spaces between words.

How do I format a date in Jinja2?

You can use it like this in jinja template {{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}

In this code the field name is row.session_start_date_time.

capture div into image using html2canvas

It can be easily done using html2canvas, try out the following,

try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.

for example have a look at the code sample,

`

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">


            <div class="modal-body">
                <p>Some text in the modal.</p>

`

paste the div, which you want to be displayed, inside the model. Hope it will help.

How to center an iframe horizontally?

You can try

<h3 style="text-align:center;"><iframe src=""></iframe></h3>

I hope its useful for you

link

PHP session lost after redirect

First, carry out these usual checks:

  1. Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
  2. After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();)
  3. Make sure cookies are enabled in the browser you are using to test it on.
  4. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  5. Make sure you didn't delete or empty the session
  6. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
  7. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  8. Make sure your file extension is .php (it happens!)

Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:

session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();

(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:

<?php echo $_SERVER['SCRIPT_FILENAME']; ?>

The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation mappedBy ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class)

The annotation @JoinColumn is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.

below is the working example :

parent class , Company

@Entity
public class Company {


    private int companyId;
    private String companyName;
    private List<Branch> branches;

    @Id
    @GeneratedValue
    @Column(name="COMPANY_ID")
    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    @Column(name="COMPANY_NAME")
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="company")
    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }


}

child class, Branch

@Entity
public class Branch {

    private int branchId;
    private String branchName;
    private Company company;

    @Id
    @GeneratedValue
    @Column(name="BRANCH_ID")
    public int getBranchId() {
        return branchId;
    }

    public void setBranchId(int branchId) {
        this.branchId = branchId;
    }

    @Column(name="BRANCH_NAME")
    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COMPANY_ID")
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }


}

split string in two on given index and return both parts

ES6 1-liner

_x000D_
_x000D_
// :: splitAt = number => Array<any>|string => Array<Array<any>|string>_x000D_
const splitAt = index => x => [x.slice(0, index), x.slice(index)]_x000D_
_x000D_
console.log(_x000D_
  splitAt(1)('foo'), // ["f", "oo"]_x000D_
  splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]_x000D_
)_x000D_
  
_x000D_
_x000D_
_x000D_

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Probably this information will help. I was on Ubuntu 18.04 and when I tried to install Krita, using the ppa method, I got this error:

This application failed to start because it could not find or load the Qt platform plugin "xcb" in "".

Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.

Reinstalling the application may fix this problem.

Aborted

I tried all the solutions that I found in this thread and other webs without any success.

Finally, I found a post where the author mention that is possible to activate the debugging tool of qt5 using this simple command:

export QT_DEBUG_PLUGINS=1

After adding this command I run again krita I got the same error, however this time I knew the cause of that error.

libxcb-xinerama.so.0: cannot open shared object file: No such file or directory.

This error prevents to the "xcb" to load properly. So, the solution will be install the `libxcb-xinerama.so.0" right? However, when I run the command:

sudo apt install libxcb-xinerama

The lib was already installed. Now what Teo? Well, then I used an old trick :) Yeah, that one --reinstall

sudo apt install --reinstall libxcb-xinerama

TLDR: This last command solved my problem.

Rotating a two-dimensional array in Python

Consider the following two-dimensional list:

original = [[1, 2],
            [3, 4]]

Lets break it down step by step:

>>> original[::-1]   # elements of original are reversed
[[3, 4], [1, 2]]

This list is passed into zip() using argument unpacking, so the zip call ends up being the equivalent of this:

zip([3, 4],
    [1, 2])
#    ^  ^----column 2
#    |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise

Hopefully the comments make it clear what zip does, it will group elements from each input iterable based on index, or in other words it groups the columns.

jQuery convert line breaks to br (nl2br equivalent)

to improve @Luca Filosofi's accepted answer,

if needed, changing the beginning clause of this regex to be /([^>[\s]?\r\n]?) will also ingore the cases where the newline comes after a tag AND some whitespace, instead of just a tag immediately followed by a newline

How to get text with Selenium WebDriver in Python

I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:

driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text

click command in selenium webdriver does not work

Please refer here https://code.google.com/p/selenium/issues/detail?id=6756 In crux

Please open the system display settings and ensure that font size is set to 100% It worked surprisingly

How to stop execution after a certain time in Java?

Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.

With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

What order are the Junit @Before/@After called?

If you turn things around, you can declare your base class abstract, and have descendants declare setUp and tearDown methods (without annotations) that are called in the base class' annotated setUp and tearDown methods.

Do I commit the package-lock.json file created by npm 5?

Yes, it's intended to be checked in. I want to suggest that it gets its own unique commit. We find that it adds a lot of noise to our diffs.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

Another solution, it covered the problem I had with clicking descendants of the popover:

$(document).mouseup(function (e) {
    // The target is not popover or popover descendants
    if (!$(".popover").is(e.target) && 0 === $(".popover").has(e.target).length) {
        $("[data-toggle=popover]").popover('hide');
    }
});

How to generate unique id in MySQL?

This generates random ids:

CREATE TABLE Persons (
    ID Integer PRIMARY KEY AUTOINCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);

How can I reverse the order of lines in a file?

at the end of your command put: | tac

tac does exactly what you're asking for, it "Write each FILE to standard output, last line first."

tac is the opposite of cat :-).

how to check redis instance version?

To get the version of Redis server

redis-server -v

To get the version of Redis client

redis-cli -v

How do I change the default schema in sql developer?

I don't know of any way doing this in SQL Developer. You can see all the other schemas and their objects (if you have the correct privileges) when looking in "Other Users" -> "< Schemaname >".

In your case, either use the method described above or create a new connection for the schema in which you want to work or create synonyms for all the tables you wish to access.

If you would work in SQL*Plus, issuing ALTER SESSION SET CURRENT_SCHEMA=MY_NAME would set your current schema (This is probably what your DBA means).

How to detect the physical connected state of a network cable/connector?

tail -f /var/log/syslog | grep -E 'link (up|down)'

or for me faster gets:

tail -f /var/log/syslog | grep 'link \(up\|down\)'

It will listen to the syslog file.

Result (if disconnect and after 4 seconds connect again):

Jan 31 13:21:09 user kernel: [19343.897157] r8169 0000:06:00.0 enp6s0: link down
Jan 31 13:21:13 user kernel: [19347.143506] r8169 0000:06:00.0 enp6s0: link up

How do you concatenate Lists in C#?

Try this:

myList1 = myList1.Concat(myList2).ToList();

Concat returns an IEnumerable<T> that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List<T>, you'll have to call ToList() on the IEnumerable<T> that is returned.

executing shell command in background from script

Building off of ngoozeff's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:

cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
  • &>/dev/null sets the command’s stdout and stderr to /dev/null instead of inheriting them from the parent process.
  • & makes the shell run the command in the background.
  • disown removes the “current” job, last one stopped or put in the background, from under the shell’s job control.

In some shells you can also use &! instead of & disown; they both have the same effect. Bash doesn’t support &!, though.

Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}" rather than "${cmd}":

cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;

If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.

Here's a function for it:

#!/bin/bash

# Run a command in the background.
_evalBg() {
    eval "$@" &>/dev/null & disown;
}

cmd="google-chrome";
_evalBg "${cmd}";

Also, see: Running bash commands in the background properly

How to generate unique ID with node.js

Install NPM uuid package (sources: https://github.com/kelektiv/node-uuid):

npm install uuid

and use it in your code:

var uuid = require('uuid');

Then create some ids ...

// Generate a v1 (time-based) id
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'

// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

** UPDATE 3.1.0
The above usage is deprecated, so use this package like this:

const uuidv1 = require('uuid/v1');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

const uuidv4 = require('uuid/v4');
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

** UPDATE 7.x
And now the above usage is deprecated as well, so use this package like this:

const { v1: uuidv1 } = require('uuid');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

const { v4: uuidv4 } = require('uuid');
uuidv4(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

Add line break within tooltips

if you are using jquery-ui 1.11.4:

var tooltip = $.widget( "ui.tooltip", {
    version: "1.11.4",
    options: {
        content: function() {
            // support: IE<9, Opera in jQuery <1.7
            // .text() can't accept undefined, so coerce to a string
            var title = $( this ).attr( "title" ) || "";
            // Escape title, since we're going from an attribute to raw HTML
Replace-->  //return $( "<a>" ).text( title ).html();
by -->      return $( "<a>" ).html( title );
             },

Render a string in HTML and preserve spaces and linebreaks

You can use white-space: pre-line to preserve line breaks in formatting. There is no need to manually insert html elements.

.popover {
    white-space: pre-line;    
}

or add to your html element style="white-space: pre-line;"

How do I do a case-insensitive string comparison?

How about converting to lowercase first? you can use string.lower().

Length of string in bash

Using your example provided

#KISS (Keep it simple stupid)
size=${#myvar}
echo $size

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I dont understand the frustrations. Why not just make a broadcastreceiver that filters for this intent:

android.provider.Telephony.MMS_RECEIVED

I checked a little further and you might need system level access to get this (rooted phone).

How do I join two lists in Java?

Off the top of my head, I can shorten it by one line:

List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

How to set default value for column of new created table from select statement in 11g

new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 as select * from t1;

This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax

create table t1 (id number default 1 unique);
insert into t1 (id) values (2);

create table t2 (id default 1 unique)
as select * from t1;

Javascript : natural sort of alphanumerical strings

So you need a natural sort ?

If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.

It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

How can I clear event subscriptions in C#?

class c1
{
    event EventHandler someEvent;
    ResetSubscriptions() => someEvent = delegate { };
}

It is better to use delegate { } than null to avoid the null ref exception.

NSURLConnection Using iOS Swift

Check Below Codes :

1. SynchronousRequest

Swift 1.2

    let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
    println("Synchronous\(jsonResult)")

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil


    do{

        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)

            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }



    }catch let error as NSError
    {
         print(error.localizedDescription)
    }

2. AsynchonousRequest

Swift 1.2

let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("Asynchronous\(jsonResult)")
       })

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

3. As usual URL connection

Swift 1.2

    var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.dataVal?.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{
    var error: NSErrorPointer=nil

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

    println(jsonResult)



}

Swift 2.0 +

   var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    dataVal.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

4. Asynchronous POST Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
     var stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    let stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

5. Asynchronous GET Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    request1.timeoutInterval = 60
    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

6. Image(File) Upload

Swift 2.0 +

  let mainURL = "YOUR_URL_HERE"

    let url = NSURL(string: mainURL)
    let request = NSMutableURLRequest(URL: url!)
    let boundary = "78876565564454554547676"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    request.HTTPMethod = "POST" // POST OR PUT What you want
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)





    var body = NSMutableData()

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your parameters

    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    // Append your Image/File Data

    var imageNameval = "HELLO.jpg"

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body




    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error


        }
        else {




            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print("Response:\(outputString)")


        }
    }
    dataTask.resume()

7. GET,POST,Etc Swift 3.0 +

let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
    cachePolicy: .useProtocolCachePolicy,
    timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want 

let session = URLSession.shared



  let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in

do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }
    dataTask.resume()

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

I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).

Once you find the htaccess file add the following line:

  1. Header set Access-Control-Allow-Origin "*" Just to see if it works. Warning: Do not use this line on a production server

It should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.

  1. Once you do have the above working change the * to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Genymotion Android emulator - adb access?

Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.

More info: https://stackoverflow.com/a/26630862/4154438

Get all mysql selected rows into an array

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

How to convert a Date to a formatted string in VB.net?

I like:

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)

Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

How to hide the title bar for an Activity in XML with existing custom theme

If you use this.requestWindowFeature(Window.FEATURE_NO_TITLE) user will still be able to see the title bar just for a moment during launch animation when activity starts through onCreate. If you use @android:style/Theme.Black.NoTitleBar as shown below then title bar won't be shown during launch animation.

<activity 
    android:name=".MainActivity" 
    android:label="My App"
    android:theme="@android:style/Theme.Black.NoTitleBar"
    android:screenOrientation="portrait">

above example will obviously override your existing application theme, if you have existing theme then add <item name="android:windowNoTitle">true</item> to it.

List all the files and folders in a Directory with PHP recursive function

here I have example for that

List all the files and folders in a Directory csv(file) read with PHP recursive function

<?php

/** List all the files and folders in a Directory csv(file) read with PHP recursive function */
function getDirContents($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            //$results[] = $path;
        }
    }

    return $results;
}





$files = getDirContents('/xampp/htdocs/medifree/lab');//here folder name where your folders and it's csvfile;


foreach($files as $file){
$csv_file =$file;
$foldername =  explode(DIRECTORY_SEPARATOR,$file);
//using this get your folder name (explode your path);
print_r($foldername);

if (($handle = fopen($csv_file, "r")) !== FALSE) {

fgetcsv($handle); 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
}
fclose($handle);
}

}

?>

http://myphpinformation.blogspot.in/2016/05/list-all-files-and-folders-in-directory-csv-file-read-with-php-recursive.html

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

how to call a onclick function in <a> tag?

Use the onclick as an attribute of your a, not part of the href

<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>

Fiddle: http://jsfiddle.net/Wt5La/

Adding 1 hour to time variable

You can do like this

    echo date('Y-m-d H:i:s', strtotime('4 minute'));
    echo date('Y-m-d H:i:s', strtotime('6 hour'));
    echo date('Y-m-d H:i:s', strtotime('2 day'));

What is the difference between a "function" and a "procedure"?

Example in C:

// function
int square( int n ) {
   return n * n;
}

// procedure
void display( int n ) {
   printf( "The value is %d", n );
}

Although you should note that the C Standard doesn't talk about procedures, only functions.

Getting attributes of a class

If you want to "get" an attribute, there is a very simple answer, which should be obvious: getattr

class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

It works dandy both in Python 2.7 and Python 3.x.

If you want a list of these items, you will still need to use inspect.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How to extract duration time from ffmpeg output?

For those who want to perform the same calculations with no additional software in Windows, here is the script for command line script:

set input=video.ts

ffmpeg -i "%input%" 2> output.tmp

rem search "  Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
    if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF

:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s

Same answer posted here: How to crop last N seconds from a TS video

How to convert DateTime to VarChar

Try the following:

CONVERT(varchar(10), [MyDateTimecolumn], 20)

For a full date time and not just date do:

CONVERT(varchar(23), [MyDateTimecolumn], 121)

See this page for convert styles:

http://msdn.microsoft.com/en-us/library/ms187928.aspx
OR
SQL Server CONVERT() Function

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

Just install the necessary types for react and it should solve the error.

if you are using yarn:

yarn add @types/react @types/react-dom @types/react-router-dom -D

if you are using npm:

npm install @types/react @types/react-dom @types/react-router-dom --save-dev

How to check for file lock?

Instead of using interop you can use the .NET FileStream class methods Lock and Unlock:

FileStream.Lock http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

FileStream.Unlock http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

EF 5 Enable-Migrations : No context type was found in the assembly

Change the default project to data access

change the default project dropdown in the package manager console to data access and give enable migrations...

Thats all success

Convert double/float to string

See if the BSD C Standard Library has fcvt(). You could start with the source for it that rather than writing your code from scratch. The UNIX 98 standard fcvt() apparently does not output scientific notation so you would have to implement it yourself, but I don't think it would be hard.

multiple plot in one figure in Python

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

I found this a while back when learning python

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

Win32Exception (0x80004005): The wait operation timed out

If you're using Entity Framework, you can extend the default timeout (to give a long-running query more time to complete) by doing:

myDbContext.Database.CommandTimeout = 300;

Where myDbContext is your DbContext instance, and 300 is the timeout value in seconds.

(Syntax current as of Entity Framework 6.)

What is it exactly a BLOB in a DBMS context

BLOB :

BLOB (Binary Large Object) is a large object data type in the database system. BLOB could store a large chunk of data, document types and even media files like audio or video files. BLOB fields allocate space only whenever the content in the field is utilized. BLOB allocates spaces in Giga Bytes.

USAGE OF BLOB :

You can write a binary large object (BLOB) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB value to your database, issue the appropriate INSERT or UPDATE statement and pass the BLOB value as an input parameter. If your BLOB is stored as text, such as a SQL Server text field, you can pass the BLOB as a string parameter. If the BLOB is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.

A useful link : Storing documents as BLOB in Database - Any disadvantages ?

Matrix Transpose in Python

Much easier with numpy:

>>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> arr.T
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
>>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
>>> theArray 
array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']], 
      dtype='|S1')
>>> theArray.T
array([['a', 'd', 'g'],
       ['b', 'e', 'h'],
       ['c', 'f', 'i']], 
      dtype='|S1')

Why use a READ UNCOMMITTED isolation level?

Use READ_UNCOMMITTED in situation where source is highly unlikely to change.

  • When reading historical data. e.g some deployment logs that happened two days ago.
  • When reading metadata again. e.g. metadata based application.

Don't use READ_UNCOMMITTED when you know souce may change during fetch operation.