Programs & Examples On #Hardware programming

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

How do I get whole and fractional parts from double in JSP/Java?

String value = "3.06";

if(!value.isEmpty()){
    if(value.contains(".")){    
        String block = value.substring(0,value.indexOf("."));
        System.out.println(block);
    }else{
        System.out.println(value);
    }
}

Returning JSON from a PHP Script

An easy way to format your domain objects to JSON is to use the Marshal Serializer. Then pass the data to json_encode and send the correct Content-Type header for your needs. If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.

For example the correct Content-Type for dealing with Javascript would be application/javascript.

Or if you need to support some pretty old browsers the safest would be text/javascript.

For all other purposes like a mobile app use application/json as the Content-Type.

Here is a small example:

<?php
...
$userCollection = [$user1, $user2, $user3];

$data = Marshal::serializeCollectionCallable(function (User $user) {
    return [
        'username' => $user->getUsername(),
        'email'    => $user->getEmail(),
        'birthday' => $user->getBirthday()->format('Y-m-d'),
        'followers => count($user->getFollowers()),
    ];
}, $userCollection);

header('Content-Type: application/json');
echo json_encode($data);

List all employee's names and their managers by manager name using an inner join

There are three tables- Equities(coulmns: ID,ISIN) and Bond(coulmns: ID,ISIN). Third table Securities(coulmns: ID,ISIN) contains all data from Equities and Bond tables. Write SQL queries to validate below: (1) Securities table should contain all the data from Equities and Bonds tables. (2) Securities table should not contain any data other than present in Equities and Bonds tables

Assignment inside lambda expression in Python

There's no need to use a lambda, when you can remove all the null ones, and put one back if the input size changes:

input = [Object(name=""), Object(name="fake_name"), Object(name="")] 
output = [x for x in input if x.name]
if(len(input) != len(output)):
    output.append(Object(name=""))

How to "select distinct" across multiple data frame columns in pandas?

I think use drop duplicate sometimes will not so useful depending dataframe.

I found this:

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

And work for me!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

There are several answers regarding this question but all are related to right path configuration of JDK, but with JRE only we can solve this problem.

We just need to make use of deployment assembly to configure the path of packaged war file of the Java EE Project and then re-run the maven-install.

Steps to make use of deployment assembly:

  1. Right click on the Jave EE project --> click on Properties --> click on Deployment Assembly

  2. Click on Add button --> Click on Archives from the File System --> Click on next --> Click on Add --> Go to the .m2\respository directory and search for the war file generated --> Select war file --> Click on Open button --> Click on Apply --> OK

  3. Right click on the project --> Click on Maven Install under Run As

This will build your project successfully, without any compiler error.

Hope this solves the problem without JDK.

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

Xpath: select div that contains class AND whose specific child element contains text

You can use ancestor. I find that this is easier to read because the element you are actually selecting is at the end of the path.

//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]

Get domain name

 protected void Page_Init(object sender, EventArgs e)
 {
   String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
 }

Thymeleaf: Concatenation - Could not parse as expression

But from what I see you have quite a simple error in syntax

<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>

the correct syntax would look like

<p th:text="${bean.field + '!' + bean.field}">Static content</p>

As a matter of fact, the syntax th:text="'static part' + ${bean.field}" is equal to th:text="${'static part' + bean.field}".

Try it out. Even though this is probably kind of useless now after 6 months.

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

How to open existing project in Eclipse

i use Mac and i deleted ADT bundle source. faced the same error so i went to project > clean and adb ran normally.

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

Connecting an input stream to an outputstream

Asynchronous way to achieve it.

void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                int d;
                while ((d = inputStream.read()) != -1) {
                    out.write(d);
                }
            } catch (IOException ex) {
                //TODO make a callback on exception.
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

Best way to convert strings to symbols in hash

In case the reason you need to do this is because your data originally came from JSON, you could skip any of this parsing by just passing in the :symbolize_names option upon ingesting JSON.

No Rails required and works with Ruby >1.9

JSON.parse(my_json, :symbolize_names => true)

Create table (structure) from existing table

I needed to copy a table from one database another database. For anyone using a GUI like Sequel Ace you can right click table and click 'copy create table syntax' and run that query (you can edit the query, e.g. change table name, remove foreign keys, add/remove columns if desired)

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

onclick="javascript:history.go(-1)" not working in Chrome

Use Simply this line code, there is no need to put anything in href attribute:

<a href="" onclick="window.history.go(-1)"> Go TO Previous Page</a>

Adding local .aar files to Gradle build using "flatDirs" is not working

This is my structure, and how I solve this:

MyProject/app/libs/mylib-1.0.0.aar

MyProject/app/myModulesFolder/myLibXYZ

On build.gradle

from Project/app/myModulesFolder/myLibXYZ

I have put this:

repositories {
   flatDir {
    dirs 'libs', '../../libs'
  }
}
compile (name: 'mylib-1.0.0', ext: 'aar')

Done and working fine, my submodule XYZ depends on somelibrary from main module.

Android Studio Rendering Problems : The following classes could not be found

I have faced this issue when I introduced additional supporting libraries in my project IntelliJ IDEA

So for me "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

Python variables as keys to dict

Here it is in one line, without having to retype any of the variables or their values:

fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})

How to hide Table Row Overflow?

In most modern browsers, you can now specify:

<table>
 <colgroup>
  <col width="100px" />
  <col width="200px" />
  <col width="145px" />
 </colgroup>
 <thead>
  <tr>
   <th>My 100px header</th>
   <th>My 200px header</th>
   <th>My 145px header</th>
  </tr>
 </thead>
 <tbody>
  <td>100px is all you get - anything more hides due to overflow.</td>
  <td>200px is all you get - anything more hides due to overflow.</td>
  <td>100px is all you get - anything more hides due to overflow.</td>
 </tbody>
</table>

Then if you apply the styles from the posts above, as follows:

table {
    table-layout: fixed; /* This enforces the "col" widths. */
}
table th, table td {
    overflow: hidden;
    white-space: nowrap;
}

The result gives you nicely hidden overflow throughout the table. Works in latest Chrome, Safari, Firefox and IE. I haven't tested in IE prior to 9 - but my guess is that it will work back as far as 7, and you might even get lucky enough to see 5.5 or 6 support. ;)

How to style a div to be a responsive square?

This is what I came up with. Here is a fiddle.

First, I need three wrapper elements for both a square shape and centered text.

<div><div><div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.</div></div></div>

This is the stylecheet. It makes use of two techniques, one for square shapes and one for centered text.

body > div {
    position:relative;
    height:0;
    width:50%; padding-bottom:50%;
}

body > div > div {
    position:absolute; top:0;
    height:100%; width:100%;
    display:table;
    border:1px solid #000;
    margin:1em;
}

body > div > div > div{
    display:table-cell;
    vertical-align:middle; text-align:center;
    padding:1em;
}

How do I loop through rows with a data reader in C#?

Or you can try to access the columns directly by name:

while(dr.Read())
{
    string col1 = (string)dr["Value1"];
    string col2 = (string)dr["Value2"];
    string col3 = (string)dr["Value3"];
}

How to make Java work with SQL Server?

Maybe a little late, but using different drivers altogether is overkill for a case of user error:

db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );

should be either one of these:

db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );

(using named pipe) or:

db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );

using port number directly; you can leave out 1433 because it's the default port, leaving:

db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );

How to upsert (update or insert) in SQL Server 2005

You can use @@ROWCOUNT to check whether row should be inserted or updated:

update table1 
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
if @@ROWCOUNT = 0
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')

in this case if update fails, the new row will be inserted

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

How can I switch to another branch in git?

Switching to another branch in git. Straightforward answer,

git-checkout - Switch branches or restore working tree files

git fetch origin         <----this will fetch the branch
git checkout branch_name <--- Switching the branch

Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.

python dictionary sorting in descending order based on values

Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

How to fix 'sudo: no tty present and no askpass program specified' error?

This worked for me:

echo "myuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

where your user is "myuser"

for a Docker image, that would just be:

RUN echo "myuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

C# if/then directives for debug vs release

DEBUG/_DEBUG should be defined in VS already.

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build.

The reason it prints "Mode=Debug" is because of your #define and then skips the elif.

The right way to check is:

#if DEBUG
    Console.WriteLine("Mode=Debug"); 
#else
    Console.WriteLine("Mode=Release"); 
#endif

Don't check for RELEASE.

List names of all tables in a SQL Server 2012 schema

SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

How to get current time and date in Android

Try to use the below code:

 Date date = new Date();
 SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());  
 String currentDate = dateFormatWithZone.format(date);

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

Java - checking if parseInt throws exception

instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

Clear text field value in JQuery

you can clear it by using this line

$('#TextBoxID').val("");

How to part DATE and TIME from DATETIME in MySQL

You can achieve that using DATE_FORMAT() (click the link for more other formats)

SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY, 
       DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY

SQLFiddle Demo

String to decimal conversion: dot separation instead of comma

You are viewing your decimal or double values in Visual Studio. That doesn't respect the culture settings you have on your code.

Change the Region and Language settings on your Control Panel if you want to see decimal and double values having the comma as the decimal separator.

java.lang.OutOfMemoryError: GC overhead limit exceeded

For this use below code in your app gradle file under android closure.

dexOptions { javaMaxHeapSize "4g" }

How to select id with max date group by category in PostgreSQL?

SELECT id FROM tbl GROUP BY cat HAVING MAX(date)

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Count immediate child div elements using jQuery

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/

R adding days to a date

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

How do I empty an array in JavaScript?

Ways to clear an existing array A:

Method 1

(this was my original answer to the question)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

This is also the fastest solution.

This code sample shows the issue you can encounter when using this method:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

Method 3 (as suggested by Anthony)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

Method 4 (as suggested by tanguy_k)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

Performance

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

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

The answers posted here, for example,

$('#yourdropdownid option:selected').text();

didn't work for me, but this did:

$('#yourdropdownid').find('option:selected').text();

It is possibly an older version of jQuery.

IE6/IE7 css border on select element

From my personal experience where we tryed to put the border red when an invalid entry was selected, it is impossible to put border red of select element in IE.

As stated before the ocntrols in internet explorer uses WindowsAPI to draw and render and you have nothing to solve this.

What was our solution was to put the background color of select element light red (for text to be readable). background color was working in every browser, but in IE we had a side effects that the element where the same background color as the select.

So to summarize the solution we putted :

select
{
  background-color:light-red;
  border: 2px solid red;
}
option
{
  background-color:white;
}

Note that color was set with hex code, I just don't remember which.

This solution was giving us the wanted effect in every browser except for the border red in IE.

Good luck

window.print() not working in IE

I was told to do document.close after document.write, I dont see how or why but this caused my script to wait until I closed the print dialog before it ran my window.close.

var printContent = document.getElementbyId('wrapper').innerHTML;
var disp_setting="toolbar=no,location=no,directories=no,menubar=no, scrollbars=no,width=600, height=825, left=100, top=25"
var printWindow = window.open("","",disp_setting);
printWindow.document.write(printContent);
printWindow.document.close();
printWindow.focus();
printWindow.print();

printWindow.close();

Why doesn't Git ignore my specified file?

I just tried this with git 1.7.3.1, and given a structure like:

repo/.git/
repo/.gitignore
repo/sites/default/settings.php

where repo thus is the "root" mentioned above (I would call it the root of your working tree), and .gitignore contains only sites/default/settings.php, the ignore works for me (and it does not matter whether .gitignore is added to the repo or not). Does this match your repo layout? If not, what differs?

How can I make XSLT work in chrome?

Check http://www.aranedabienesraices.com.ar

This site is built with XML/XSLT client-side. It works on IE6-7-8, FF, O, Safari and Chrome. Are you sending HTTP headers correctly? Are you respecting the same-origin policy?

How can I convert spaces to tabs in Vim or Linux?

If you have GNU coreutils installed, consider %!unexpand --first-only or for 4-space tabs, consider %!unexpand -t 4 --first-only (--first-only is present just in case you were accidentally invoking unexpand with --all).

Note that this will only replace the spaces preceding the prescribed tab stops, not the spaces that follow them; you will see no visual difference in vim unless you display tabs more literally; for example, my ~/.vimrc contains set list listchars=tab:?? (I suspect this is why you thought unexpand didn't work).

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

You can use npm i y-websockets-server and then use the below command

y-websockets-server --port 11000

and here in my case, the port No is 11000.

Keeping ASP.NET Session Open / Alive

Whenever you make a request to the server the session timeout resets. So you can just make an ajax call to an empty HTTP handler on the server, but make sure the handler's cache is disabled, otherwise the browser will cache your handler and won't make a new request.

KeepSessionAlive.ashx.cs

public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            context.Response.Cache.SetNoStore();
            context.Response.Cache.SetNoServerCaching();
        }
    }

.JS:

window.onload = function () {
        setInterval("KeepSessionAlive()", 60000)
}

 function KeepSessionAlive() {
 url = "/KeepSessionAlive.ashx?";
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, true);
        xmlHttp.send();
        }

@veggerby - There is no need for the overhead of storing variables in the session. Just preforming a request to the server is enough.

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

Using the GET parameter of a URL in JavaScript

Here's how you could do it in Coffee Script (just if anyone is interested).

decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

This works for me (no Azure), SQL 2008 R2 on dev server or localdb\mssqllocaldb on local workstation. Note: entity adds Create, CreateBy, Modified, ModifiedBy and Version columns.

public class Carrier : Entity
{
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

then create a mapping configuration class

public class CarrierMap : EntityTypeConfiguration<Carrier>
{
    public CarrierMap()
    {
        HasKey(p => p.Id);

        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(p => p.Code)
            .HasMaxLength(4)
            .IsRequired()
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsClustered = true, IsUnique = true }));

        Property(p => p.Name).HasMaxLength(255).IsRequired();
        Property(p => p.Created).HasPrecision(7).IsRequired();
        Property(p => p.Modified)
            .HasColumnAnnotation("IX_Modified", new IndexAnnotation(new IndexAttribute()))
            .HasPrecision(7)
            .IsRequired();
        Property(p => p.CreatedBy).HasMaxLength(50).IsRequired();
        Property(p => p.ModifiedBy).HasMaxLength(50).IsRequired();
        Property(p => p.Version).IsRowVersion();
    }
}

This creates an Up method in the initial DbMigration when you execute add-migration like this

        CreateTable(
            "scoFreightRate.Carrier",
            c => new
                {
                    Id = c.Guid(nullable: false, identity: true),
                    Code = c.String(nullable: false, maxLength: 4),
                    Name = c.String(nullable: false, maxLength: 255),
                    Created = c.DateTimeOffset(nullable: false, precision: 7),
                    CreatedBy = c.String(nullable: false, maxLength: 50),
                    Modified = c.DateTimeOffset(nullable: false, precision: 7,
                        annotations: new Dictionary<string, AnnotationValues>
                        {
                            { 
                                "IX_Modified",
                                new AnnotationValues(oldValue: null, newValue: "IndexAnnotation: { }")
                            },
                        }),
                    ModifiedBy = c.String(nullable: false, maxLength: 50),
                    Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                })
            .PrimaryKey(t => t.Id)
            .Index(t => t.Code, unique: true, clustered: true);

Note: that the Id columns does not get a default value, don't worry

Now execute Update-Database, and you should end up with a table definition in your database like this:

CREATE TABLE [scoFreightRate].[Carrier] (
    [Id]         UNIQUEIDENTIFIER   DEFAULT (newsequentialid()) NOT NULL,
    [Code]       NVARCHAR (4)       NOT NULL,
    [Name]       NVARCHAR (255)     NOT NULL,
    [Created]    DATETIMEOFFSET (7) NOT NULL,
    [CreatedBy]  NVARCHAR (50)      NOT NULL,
    [Modified]   DATETIMEOFFSET (7) NOT NULL,
    [ModifiedBy] NVARCHAR (50)      NOT NULL,
    [Version]    ROWVERSION         NOT NULL,
    CONSTRAINT [PK_scoFreightRate.Carrier] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);


GO
CREATE UNIQUE CLUSTERED INDEX [IX_Code]
    ON [scoFreightRate].[Carrier]([Code] ASC);

Note: we have a overridden the SqlServerMigrationSqlGenerator to ensure it does NOT make the Primary Key a Clustered index as we encourage our developers to set a better clustered index on tables

public class OurMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
    protected override void Generate(AddPrimaryKeyOperation addPrimaryKeyOperation)
    {
        if (addPrimaryKeyOperation == null) throw new ArgumentNullException("addPrimaryKeyOperation");
        if (!addPrimaryKeyOperation.Table.Contains("__MigrationHistory"))
            addPrimaryKeyOperation.IsClustered = false;
        base.Generate(addPrimaryKeyOperation);
    }

    protected override void Generate(CreateTableOperation createTableOperation)
    {
        if (createTableOperation == null) throw new ArgumentNullException("createTableOperation");
        if (!createTableOperation.Name.Contains("__MigrationHistory"))
            createTableOperation.PrimaryKey.IsClustered = false;
        base.Generate(createTableOperation);
    }

    protected override void Generate(MoveTableOperation moveTableOperation)
    {
        if (moveTableOperation == null) throw new ArgumentNullException("moveTableOperation");
        if (!moveTableOperation.CreateTableOperation.Name.Contains("__MigrationHistory")) moveTableOperation.CreateTableOperation.PrimaryKey.IsClustered = false;
        base.Generate(moveTableOperation);
    }
}

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

How to clear the canvas for redrawing

This is what I use, regardless boundaries and matrix transformations:

function clearCanvas(canvas) {
  const ctx = canvas.getContext('2d');
  ctx.save();
  ctx.globalCompositeOperation = 'copy';
  ctx.strokeStyle = 'transparent';
  ctx.beginPath();
  ctx.lineTo(0, 0);
  ctx.stroke();
  ctx.restore();
}

Basically, it saves the current state of the context, and draws a transparent pixel with copy as globalCompositeOperation. Then, restores the previous context state.

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

jQuery .on('change', function() {} not triggering for dynamically created inputs

You should provide a selector to the on function:

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

In that case, it will work as you expected. Also, it is better to specify some element instead of document.

Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

how to change directory using Windows command line

cd /driveName driveName:\pathNamw

How to add favicon.ico in ASP.NET site

_x000D_
_x000D_
    <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />
_x000D_
_x000D_
_x000D_

This worked for me. If anyone is troubleshooting while reading this - I found issues when my favicon.ico was not nested in the root folder. I had mine in the Resources folder and was struggling at that point.

how to get 2 digits after decimal point in tsql?

Assume that you have dynamic currency precision

  • value => 1.002431

  • currency precision => 3

  • `result => 1.002

CAST(Floor(your_float_value) AS VARCHAR) + '.' + REPLACE(STR(FLOOR((your_float_value FLOOR(your_float_value)) * power(10,cu_precision)), cu_precision), SPACE(1), '0')

SVG gradient using CSS

Here is a solution where you can add a gradient and change its colours using only CSS:

_x000D_
_x000D_
// JS is not required for the solution. It's used only for the interactive demo._x000D_
const svg = document.querySelector('svg');_x000D_
document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green'));_x000D_
document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red'));
_x000D_
svg.green stop:nth-child(1) {_x000D_
  stop-color: #60c50b;_x000D_
}_x000D_
svg.green stop:nth-child(2) {_x000D_
  stop-color: #139a26;_x000D_
}_x000D_
_x000D_
svg.red stop:nth-child(1) {_x000D_
  stop-color: #c84f31;_x000D_
}_x000D_
svg.red stop:nth-child(2) {_x000D_
  stop-color: #dA3448;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop offset="0%" />_x000D_
    <stop offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>_x000D_
_x000D_
<br/>_x000D_
<button id="greenButton">Green</button>_x000D_
<button id="redButton">Red</button>
_x000D_
_x000D_
_x000D_

Allow multi-line in EditText view in Android?

 <EditText
           android:id="@id/editText" //id of editText
           android:gravity="start"   // Where to start Typing
           android:inputType="textMultiLine" // multiline
           android:imeOptions="actionDone" // Keyboard done button
           android:minLines="5" // Min Line of editText
           android:hint="@string/Enter Data" // Hint in editText
           android:layout_width="match_parent" //width editText
           android:layout_height="wrap_content" //height editText
           /> 

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

Cannot checkout, file is unmerged

status tell you what to do.

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

you probably applied a stash or something else that cause a conflict.

either add, reset, or rm.

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

Best lightweight web server (only static content) for Windows

Have a look at mongoose:

  • single executable
  • very small memory footprint
  • allows multiple worker threads
  • easy to install as service
  • configurable with a configuration file if required

No tests found with test runner 'JUnit 4'

This happened to me as well. I tried restarting Eclipse and also prefixed my test-methods with tests. Neither worked.

The following step worked: Change all your test methods present in @BeforeClass and @AfterClass to static methods.

i.e. if you have your test method in the below format:

@BeforeClass
public void testBeforeClass(){
}

then change it to:

@BeforeClass
public static void testBeforeClass(){
}

This worked for me.

window.location.href doesn't redirect

Though it is very old question, i would like to answer as i faced same issue recently and got solution from here -

http://www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working Solution:

document.location.href = 'Your url',true;

This worked for me.

Iterating through a range of dates in Python

import datetime

def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
  # inclusive=False to behave like range by default
  if step.days > 0:
    while start < stop:
      yield start
      start = start + step
      # not +=! don't modify object passed in if it's mutable
      # since this function is not restricted to
      # only types from datetime module
  elif step.days < 0:
    while start > stop:
      yield start
      start = start + step
  if inclusive and start == stop:
    yield start

# ...

for date in daterange(start_date, end_date, inclusive=True):
  print strftime("%Y-%m-%d", date.timetuple())

This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count and most importantly the code becomes easier to read as you call the function from multiple places.

adb doesn't show nexus 5 device

ADB and driver versions matter. The newer the device, the lower the chances of an older version ADB to work correctly.

Apps using their own ADB copy need to be updated or at least have their ADB updated manually.

When installing Helium / Carbon for instance, it uses an old / incomplete ADB. Newer devices might not link to the ADB server for this very reason.

What I'm writing here should work for any future devices on Windows and possibly *nix OSes.

First the systems must be prepared. on Android:

  • activate developer mode, either from an app (like Helium, when prompted) or by accessing the about phone section, taping build number until the developer mode unlocks
  • in developer settings enable USB debugging
  • in security settings allow unknown sources
  • (when connected with USB cable) set USB connectivity to PTP mode (camera device, if so labeled)

in Windows:

  • uninstall older USB driver (with file removal) if there is one, but only when the device is connected and in developer mode, otherwise that particular device won't be listed
  • install latest USB driver after the device has been plugged in and developer mode is active, the device will be listed as unknown or other in Device Manager; the drivers can be downloaded separately from Google Android support site, these are the same as vendor drivers, with only fewer ID's in inf file making the driver not being recognized for all Android devices
  • if the driver does not recognise the device, no problem, install it generically: Manual Install > Show All Devices > Have Disk > pick inf location of the Android USB driver and from the list select Android ADB Interface; there's not need to edit the inf by adding hardware ids, the end result is the same
  • each of the modes, PTP and MTP will have their own driver entry, so if the device asks for MTP, the same driver installation procedure must be followed, again

Once these steps are/were previously done correctly, adb must be tested. If Android SDK was installed previously, open a command prompt where adb.exe is and test the listing of the device.

adb start-server IMPORTANT NOTE: This command will prompt the device to allow the communication between the computer it's been linked to on the first run. The prompt will also list an RSA key specific to the PC in question. Without this prompt on start-server, ADB will NOT work! Nor will any application relying on ADB.

adb devices Must list the device(s). If the list is empty, and most likely the RSA prompt did not occur, then no communication will work. If the list is empty the current ADB (and SDK) must be updated or installed fresh (in the case of apps bringing in their own ADB runtime, like Helium / Carbon).

In the case of applications that do bring their own ADB, if the version is old, and these apps insist in using it instead of the SDK one, these files need to be replaced with the latest ones from Android SDK. Plain and simple copy & paste.

As for Android SDK, the only required packages to be installed are SDK Tools and Platform-tools. There, ADB.exe will need some support libraries, on Windows these files are AdbWinApi.dll and AdbWinUsbApi.dll. After all is done, the SDK can be uninstalled from SDK Manager while being able to retain the ADB tool if this is the only runtime used, depending on the case in question.

How to reference Microsoft.Office.Interop.Excel dll?

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn't have access to NuGet.

  • Right-click on "References" and select "Add Reference".
  • Select "Extensions" on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type "excel" into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on "References" and select "Add Reference".
  • Select the ".NET" tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

Get multiple elements by Id

You should use querySelectorAll, this writes every occurrence in an array and it allows you to use forEach to get individual element.

document.querySelectorAll('[id=test]').forEach(element=> 
    document.write(element);
});

How to get terminal's Character Encoding

The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:

echo $LC_CTYPE

or

echo $LANG

Posting JSON Data to ASP.NET MVC

The simplest way of doing this

I urge you to read this blog post that directly addresses your problem.

Using custom model binders isn't really wise as Phil Haack pointed out (his blog post is linked in the upper blog post as well).

Basically you have three options:

  1. Write a JsonValueProviderFactory and use a client side library like json2.js to communicate wit JSON directly.

  2. Write a JQueryValueProviderFactory that understands the jQuery JSON object transformation that happens in $.ajax or

  3. Use the very simple and quick jQuery plugin outlined in the blog post, that prepares any JSON object (even arrays that will be bound to IList<T> and dates that will correctly parse on the server side as DateTime instances) that will be understood by Asp.net MVC default model binder.

Of all three, the last one is the simplest and doesn't interfere with Asp.net MVC inner workings thus lowering possible bug surface. Using this technique outlined in the blog post will correctly data bind your strong type action parameters and validate them as well. So it is basically a win win situation.

How can a divider line be added in an Android RecyclerView?

So this might not be the correct way, but I just added a view to the single item view of the RecyclerView (as I don't think there is a built-in function) like so:

<View
    android:layout_width="fill_parent"
    android:layout_height="@dimen/activity_divider_line_margin"
    android:layout_alignParentBottom="true"
    android:background="@color/tasklist_menu_dividerline_grey" />

This means each item will have a line which fills it at its bottom. I made it about 1dp high with a #111111 background. This also gives it a kind of "3D" effect.

Using setDate in PreparedStatement

Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.

try this:

private static java.sql.Date getCurrentDate(String date) {

    java.util.Date today;
    java.sql.Date rv = null;
    try {

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        today = format.parse(date);
        rv = new java.sql.Date(today.getTime());
        System.out.println(rv.getTime());

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    } finally {
        return rv;
    }

}    

Will return a java.sql.Date object for setDate();

The function above will print out a long value:

1375934400000

Call and receive output from Python script in Java?

The best way to achieve would be to use Apache Commons Exec as I use it for production without problems even for Java 8 environment because of the fact that it lets you execute any external process (including python, bash etc) in synchronous and asynchronous way by using watchdogs.

 CommandLine cmdLine = new CommandLine("python");
 cmdLine.addArgument("/my/python/script/script.py");
 DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

 ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
 Executor executor = new DefaultExecutor();
 executor.setExitValue(1);
 executor.setWatchdog(watchdog);
 executor.execute(cmdLine, resultHandler);

 // some time later the result handler callback was invoked so we
 // can safely request the exit value
 resultHandler.waitFor();

Complete source code for a small but complete POC is shared here that addresses another concern in this post;

https://github.com/raohammad/externalprocessfromjava.git

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

SDK Manager.exe doesn't work

I fixed this issue by reinstalling it in Program Files, it originally tried to install it in c:/Users/.../AppData/Android/....

Mine was caused by a user permission issue that running as admin didn't seem to fix (perhaps because they call batch files?).

Python: Convert timedelta to int in a dataframe

If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.days accessor you need either df.astype or pd.to_numeric

Either of these options should help:

df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')

or

df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

Nth word in a string variable

No expensive forks, no pipes, no bashisms:

$ set -- $STRING
$ eval echo \${$N}
three

But beware of globbing.

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

Git command to checkout any branch and overwrite local changes

Couple of points:

  • I believe git stash + git stash drop could be replaced with git reset --hard
  • ... or, even shorter, add -f to checkout command:

    git checkout -f -b $branch
    

    That will discard any local changes, just as if git reset --hard was used prior to checkout.

As for the main question: instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.

In javascript, how do you search an array for a substring match

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

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

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

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

java.net.URL read stream to byte[]

I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.

The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:

public static byte[] downloadFile(URL url)
{
    try {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect(); 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), baos);

        return baos.toByteArray();
    }
    catch (IOException e)
    {
        // Log error and return null, some default or throw a runtime exception
    }
}

How to convert a string with Unicode encoding to a string of letters

This simple method will work for most cases, but would trip up over something like "u005Cu005C" which should decode to the string "\u0048" but would actually decode "H" as the first pass produces "\u0048" as the working string which then gets processed again by the while loop.

static final String decode(final String in)
{
    String working = in;
    int index;
    index = working.indexOf("\\u");
    while(index > -1)
    {
        int length = working.length();
        if(index > (length-6))break;
        int numStart = index + 2;
        int numFinish = numStart + 4;
        String substring = working.substring(numStart, numFinish);
        int number = Integer.parseInt(substring,16);
        String stringStart = working.substring(0, index);
        String stringEnd   = working.substring(numFinish);
        working = stringStart + ((char)number) + stringEnd;
        index = working.indexOf("\\u");
    }
    return working;
}

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

If you need a body in your response, you can call

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

This will return a 500 with the response object...

How to delete a module in Android Studio

To delete a module in Android Studio 2.3.3,

  • Open File -> Project Structure
  • On Project Structure window, list of modules of the current project gets displayed on left panel. Select the module which needs to be deleted.
  • Then click - button on top left, that means just above left panel.

Pycharm and sys.argv arguments

Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.

Task vs Thread differences

Thread is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.

Task is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:

  • Task.Delay doesn't need any actual CPU time; it's just like setting a timer to go off in the future
  • A task returned by WebClient.DownloadStringTaskAsync won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)
  • A task returned by Task.Run() really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.

Note that the Task<T> abstraction is pivotal to the async support in C# 5.

In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.

How to impose maxlength on textArea in HTML using JavaScript

Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:

$("#comments").bind("keyup keydown", function() {
    var max = 500;
    var value = $(this).val();
    var left = max - value.length;
    if(left < 0) {
        $(this).val( value.slice(0, left) );
        left = 0;
    }
    $("#charcount").text(left);
}); 

<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>

HTML.ActionLink vs Url.Action in ASP.NET Razor

You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:

@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })

Initialize Array of Objects using NSArray

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

[persons addObject:[[[Person alloc] init] autorelease];

Change <br> height using CSS

This feels very hacky, but in chrome 41 on ubuntu I can make a <br> slightly stylable:

br {
  content: "";
  margin: 2em;
  display: block;
  font-size: 24%;
}

I control the spacing with the font size.


Update

I made some test cases to see how the response changes as browsers update.

_x000D_
_x000D_
*{outline: 1px solid hotpink;}
div {
  display: inline-block;
  width: 10rem;
  margin-top: 0;
  vertical-align: top;
}

h2 {
  display: block;
  height: 3rem;
  margin-top:0;
}

.old br {
  content: "";
  margin: 2em;
  display: block;
  font-size: 24%;
  outline: red;
}

.just-font br {
  content: "";
  display: block;
  font-size: 200%;
}
.just-margin br {
  content: "";
  display: block;
  margin: 2em;
}

.brbr br {
  content: "";
  display: block;
  font-size: 100%;
  height: 1em;
  outline: red;
  display: block;
}
_x000D_
<div class="raw">
  <h2>Raw <code>br</code>rrrrs</h2>
  bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
  
<div class="old">
  <h2>margin & font size</h2>
  bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
  
<div class="just-font">
  <h2>only font size</h2>
  bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>

 <div class="just-margin">
  <h2>only margin</h2>
  bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
   
<div class="brbr">
  <h2><code>br</code>others vs only <code>br</code>s</h2>
  bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
_x000D_
_x000D_
_x000D_

They all have their own version of strange behaviour. Other than the browser default, only the last one respects the difference between one and two brs.

Automatically enter SSH password with script

This is basically an extension of abbotto's answer, with some additional steps (aimed at beginners) to make starting up your server, from your linux host, very easy:

  1. Write a simple bash script, e.g.:
#!/bin/bash

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM
  1. Save the file, e.g. 'startMyServer', then make the file executable by running this in your terminal:
sudo chmod +x startMyServer
  1. Move the file to a folder which is in your 'PATH' variable (run 'echo $PATH' in your terminal to see those folders). So for example move it to '/usr/bin/'.

And voila, now you are able to get into your server by typing 'startMyServer' into your terminal.

P.S. (1) this is not very secure, look into ssh keys for better security.

P.S. (2) SMshrimant answer is quite similar and might be more elegant to some. But I personally prefer to work in bash scripts.

How to compile a c++ program in Linux?

As the other answers say, use g++ instead of gcc.

Or use make: make hi

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

how to generate public key from windows command prompt

Just download and install openSSH for windows. It is open source, and it makes your cmd ssh ready. A quick google search will give you a tutorial on how to install it, should you need it.

After it is installed you can just go ahead and generate your public key if you want to put in on a server. You generate it by running:

ssh-keygen -t rsa

After that you can just can just press enter, it will automatically assign a name for the key (example: id_rsa.pub)

Remove all newlines from inside a string

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

Google Chrome Full Black Screen

I still experience occasional black screens with latest Chrome 60 with GPU acceleration enabled by default (probably caused by lack of free memory for numerous tabs).

Sometimes it helps to kill GPU process in builtin Task manager (Shift+Esc) as @amit suggests. But sometimes this forces more Chrome windows to become black while some others may remain normal.

I've noticed that tabs headers and address bar of black windows remain funtional and tabs can be fully repaired just by dragging them out of black windows. But it's too tedious to do this one by one when their number is huge.

So here is quick completely restartless solution inspired by Merging windows of Google Chrome:

  • Add a new empty tab to black window (Ctrl+T)
  • Left-click the first tab in the window
  • Then hold the Shift key and left-click the right most tab just before the empty one
  • Drag all the selected tabs at once out of the black window
  • Close the black window with remaining single empty tab

When is it acceptable to call GC.Collect?

This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

Accessing Session Using ASP.NET Web API

I had this same problem in asp.net mvc, I fixed it by putting this method in my base api controller that all my api controllers inherit from:

    /// <summary>
    /// Get the session from HttpContext.Current, if that is null try to get it from the Request properties.
    /// </summary>
    /// <returns></returns>
    protected HttpContextWrapper GetHttpContextWrapper()
    {
      HttpContextWrapper httpContextWrapper = null;
      if (HttpContext.Current != null)
      {
        httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
      }
      else if (Request.Properties.ContainsKey("MS_HttpContext"))
      {
        httpContextWrapper = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
      }
      return httpContextWrapper;
    }

Then in your api call that you want to access the session you just do:

HttpContextWrapper httpContextWrapper = GetHttpContextWrapper();
var someVariableFromSession = httpContextWrapper.Session["SomeSessionValue"];

I also have this in my Global.asax.cs file like other people have posted, not sure if you still need it using the method above, but here it is just in case:

/// <summary>
/// The following method makes Session available.
/// </summary>
protected void Application_PostAuthorizeRequest()
{
  if (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api"))
  {
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
  }
}

You could also just make a custom filter attribute that you can stick on your api calls that you need session, then you can use session in your api call like you normally would via HttpContext.Current.Session["SomeValue"]:

  /// <summary>
  /// Filter that gets session context from request if HttpContext.Current is null.
  /// </summary>
  public class RequireSessionAttribute : ActionFilterAttribute
  {
    /// <summary>
    /// Runs before action
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
      if (HttpContext.Current == null)
      {
        if (actionContext.Request.Properties.ContainsKey("MS_HttpContext"))
        {
          HttpContext.Current = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).ApplicationInstance.Context;
        }
      }
    }
  }

Hope this helps.

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

How to find and turn on USB debugging mode on Nexus 4

Solution

To see the option for USB debugging mode in Nexus 4 or Android 4.2 or higher OS, do the following:

  • Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping “System settings”
  • Now scroll to the bottom and tap “About phone” or “About tablet”.
  • At the “About” screen, scroll to the bottom and tap on “Build number” seven times.
    • Make sure you tap seven times. If you see a “Not need, you are already a developer!” message pop up, then you know you have done it correctly.

Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.

CONCLUSION

That was easy. The best part is you only have to do the tap-build-number-seven-times once. After you do it once, USB debugging has been unlocked and you can enable or disable at your leisure. Please restart after done these steps.

Additional information

Setting up a Device for Development native documentation of Google Android developer site

Update: Google Pixel 3

If you need to facilitate a connection between your device and a computer with the Android SDK (software development kit), view this info.

  1. From a Home screen, swipe up to display all apps.
  2. Navigate: Settings > System > Advanced.
  3. Developer options .
    If Developer options isn't available, navigate: SettingsAbout phone then tap Build number 7 times. Tap the Back icon  to Settings then select System > Advanced > Developer options.
  4. Ensure that the Developer options switch (upper-right) is turned on .
  5. Tap USB debugging to turn on or off .
  6. If prompted with 'Allow USB debugging?', tap OK to confirm.

Doc by Verizon: Original source

django - get() returned more than one topic

In your Topic model you're allowing for more than one element to have the same topic field. You have created two with the same one already.

topic=models.TextField(verbose_name='Thema')

Now when trying to add a new learningObjective you seem to want to add it to only one Topic that matches what you're sending on the form. Since there's more than one with the same topic field get is finding 2, hence the exception.

You can either add the learningObjective to all Topics with that topic field:

for t in topic.objects.filter(topic=request.POST['Thema']):
    t.learningObjectivesTopic.add(neuesLernziel)

or restrict the Topic model to have a unique topic field and keep using get, but that might not be what you want.

Eclipse Java error: This selection cannot be launched and there are no recent launches

When you create a new class file, try to mark the check box near

public static void main(String[] args) {

this will help you to fix the problem.

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

How to create Windows EventLog source from command line?

you can create your own custom event by using diagnostics.Event log class. Open a windows application and on a button click do the following code.

System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "MyNewLog");

"MyNewLog" means the name you want to give to your log in event viewer.

for more information check this link [ http://msdn.microsoft.com/en-in/library/49dwckkz%28v=vs.90%29.aspx]

Using msbuild to execute a File System Publish Profile

First check the Visual studio version of the developer PC which can publish the solution(project). as shown is for VS 2013

 /p:VisualStudioVersion=12.0

add the above command line to specify what kind of a visual studio version should build the project. As previous answers, this might happen when we are trying to publish only one project, not the whole solution.

So the complete code would be something like this

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" "C:\Program Files (x86)\Jenkins\workspace\Jenkinssecondsample\MVCSampleJenkins\MVCSampleJenkins.csproj" /T:Build;Package /p:Configuration=DEBUG /p:OutputPath="obj\DEBUG" /p:DeployIisAppPath="Default Web Site/jenkinsdemoapp" /p:VisualStudioVersion=12.0

Java program to get the current date without timestamp

Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.

java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);

Thread.sleep(2000);

java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);

boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);

Output:

Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true

Unzipping files

I'm using zip.js and it seems to be quite useful. It's worth a look!

Check the Unzip demo, for example.

Java code To convert byte to Hexadecimal

If you like streams, here is a single-expression version of the format-and-concatenate approach:

String hex = IntStream.range(0, bytes.length)
                      .map(i -> bytes[i] & 0xff)
                      .mapToObj(b -> String.format("%02x", b))
                      .collect(Collectors.joining());

It's a shame there isn't a method like Arrays::streamUnsignedBytes for this.

How to go back to previous page if back button is pressed in WebView?

Full reference for next button and progress bar : put back and next button in webview

If you want to go to back page when click on phone's back button, use this:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
} 

You can also create custom back button like this:

btnback.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (wv.canGoBack()) {
                wv.goBack();
            }
        }
    }); 

Chrome desktop notification example

In modern browsers, there are two types of notifications:

  • Desktop notifications - simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds
  • Service Worker notifications - a bit more complicated, but they can work in the background (even after the page is closed), are persistent, and support action buttons

The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.


Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost:// or HTTPS.

_x000D_
_x000D_
// request permission on page load_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
 if (!Notification) {_x000D_
  alert('Desktop notifications not available in your browser. Try Chromium.');_x000D_
  return;_x000D_
 }_x000D_
_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
});_x000D_
_x000D_
_x000D_
function notifyMe() {_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
 else {_x000D_
  var notification = new Notification('Notification title', {_x000D_
   icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',_x000D_
   body: 'Hey there! You\'ve been notified!',_x000D_
  });_x000D_
  notification.onclick = function() {_x000D_
   window.open('http://stackoverflow.com/a/13328397/1269037');_x000D_
  };_x000D_
 }_x000D_
}
_x000D_
 <button onclick="notifyMe()">Notify me!</button>
_x000D_
_x000D_
_x000D_

We're using the W3C Notifications API. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.

W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.

Note that Chrome doesn't honor the notification icon on Linux, due to this bug.

Final words

Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.

Now the latest standard is at https://notifications.spec.whatwg.org/.

As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.

See also notify.js for a helper library.

How to get folder path from file path with CMD

In case anyone wants an alternative method...

If it is the last subdirectory in the path, you can use this one-liner:

cd "c:\directory\subdirectory\filename.exe\..\.." && dir /ad /b /s

This would return the following:

c:\directory\subdirectory

The .... drops back to the previous directory. /ad shows only directories /b is a bare format listing /s includes all subdirectories. This is used to get the full path of the directory to print.

ZIP Code (US Postal Code) validation

function isValidUSZip(sZip) {
   return /^\d{5}(-\d{4})?$/.test(sZip);
}

Undefined symbols for architecture x86_64 on Xcode 6.1

I solved the problem by deleting reference to the file and adding it again in project. In my case it works.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I was receiving this error CastError: Cast to ObjectId failed for value “[object Object]” at path “_id” after creating a schema, then modifying it and couldn't track it down. I deleted all the documents in the collection and I could add 1 object but not a second. I ended up deleting the collection in Mongo and that worked as Mongoose recreated the collection.

How to convert a byte array to its numeric value (Java)?

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

Running code after Spring Boot starts

You can extend a class using ApplicationRunner , override the run() method and add the code there.

import org.springframework.boot.ApplicationRunner;

@Component
public class ServerInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        //code goes here

    }
}

How to get element value in jQuery

Did you want the HTML or text that is inside the li tag?

If so, use either:

$(this).html()

or:

$(this).text()

The val() is for form fields only.

PHP: Inserting Values from the Form into MySQL

Try this:

dbConfig.php

<?php
$mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name');
    if($mysqli->connect_error)
        {
        echo $mysqli->connect_error;
        }
    ?>

Index.php

<html>
<head><title>Inserting data in database table </title>
</head>
<body>
<form action="control_table.php" method="post">
<table border="1" background="red" align="center">
<tr>
<td>Login Name</td>
<td><input type="text" name="txtname" /></td>
</tr>
<br>
<tr>
<td>Password</td>
<td><input type="text" name="txtpwd" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="txtbutton" value="SUBMIT" /></td>
</tr>
</table>
control_table.php
<?php include 'config.php'; ?>
<?php
$name=$pwd="";
    if(isset($_POST['txtbutton']))
        {
            $name = $_POST['txtname'];
            $pwd = $_POST['txtpwd'];
            $mysqli->query("insert into users(name,pwd) values('$name', '$pwd')");
        if(!$mysqli) 
        { echo mysqli_error(); }
    else
    {
        echo "Successfully Inserted <br />";
        echo "<a href='show.php'>View Result</a>";
    }

         }  

    ?>

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

I was able to toggle this error by changing a single thing. In my ASP.Net Core 1.0 RC2 Web Application project's launchSettings.json file:

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "https://localhost:18177/",
      "sslPort": 0
    }
  },

to

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:18177/",
      "sslPort": 0
    }
  },

I had changed to https in an attempt to run the project using that protocol. Apparently this is not the place to make that change. I suspect it is creating multiple bindings on the same port, and IIS Express doesn't like that.

What is the difference between g++ and gcc?

For c++ you should use g++.

It's the same compiler (e.g. the GNU compiler collection). GCC or G++ just choose a different front-end with different default options.

In a nutshell: if you use g++ the frontend will tell the linker that you may want to link with the C++ standard libraries. The gcc frontend won't do that (also it could link with them if you pass the right command line options).

Xcode error "Could not find Developer Disk Image"

For people who would have similar problems in the future, beware that this problem is fundamentally rooted in the mismatch of your iOS version and Xcode version.

Check the compatibility of iOS and Xcode.

ERROR: Sonar server 'http://localhost:9000' can not be reached

In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This kind of logic could be implemented using EXISTS:

CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');

Query:

DECLARE @a INT;

--SET @a = 1;    -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1;   -- all values

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');

db<>fiddle demo

It could be extended to contain multiple params:

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
  AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');

how to customize `show processlist` in mysql?

The command

show full processlist

can be replaced by:

SELECT * FROM information_schema.processlist

but if you go with the latter version you can add WHERE clause to it:

SELECT * FROM information_schema.processlist WHERE `INFO` LIKE 'SELECT %';

For more information visit this

How can I check Drupal log files?

To view entries in Drupal's own internal log system (the watchdog database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.

Use the watchdog() function to add an entry to this log from your own custom module.

When Drupal bootstraps it uses the PHP function set_error_handler() to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog() call at admin/reports/dblog. If you look for PHP fatal errors, for example, in /var/log/apache/error.log and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log, or wherever you have it configured to log to.

Fill username and password using selenium in python

driver = webdriver.Firefox(...)  # Or Chrome(), or Ie(), or Opera()

username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")

username.send_keys("YourUsername")
password.send_keys("Pa55worD")

driver.find_element_by_name("submit").click()

Notes to your code:

MySQL vs MongoDB 1000 reads

MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL team could just incorporate it into their codebase.

People are seeing real world MongoDB performance largely because MongoDB allows you to query in a different manner that is more sensible to your workload.

For example, consider a design that persisted a lot of information about a complicated entity in a normalised fashion. This could easily use dozens of tables in MySQL (or any relational db) to store the data in normal form, with many indexes needed to ensure relational integrity between tables.

Now consider the same design with a document store. If all of those related tables are subordinate to the main table (and they often are), then you might be able to model the data such that the entire entity is stored in a single document. In MongoDB you can store this as a single document, in a single collection. This is where MongoDB starts enabling superior performance.

In MongoDB, to retrieve the whole entity, you have to perform:

  • One index lookup on the collection (assuming the entity is fetched by id)
  • Retrieve the contents of one database page (the actual binary json document)

So a b-tree lookup, and a binary page read. Log(n) + 1 IOs. If the indexes can reside entirely in memory, then 1 IO.

In MySQL with 20 tables, you have to perform:

  • One index lookup on the root table (again, assuming the entity is fetched by id)
  • With a clustered index, we can assume that the values for the root row are in the index
  • 20+ range lookups (hopefully on an index) for the entity's pk value
  • These probably aren't clustered indexes, so the same 20+ data lookups once we figure out what the appropriate child rows are.

So the total for mysql, even assuming that all indexes are in memory (which is harder since there are 20 times more of them) is about 20 range lookups.

These range lookups are likely comprised of random IO — different tables will definitely reside in different spots on disk, and it's possible that different rows in the same range in the same table for an entity might not be contiguous (depending on how the entity has been updated, etc).

So for this example, the final tally is about 20 times more IO with MySQL per logical access, compared to MongoDB.

This is how MongoDB can boost performance in some use cases.

Create an Array of Arraylists

You can't create array of generic type. Create List of ArrayLists :

 List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();

or if you REALLY need array (WARNING: bad design!):

 ArrayList[] group = new ArrayList[4];

symfony 2 twig limit the length of the text and put three dots

{{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text  }}

You need Twig 1.6

View stored procedure/function definition in MySQL

You can use this:

SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";

jquery input select all on focus

Works great with the native JavaScript select().

$("input[type=text]").focus(function(event) {
   event.currentTarget.select();
});

or in general:

$("input[type=text]")[0].select()

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

How to make an unaware datetime timezone aware in python

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

Virtual member call in a constructor

Just to add my thoughts. If you always initialize the private field when define it, this problem should be avoid. At least below code works like a charm:

class Parent
{
    public Parent()
    {
        DoSomething();
    }
    protected virtual void DoSomething()
    {
    }
}

class Child : Parent
{
    private string foo = "HELLO";
    public Child() { /*Originally foo initialized here. Removed.*/ }
    protected override void DoSomething()
    {
        Console.WriteLine(foo.ToLower());
    }
}

phpMyAdmin - Error > Incorrect format parameter?

Note: If you're using MAMP you MUST edit the file using the built-in editor.

Select PHP in the languages section (LH Menu Column) Next, in the main panel next to the default version drop-down click the small arrow pointing to the right. This will launch the php.ini file using the MAMP text editor. Any changes you make to this file will persist after you restart the servers.

Editing the file through Application->MAMP->bin->php->{choosen the version}->php.ini would not work. Since the application overwrites any changes you make.

Needless to say: "Here be dragons!" so please cut and paste a copy of the original and store it somewhere safe in case of disaster.enter image description here

Converting a JS object to an array using jQuery

If you know the maximum index in you object you can do the following:

_x000D_
_x000D_
var myObj = {_x000D_
    1: ['c', 'd'],_x000D_
    2: ['a', 'b']_x000D_
  },_x000D_
  myArr;_x000D_
_x000D_
myObj.length = 3; //max index + 1_x000D_
myArr = Array.prototype.slice.apply(myObj);_x000D_
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
_x000D_
_x000D_
_x000D_

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

Injecting $scope into an angular service function()

Got into the same predicament. I ended up with the following. So here I am not injecting the scope object into the factory, but setting the $scope in the controller itself using the concept of promise returned by $http service.

(function () {
    getDataFactory = function ($http)
    {
        return {
            callWebApi: function (reqData)
            {
                var dataTemp = {
                    Page: 1, Take: 10,
                    PropName: 'Id', SortOrder: 'Asc'
                };

                return $http({
                    method: 'GET',
                    url: '/api/PatientCategoryApi/PatCat',
                    params: dataTemp, // Parameters to pass to external service
                    headers: { 'Content-Type': 'application/Json' }
                })                
            }
        }
    }
    patientCategoryController = function ($scope, getDataFactory) {
        alert('Hare');
        var promise = getDataFactory.callWebApi('someDataToPass');
        promise.then(
            function successCallback(response) {
                alert(JSON.stringify(response.data));
                // Set this response data to scope to use it in UI
                $scope.gridOptions.data = response.data.Collection;
            }, function errorCallback(response) {
                alert('Some problem while fetching data!!');
            });
    }
    patientCategoryController.$inject = ['$scope', 'getDataFactory'];
    getDataFactory.$inject = ['$http'];
    angular.module('demoApp', []);
    angular.module('demoApp').controller('patientCategoryController', patientCategoryController);
    angular.module('demoApp').factory('getDataFactory', getDataFactory);    
}());

jQuery.click() vs onClick

From what I understand, your question is not really about whether to use jQuery or not. It's rather: Is it better to bind events inline in HTML or through event listeners?

Inline binding is deprecated. Moreover this way you can only bind one function to a certain event.

Therefore I recommend using event listeners. This way, you'll be able to bind many functions to a single event and to unbind them later if needed. Consider this pure JavaScript code:

querySelector('#myDiv').addEventListener('click', function () {
    // Some code...
});

This works in most modern browsers.

However, if you already include jQuery in your project — just use jQuery: .on or .click function.

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

Program to find largest and second largest number in array

Find your second largest number without using any String function:

int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
    printf("Array is too small");
    return;
}

firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
    //Largest number check
    if (array[index] > first)
    {
        secondLargest = firstLargest;
        firstLargest = array[index];
    }

    //It may not larger than first but can be larger than second number
    else if (array[index] > secondLargest && array[index] != firstLargest)
{
        secondLargest = array[index];
}

//Finally you got your answer
if (secondLargest == minNumber)
{
    printf("No Second largest number");
}
else
{
    printf("Second Largest Number is %d", secondLargest);
}

What is token-based authentication?

A token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

Source (Web Archive)

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I used Mosh's solution, but it was not obvious to me how to implement the composition key correctly in code first.

So here is the solution:

public class Holiday
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int HolidayId { get; set; }
    [Key, Column(Order = 1), ForeignKey("Location")]
    public LocationEnum LocationId { get; set; }

    public virtual Location Location { get; set; }

    public DateTime Date { get; set; }
    public string Name { get; set; }
}

Is there a code obfuscator for PHP?

People will offer you obfuscators, but no amount of obfuscation can prevent someone from getting at your code. None. If your computer can run it, or in the case of movies and music if it can play it, the user can get at it. Even compiling it to machine code just makes the job a little more difficult. If you use an obfuscator, you are just fooling yourself. Worse, you're also disallowing your users from fixing bugs or making modifications.

Music and movie companies haven't quite come to terms with this yet, they still spend millions on DRM.

In interpreted languages like PHP and Perl it's trivial. Perl used to have lots of code obfuscators, then we realized you can trivially decompile them.

perl -MO=Deparse some_program

PHP has things like DeZender and Show My Code.

My advice? Write a license and get a lawyer. The only other option is to not give out the code and instead run a hosted service.

See also the perlfaq entry on the subject.

Arrow operator (->) usage in C

foo->bar is only shorthand for (*foo).bar. That's all there is to it.

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

Java: how do I initialize an array size if it's unknown?

String line=sc.nextLine();
    int counter=1;
    for(int i=0;i<line.length();i++) {
        if(line.charAt(i)==' ') {
            counter++;
        }
    }
    long[] numbers=new long[counter];
    counter=0;
    for(int i=0;i<line.length();i++){
        int j=i;
        while(true) {
            if(j>=line.length() || line.charAt(j)==' ') {
                break;
            }
            j++;
        }
        numbers[counter]=Integer.parseInt(line.substring(i,j));
        i=j;
        counter++;  
    }
    for(int i=0;i<counter;i++) {
        System.out.println(numbers[i]);
    }    

I always use this code for situations like this. beside you can recognize two or three or more digit numbers.

how to fetch data from database in Hibernate

Query query = session.createQuery("from Employee");

Note: from Employee. here Employee is not your table name it's POJO name.

How do I get sed to read from standard input?

use "-e" to specify the sed-expression

cat input.txt | sed -e 's/foo/bar/g'

How to call a Parent Class's method from Child Class in Python?

Python 3 has a different and simpler syntax for calling parent method.

If Foo class inherits from Bar, then from Bar.__init__ can be invoked from Foo via super().__init__():

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

When do you use Java's @Override annotation and why?

I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.

I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.

What is “2's Complement”?

I wonder if it could be explained any better than the Wikipedia article.

The basic problem that you are trying to solve with two's complement representation is the problem of storing negative integers.

First, consider an unsigned integer stored in 4 bits. You can have the following

0000 = 0
0001 = 1
0010 = 2
...
1111 = 15

These are unsigned because there is no indication of whether they are negative or positive.

Sign Magnitude and Excess Notation

To store negative numbers you can try a number of things. First, you can use sign magnitude notation which assigns the first bit as a sign bit to represent +/- and the remaining bits to represent the magnitude. So using 4 bits again and assuming that 1 means - and 0 means + then you have

0000 = +0
0001 = +1
0010 = +2
...
1000 = -0
1001 = -1
1111 = -7

So, you see the problem there? We have positive and negative 0. The bigger problem is adding and subtracting binary numbers. The circuits to add and subtract using sign magnitude will be very complex.

What is

0010
1001 +
----

?

Another system is excess notation. You can store negative numbers, you get rid of the two zeros problem but addition and subtraction remains difficult.

So along comes two's complement. Now you can store positive and negative integers and perform arithmetic with relative ease. There are a number of methods to convert a number into two's complement. Here's one.

Convert Decimal to Two's Complement

  1. Convert the number to binary (ignore the sign for now) e.g. 5 is 0101 and -5 is 0101

  2. If the number is a positive number then you are done. e.g. 5 is 0101 in binary using two's complement notation.

  3. If the number is negative then

    3.1 find the complement (invert 0's and 1's) e.g. -5 is 0101 so finding the complement is 1010

    3.2 Add 1 to the complement 1010 + 1 = 1011. Therefore, -5 in two's complement is 1011.

So, what if you wanted to do 2 + (-3) in binary? 2 + (-3) is -1. What would you have to do if you were using sign magnitude to add these numbers? 0010 + 1101 = ?

Using two's complement consider how easy it would be.

 2  =  0010
 -3 =  1101 +
 -------------
 -1 =  1111

Converting Two's Complement to Decimal

Converting 1111 to decimal:

  1. The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000.

  2. Add 1 to 0000, and we obtain 0001.

  3. Convert 0001 to decimal, which is 1.

  4. Apply the sign = -1.

Tada!

Set background color of WPF Textbox in C# code

If you want to set the background using a hex color you could do this:

var bc = new BrushConverter();

myTextBox.Background = (Brush)bc.ConvertFrom("#FFXXXXXX");

Or you could set up a SolidColorBrush resource in XAML, and then use findResource in the code-behind:

<SolidColorBrush x:Key="BrushFFXXXXXX">#FF8D8A8A</SolidColorBrush>
myTextBox.Background = (Brush)Application.Current.MainWindow.FindResource("BrushFFXXXXXX");

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

As of 27 February 2019, there are CSS fonts for the new Material Icon themes.

However, you have to create CSS classes to use the fonts.

The font families are as follows:

  • Material Icons Outlined - Outlined icons
  • Material Icons Two Tone - Two-tone icons
  • Material Icons Round - Rounded icons
  • Material Icons Sharp - Sharp icons

See the code sample below for an example:

_x000D_
_x000D_
body {_x000D_
  font-family: Roboto, sans-serif;_x000D_
}_x000D_
_x000D_
.material-icons-outlined,_x000D_
.material-icons.material-icons--outlined,_x000D_
.material-icons-two-tone,_x000D_
.material-icons.material-icons--two-tone,_x000D_
.material-icons-round,_x000D_
.material-icons.material-icons--round,_x000D_
.material-icons-sharp,_x000D_
.material-icons.material-icons--sharp {_x000D_
  font-weight: normal;_x000D_
  font-style: normal;_x000D_
  font-size: 24px;_x000D_
  line-height: 1;_x000D_
  letter-spacing: normal;_x000D_
  text-transform: none;_x000D_
  display: inline-block;_x000D_
  white-space: nowrap;_x000D_
  word-wrap: normal;_x000D_
  direction: ltr;_x000D_
  -webkit-font-feature-settings: 'liga';_x000D_
  -webkit-font-smoothing: antialiased;_x000D_
}_x000D_
_x000D_
.material-icons-outlined,_x000D_
.material-icons.material-icons--outlined {_x000D_
  font-family: 'Material Icons Outlined';_x000D_
}_x000D_
_x000D_
.material-icons-two-tone,_x000D_
.material-icons.material-icons--two-tone {_x000D_
  font-family: 'Material Icons Two Tone';_x000D_
}_x000D_
_x000D_
.material-icons-round,_x000D_
.material-icons.material-icons--round {_x000D_
  font-family: 'Material Icons Round';_x000D_
}_x000D_
_x000D_
.material-icons-sharp,_x000D_
.material-icons.material-icons--sharp {_x000D_
  font-family: 'Material Icons Sharp';_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <section id="original">_x000D_
    <h2>Baseline</h2>_x000D_
    <i class="material-icons">home</i>_x000D_
    <i class="material-icons">assignment</i>_x000D_
  </section>_x000D_
  <section id="outlined">_x000D_
    <h2>Outlined</h2>_x000D_
    <i class="material-icons-outlined">home</i>_x000D_
    <i class="material-icons material-icons--outlined">assignment</i>_x000D_
  </section>_x000D_
  <section id="two-tone">_x000D_
    <h2>Two tone</h2>_x000D_
    <i class="material-icons-two-tone">home</i>_x000D_
    <i class="material-icons material-icons--two-tone">assignment</i>_x000D_
  </section>_x000D_
  <section id="rounded">_x000D_
    <h2>Rounded</h2>_x000D_
    <i class="material-icons-round">home</i>_x000D_
    <i class="material-icons material-icons--round">assignment</i>_x000D_
  </section>_x000D_
  <section id="sharp">_x000D_
    <h2>Sharp</h2>_x000D_
    <i class="material-icons-sharp">home</i>_x000D_
    <i class="material-icons material-icons--sharp">assignment</i>_x000D_
  </section>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Or view it on Codepen


EDIT: As of 10 March 2019, it appears that there are now classes for the new font icons:

_x000D_
_x000D_
body {_x000D_
  font-family: Roboto, sans-serif;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <section id="original">_x000D_
    <h2>Baseline</h2>_x000D_
    <i class="material-icons">home</i>_x000D_
    <i class="material-icons">assignment</i>_x000D_
  </section>_x000D_
  <section id="outlined">_x000D_
    <h2>Outlined</h2>_x000D_
    <i class="material-icons-outlined">home</i>_x000D_
    <i class="material-icons-outlined">assignment</i>_x000D_
  </section>_x000D_
  <section id="two-tone">_x000D_
    <h2>Two tone</h2>_x000D_
    <i class="material-icons-two-tone">home</i>_x000D_
    <i class="material-icons-two-tone">assignment</i>_x000D_
  </section>_x000D_
  <section id="rounded">_x000D_
    <h2>Rounded</h2>_x000D_
    <i class="material-icons-round">home</i>_x000D_
    <i class="material-icons-round">assignment</i>_x000D_
  </section>_x000D_
  <section id="sharp">_x000D_
    <h2>Sharp</h2>_x000D_
    <i class="material-icons-sharp">home</i>_x000D_
    <i class="material-icons-sharp">assignment</i>_x000D_
  </section>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

EDIT #2: Here's a workaround to tint two-tone icons by using CSS image filters (code adapted from this comment):

_x000D_
_x000D_
body {_x000D_
  font-family: Roboto, sans-serif;_x000D_
}_x000D_
_x000D_
.material-icons-two-tone {_x000D_
  filter: invert(0.5) sepia(1) saturate(10) hue-rotate(180deg);_x000D_
  font-size: 48px;_x000D_
}_x000D_
_x000D_
.material-icons,_x000D_
.material-icons-outlined,_x000D_
.material-icons-round,_x000D_
.material-icons-sharp {_x000D_
  color: #0099ff;_x000D_
  font-size: 48px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <section id="original">_x000D_
    <h2>Baseline</h2>_x000D_
    <i class="material-icons">home</i>_x000D_
    <i class="material-icons">assignment</i>_x000D_
  </section>_x000D_
  <section id="outlined">_x000D_
    <h2>Outlined</h2>_x000D_
    <i class="material-icons-outlined">home</i>_x000D_
    <i class="material-icons-outlined">assignment</i>_x000D_
  </section>_x000D_
  <section id="two-tone">_x000D_
    <h2>Two tone</h2>_x000D_
    <i class="material-icons-two-tone">home</i>_x000D_
    <i class="material-icons-two-tone">assignment</i>_x000D_
  </section>_x000D_
  <section id="rounded">_x000D_
    <h2>Rounded</h2>_x000D_
    <i class="material-icons-round">home</i>_x000D_
    <i class="material-icons-round">assignment</i>_x000D_
  </section>_x000D_
  <section id="sharp">_x000D_
    <h2>Sharp</h2>_x000D_
    <i class="material-icons-sharp">home</i>_x000D_
    <i class="material-icons-sharp">assignment</i>_x000D_
  </section>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Or view it on Codepen

How to determine previous page URL in Angular?

I had some struggle to access the previous url inside a guard.
Without implementing a custom solution, this one is working for me.

public constructor(private readonly router: Router) {
};

public ngOnInit() {
   this.router.getCurrentNavigation().previousNavigation.initialUrl.toString();
}

The initial url will be the previous url page.

JPA 2.0, Criteria API, Subqueries, In Expressions

Below is the pseudo-code for using sub-query using Criteria API.

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class);
Path<Object> path = from.get("compare_field"); // field to map with sub-query
from.fetch("name");
from.fetch("id");
CriteriaQuery<Object> select = criteriaQuery.select(from);

Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class);
Root fromProject = subquery.from(PROJECT.class);
subquery.select(fromProject.get("requiredColumnName")); // field to map with main-query
subquery.where(criteriaBuilder.and(criteriaBuilder.equal("name",name_value),criteriaBuilder.equal("id",id_value)));

select.where(criteriaBuilder.in(path).value(subquery));

TypedQuery<Object> typedQuery = entityManager.createQuery(select);
List<Object> resultList = typedQuery.getResultList();

Also it definitely needs some modification as I have tried to map it according to your query. Here is a link http://www.ibm.com/developerworks/java/library/j-typesafejpa/ which explains concept nicely.

How do I mock a class without an interface?

With MoQ, you can mock concrete classes:

var mocked = new Mock<MyConcreteClass>();

but this allows you to override virtual code (methods and properties).

Python non-greedy regexes

Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of .* -- what about this?

groups = re.search(r"\([^)]*\)", x)

How to pop an alert message box using PHP?

Use jQuery before the php command alert

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

Can I get a patch-compatible output from git-diff?

If you want to use patch you need to remove the a/ b/ prefixes that git uses by default. You can do this with the --no-prefix option (you can also do this with patch's -p option):

git diff --no-prefix [<other git-diff arguments>]

Usually though, it is easier to use straight git diff and then use the output to feed to git apply.

Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash and bundles are easier to manage.

For your use case I think that stash is most appropriate.

# save uncommitted changes
git stash

# do a merge or some other operation
git merge some-branch

# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop

INSERT IF NOT EXISTS ELSE UPDATE?

I believe you want UPSERT.

"INSERT OR REPLACE" without the additional trickery in that answer will reset any fields you don't specify to NULL or other default value. (This behavior of INSERT OR REPLACE is unlike UPDATE; it's exactly like INSERT, because it actually is INSERT; however if what you wanted is UPDATE-if-exists you probably want the UPDATE semantics and will be unpleasantly surprised by the actual result.)

The trickery from the suggested UPSERT implementation is basically to use INSERT OR REPLACE, but specify all fields, using embedded SELECT clauses to retrieve the current value for fields you don't want to change.

How to clear PermGen space Error in tomcat

You have to allocate more space to the PermGenSpace of the tomcat JVM.

This can be done with the JVM argument : -XX:MaxPermSize=128m

By default, the PermGen space is 64M (and it contains all compiled classes, so if you have a lot of jar (classes) in your classpath, you may indeed fill this space).

On a side note, you can monitor the size of the PermGen space with JVisualVM and you can even inspect its content with YourKit Java Profiler

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You can either use the prepareStatement method taking an additional int parameter

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

Move div to new line

I've found that you can move div elements to the next line simply by setting the property Display: block;

On each div.

array filter in python?

How about

set(A).difference(subset_of_A)

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

Best way to convert text files between character sets?

Try iconv Bash function

I've put this into .bashrc:

utf8()
{
    iconv -f ISO-8859-1 -t UTF-8 $1 > $1.tmp
    rm $1
    mv $1.tmp $1
}

..to be able to convert files like so:

utf8 MyClass.java

Eclipse: All my projects disappeared from Project Explorer

if you use the "Task List" view of Eclipse, it will sometimes try to hide files or projects that it thinks are not associated with a given task (i.e. any file that was not opened while you had a certain task selected as the current task). If you want Eclipse to stop hiding files in that case, you can just delete all tasks.

Or you may also restart your eclipse and by just closing the project and then opening it again (from the right mouse click context menu) the files will be restored.

If that doesnt get your projects back then check the "filters option" (Click on right corner of Project Explorer tab and open context menu. Select Filters option from menu) and make sure that your projects type isnt checked.

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

Allow Access-Control-Allow-Origin header using HTML5 fetch API

I know this is an older post, but I found what worked for me to fix this error was using the IP address of my server instead of using the domain name within my fetch request. So for example:

#(original) var request = new Request('https://davidwalsh.name/demo/arsenal.json');
#use IP instead
var request = new Request('https://0.0.0.0/demo/arsenal.json');

fetch(request).then(function(response) {
    // Convert to JSON
    return response.json();
}).then(function(j) {
    // Yay, `j` is a JavaScript object
    console.log(JSON.stringify(j));
}).catch(function(error) {
    console.log('Request failed', error)
});

Looking to understand the iOS UIViewController lifecycle

iOS 10,11 (Swift 3.1,Swift 4.0)

According to UIViewController in UIKit developers,

1. loadView()

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

2. loadViewIfNeeded()

Loads the view controller's view if it has not already been set.

3. viewDidLoad()

Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

4. viewWillAppear(_ animated: Bool)

Called when the view is about to made visible. Default does nothing

5. viewWillLayoutSubviews()

Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

6. viewDidLayoutSubviews()

Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

7. viewDidAppear(_ animated: Bool)

Called when the view has been fully transitioned onto the screen. Default does nothing

8. viewWillDisappear(_ animated: Bool)

Called when the view is dismissed, covered or otherwise hidden. Default does nothing

9. viewDidDisappear(_ animated: Bool)

Called after the view was dismissed, covered or otherwise hidden. Default does nothing

10. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

Called when the view is Transitioning.

11. willMove(toParentViewController parent: UIViewController?)

12. didMove(toParentViewController parent: UIViewController?)

These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super.

The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.

13. didReceiveMemoryWarning()

Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.

How do I compile the asm generated by GCC?

Yes, You can use gcc to compile your asm code. Use -c for compilation like this:

gcc -c file.S -o file.o

This will give object code file named file.o. To invoke linker perform following after above command:

gcc file.o -o file

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Generate C# class from XML

At first I thought the Paste Special was the holy grail! But then I tried it and my hair turned white just like the Indiana Jones movie.

But now I use http://xmltocsharp.azurewebsites.net/ and now I'm as young as ever.

Here's a segment of what it generated:

namespace Xml2CSharp
{
    [XmlRoot(ElementName="entry")]
    public class Entry {
        [XmlElement(ElementName="hybrisEntryID")]
        public string HybrisEntryID { get; set; }
        [XmlElement(ElementName="mapicsLineSequenceNumber")]
        public string MapicsLineSequenceNumber { get; set; }