Programs & Examples On #Mail queue

Best way to run scheduled tasks

You can easily create a Windows Service that runs code on interval using the 'ThreadPool.RegisterWaitForSingleObject' method. It is really slick and quite easy to get set up. This method is a more streamlined approach then to use any of the Timers in the Framework.

Have a look at the link below for more information:

Running a Periodic Process in .NET using a Windows Service:
http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html

Pure CSS to make font-size responsive based on dynamic amount of characters

Note: This solution changes based on viewport size and not the amount of content

I just found out that this is possible using VW units. They're the units associated with setting the viewport width. There are some drawbacks, such as lack of legacy browser support, but this is definitely something to seriously consider using. Plus you can still provide fallbacks for older browsers like so:

p {
    font-size: 30px;
    font-size: 3.5vw;
}

http://css-tricks.com/viewport-sized-typography/ and https://medium.com/design-ux/66bddb327bb1

SQL SERVER DATETIME FORMAT

In MS SQL Server you can do:

SET DATEFORMAT ymd

Find the day of a week

Use the lubridate package and function wday:

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

relative path in BAT script

Use this in your batch file:

%~dp0\bin\Iris.exe

%~dp0 resolves to the full path of the folder in which the batch script resides.

How do I evenly add space between a label and the input field regardless of length of text?

2019 answer:

Some time has passed and I changed my approach now when building forms. I've done thousands of them till today and got really tired of typing id for every label/input pair, so this was flushed down the toilet. When you dive input right into the label, things work the same way, no ids necessary. I also took advantage of flexbox being, well, very flexible.

HTML:

<label>
  Short label <input type="text" name="dummy1" />
</label>

<label>
  Somehow longer label <input type="text" name="dummy2" />
</label>

<label>
  Very long label for testing purposes <input type="text" name="dummy3" />
</label>

CSS:

label {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  text-align: right;
  width: 400px;
  line-height: 26px;
  margin-bottom: 10px;
}

input {
  height: 20px;
  flex: 0 0 200px;
  margin-left: 10px;
}

Fiddle DEMO


Original answer:

Use label instead of span. It's meant to be paired with inputs and preserves some additional functionality (clicking label focuses the input).

This might be exactly what you want:

HTML:

<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">

<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">

<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">

CSS:

label {
    width:180px;
    clear:left;
    text-align:right;
    padding-right:10px;
}

input, label {
    float:left;
}

jsfiddle DEMO here.

How do I import an SQL file using the command line in MySQL?

You can try this query.

Export:

mysqldump -u username –-password=your_password database_name > file.sql

Import:

mysql -u username –-password=your_password database_name < file.sql

and detail following this link:

https://chartio.com/resources/tutorials/importing-from-and-exporting-to-files-using-the-mysql-command-line/

Closing JFrame with button click

It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

How to disable/enable select field using jQuery?

Good question - I think the only way to achieve this is to filter the items in the select.
You can do this through a jquery plugin. Check the following link, it describes how to achieve something similar to what you need. Thanks
jQuery disable SELECT options based on Radio selected (Need support for all browsers)

Changing the child element's CSS when the parent is hovered

To change it from css you dont even need to set the child class

.parent > div:nth-child(1) { display:none; }
.parent:hover > div:nth-child(1) { display: block; }

iOS Detection of Screenshot?

Swift 4 Examples

Example #1 using closure

NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil, 
                                       queue: OperationQueue.main) { notification in
    print("\(notification) that a screenshot was taken!")
}

Example #2 with selector

NotificationCenter.default.addObserver(self, 
                                       selector: #selector(screenshotTaken), 
                                       name: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil)

@objc func screenshotTaken() {
    print("Screenshot taken!")
}

How do you update a DateTime field in T-SQL?

When in doubt, be explicit about the data type conversion using CAST/CONVERT:

UPDATE TABLE
   SET EndDate = CAST('2009-05-25' AS DATETIME)
 WHERE Id = 1

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) - meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

How can I get a favicon to show up in my django app?

One lightweight trick is to make a redirect in your urls.py file, e.g. add a view like so:

from django.views.generic.base import RedirectView

favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)

urlpatterns = [
    ...
    re_path(r'^favicon\.ico$', favicon_view),
    ...
]

This works well as an easy trick for getting favicons working when you don't really have other static content to host.

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

How to hide a mobile browser's address bar?

In my case problem was in css and html layout. Layout was something like html - body - root - ... html and body was overflow: hidden, and root was position: fixed, height: 100vh.

Whith this layout browser tabs on mobile doesnt hide. For solve this I delete overflow: hidden from html and body and delete position: fixed, height: 100vh from root.

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

How to obtain image size using standard Python class (without using external library)?

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info

Output:

foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

Flask - Calling python function on button OnClick event

index.html (index.html should be in templates folder)

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
    function(data) { }); return false; }); }); </script> 
</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
</body>    

</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SomeFunction')
def SomeFunction():
    print('In SomeFunction')
    return "Nothing"



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

Check whether a variable is a string in Ruby

In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.

  • o.class class of o.
  • o.instance_of? c determines whether o.class == c
  • o.is_a? c Is o an instance of c or any of it's subclasses?
  • o.kind_of? c synonym for *is_a?*
  • c === o for a class or module, determine if *o.is_a? c* (String === "s" returns true)

Displaying Image in Java

Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?

sql ORDER BY multiple values in specific order?

@bobflux's answer is great. I would like to extend it by adding a complete query that uses proposed approach.

select tt.id, tt.x_field
from target_table as tt
-- Here we join our target_table with order_table to specify custom ordering.
left join
    (values ('f', 1), ('p', 2), ('i', 3), ('a', 4)) as order_table (x_field, order_num)
    on order_table.x_field = tt.x_field
order by
    order_table.order_num, -- Here we order values by our custom order.
    tt.x_field;            -- Other values can be ordered alphabetically, for example.

Here is complete demo.

How to set up a cron job to run an executable every hour?

Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH

What's the simplest way to list conflicted files in Git?

git diff --name-only --diff-filter=U

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You could run jconsole (included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.

Assembly code vs Machine code vs Object code?

Machine code is binary (1's and 0's) code that can be executed directly by the CPU. If you open a machine code file in a text editor you would see garbage, including unprintable characters (no, not those unprintable characters ;) ).

Object code is a portion of machine code not yet linked into a complete program. It's the machine code for one particular library or module that will make up the completed product. It may also contain placeholders or offsets not found in the machine code of a completed program. The linker will use these placeholders and offsets to connect everything together.

Assembly code is plain-text and (somewhat) human read-able source code that mostly has a direct 1:1 analog with machine instructions. This is accomplished using mnemonics for the actual instructions, registers, or other resources. Examples include JMP and MULT for the CPU's jump and multiplication instructions. Unlike machine code, the CPU does not understand assembly code. You convert assembly code to machine code with the use of an assembler or a compiler, though we usually think of compilers in association with high-level programming language that are abstracted further from the CPU instructions.


Building a complete program involves writing source code for the program in either assembly or a higher level language like C++. The source code is assembled (for assembly code) or compiled (for higher level languages) to object code, and individual modules are linked together to become the machine code for the final program. In the case of very simple programs the linking step may not be needed. In other cases, such as with an IDE (integrated development environment) the linker and compiler may be invoked together. In other cases, a complicated make script or solution file may be used to tell the environment how to build the final application.

There are also interpreted languages that behave differently. Interpreted languages rely on the machine code of a special interpreter program. At the basic level, an interpreter parses the source code and immediately converts the commands to new machine code and executes them. Modern interpreters are now much more complicated: evaluating whole sections of source code at a time, caching and optimizing where possible, and handling complex memory management tasks.

One final type of program involves the use of a runtime-environment or virtual machine. In this situation, a program is first pre-compiled to a lower-level intermediate language or byte code. The byte code is then loaded by the virtual machine, which just-in-time compiles it to native code. The advantage here is the virtual machine can take advantage of optimizations available at the time the program runs and for that specific environment. A compiler belongs to the developer, and therefore must produce relatively generic (less-optimized) machine code that could run in many places. The runtime environment or virtual machine, however, is located on the end user's computer and therefore can take advantage of all the features provided by that system.

How to extract the substring between two markers?

Just in case somebody will have to do the same thing that I did. I had to extract everything inside parenthesis in a line. For example, if I have a line like 'US president (Barack Obama) met with ...' and I want to get only 'Barack Obama' this is solution:

regex = '.*\((.*?)\).*'
matches = re.search(regex, line)
line = matches.group(1) + '\n'

I.e. you need to block parenthesis with slash \ sign. Though it is a problem about more regular expressions that Python.

Also, in some cases you may see 'r' symbols before regex definition. If there is no r prefix, you need to use escape characters like in C. Here is more discussion on that.

How to use Bootstrap in an Angular project?

In an angular-cli environment, the most straightforward way I've found is the following:


1. Solution in an environment with s_c_s_s_ stylesheets

npm install bootstrap-sass —save

In style.scss:

$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

Note1: The ~ character is a reference to nodes_modules folder.
Note2: As we are using scss, we can customize all boostrap variables we want.


2. Solution in an environment with c_s_s_ stylesheets

npm install bootstrap —save

In style.css:

@import '~bootstrap/dist/css/bootstrap.css';

How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP

How to generate classes from wsdl using Maven and wsimport?

i was having the same issue while generating the classes from wsimport goal. Instead of using jaxws:wsimport goal in eclipse Maven Build i was using clean compile install that was not able to generate code from wsdl file. Thanks to above example. Run jaxws:wsimport goal from Eclipse ide and it will work

No space left on device

To list processes holding deleted files a linux system which has no lsof, here's my trick:

    pushd /proc ; for i in [1-9]* ; do ls -l $i/fd | grep "(deleted)" && (echo -n "used by: " ; ps -p $i | grep -v PID ; echo ) ; done ; popd

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

How to initialize an array's length in JavaScript?

[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]

OR

Array(6).fill(0);
// [0, 0, 0, 0, 0, 0]

Note: you can't loop empty slots i.e. Array(4).forEach(() => …)


OR

( typescript safe )

Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]

OR

Classic method using a function ( works in any browser )

function NewArray(size) {
    var x = [];
    for (var i = 0; i < size; ++i) {
        x[i] = i;
    }
    return x;
}

var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating nested arrays

When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.

var a = Array(3).fill([6]);
// [  [6], [6], [6]  ]

a[0].push(9);
// [  [6, 9], [6, 9], [6, 9]  ]

Solution

var a = [...Array(3)].map(x => []);

a[0].push(4, 2);
// [  [4, 2], [], []  ]

So a 3x2 Array will look something like this:

[...Array(3)].map(x => Array(2).fill(0));
// [  [0, 0], [0, 0], [0, 0]  ]

N-dimensional array

function NArray(...dimensions) {
    var index = 0;
    function NArrayRec(dims) {
        var first = dims[0], next = dims.slice().splice(1); 
        if(dims.length > 1) 
            return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
        return Array(dims[0]).fill(null).map((x, i) => (index++));
    }
    return NArrayRec(dimensions);
}

var arr = NArray(3, 2, 4);
// [   [  [ 0,  1,  2,  3 ] , [  4,  5,  6,  7]  ],
//     [  [ 8,  9,  10, 11] , [ 12, 13, 14, 15]  ],
//     [  [ 16, 17, 18, 19] , [ 20, 21, 22, 23]  ]   ]

Initialize a chessboard

var Chessboard = [...Array(8)].map((x, j) => {
    return Array(8).fill(null).map((y, i) => {
        return `${String.fromCharCode(65 + i)}${8 - j}`;
    });
});

// [ [A8, B8, C8, D8, E8, F8, G8, H8],
//   [A7, B7, C7, D7, E7, F7, G7, H7],
//   [A6, B6, C6, D6, E6, F6, G6, H6],
//   [A5, B5, C5, D5, E5, F5, G5, H5],
//   [A4, B4, C4, D4, E4, F4, G4, H4],
//   [A3, B3, C3, D3, E3, F3, G3, H3],
//   [A2, B2, C2, D2, E2, F2, G2, H2],
//   [A1, B1, C1, D1, E1, F1, G1, H1] ]

Math filled values

handy little method overload when working with math


function NewArray( size , method, linear )
{
    method = method || ( i => i ); 
    linear = linear || false;
    var x = [];
    for( var i = 0; i < size; ++i )
        x[ i ] = method( linear ? i / (size-1) : i );
    return x;
}

NewArray( 4 ); 
// [ 0, 1, 2, 3 ]

NewArray( 4, Math.sin ); 
// [ 0, 0.841, 0.909, 0.141 ]

NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]

var pow2 = ( x ) => x * x;

NewArray( 4, pow2 ); 
// [ 0, 1, 4, 9 ]

NewArray( 4, pow2, true ); 
// [ 0, 0.111, 0.444, 1 ]

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Pandas: Return Hour from Datetime Column Directly

You can use a lambda expression, e.g:

sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)

Can a foreign key refer to a primary key in the same table?

I think the question is a bit confusing.

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.

If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!

create table t1(c1 int not null primary key foreign key references t1(c1))

But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.

AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.

Export DataTable to Excel with Open Xml SDK in c#

I also wrote a C#/VB.Net "Export to Excel" library, which uses OpenXML and (more importantly) also uses OpenXmlWriter, so you won't run out of memory when writing large files.

Full source code, and a demo, can be downloaded here:

Export to Excel

It's dead easy to use. Just pass it the filename you want to write to, and a DataTable, DataSet or List<>.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

And if you're calling it from an ASP.Net application, pass it the HttpResponse to write the file out to.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

Java, How to get number of messages in a topic in apache kafka

The only way that comes to mind for this from a consumer point of view is to actually consume the messages and count them then.

The Kafka broker exposes JMX counters for number of messages received since start-up but you cannot know how many of them have been purged already.

In most common scenarios, messages in Kafka is best seen as an infinite stream and getting a discrete value of how many that is currently being kept on disk is not relevant. Furthermore things get more complicated when dealing with a cluster of brokers which all have a subset of the messages in a topic.

Error:java: javacTask: source release 8 requires target release 1.8

I've just spent a while struggling with the same problem. The only thing that worked for me was not using the built mvn (3.3.9) but pointing it to an external downloaded version (3.5.0). Finally the project opened and everything was good.

How to remove specific object from ArrayList in Java?

use this code

test.remove(test.indexOf(obj));

test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.

Store output of subprocess.Popen call in a string

Use check_output method of subprocess module

import subprocess

address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])

Finally parse the string

for line in res.splitlines():

Hope it helps, happy coding

Can I have multiple primary keys in a single table?

Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.

CREATE t1(
c1 int NOT NULL,
c2 int NOT NULL UNIQUE,
...,
PRIMARY KEY (c1)
);

However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict.

How to create a GUID in Excel?

The formula for Polish version:

=ZLACZ.TEKSTY(
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4);"-";
    DZIES.NA.SZESN(LOS.ZAKR(0;4294967295);8);
    DZIES.NA.SZESN(LOS.ZAKR(0;42949);4)
)

How to clear a textbox once a button is clicked in WPF?

You wouldn't have to put it in the button click hander. If you were, then you'd assign your text box a name (x:Name) in your view and then use the generated member of the same name in the code behind to set the Text property.

If you were avoiding code behind, then you would investigate the MVVM design pattern and data binding, and bind a property on your view model to the text box's Text property.

Jquery select change not firing

Try

 $(document).on('change','#multiid',function(){
    alert('Change Happened');
});

As your select-box is generated from the code, so you have to use event delegation, where in place of $(document) you can have closest parent element.

Or

$(document.body).on('change','#multiid',function(){
    alert('Change Happened');
});

Update:

Second one works fine, there is another change of selector to make it work.

$('#addbasket').on('change','#multiid',function(){
    alert('Change Happened');
});

Ideally we should use $("#addbasket") as it's the closest parent element [As i have mentioned above].

psql: FATAL: Peer authentication failed for user "dev"

While @flaviodesousa's answer would work, it also makes it mandatory for all users (everyone else) to enter a password.

Sometime it makes sense to keep peer authentication for everyone else, but make an exception for a service user. In that case you would want to add a line to the pg_hba.conf that looks like:

local   all             some_batch_user                         md5

I would recommend that you add this line right below the commented header line:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             some_batch_user                         md5

You will need to restart PostgreSQL using

sudo service postgresql restart

If you're using 9.3, your pg_hba.conf would most likely be:

/etc/postgresql/9.3/main/pg_hba.conf

'React' must be in scope when using JSX react/react-in-jsx-scope?

This is an error caused by importing the wrong module react from 'react' how about you try this: 1st

import React , { Component}  from 'react';

2nd Or you can try this as well:

import React from 'react';
import { render   }  from 'react-dom';

class TechView extends React.Component {

    constructor(props){
       super(props);
       this.state = {
           name:'Gopinath',
       }
    }
    render(){
        return(
            <span>hello Tech View</span>
        );
    }
}

export default TechView;

Java Multiple Inheritance

May I suggest the concept of Duck-typing?

Most likely you would tend to make the Pegasus extend a Bird and a Horse interface but duck typing actually suggests that you should rather inherit behaviour. As already stated in the comments, a pegasus is not a bird but it can fly. So your Pegasus should rather inherit a Flyable-interface and lets say a Gallopable-interface.

This kind of concept is utilized in the Strategy Pattern. The given example actually shows you how a duck inherits the FlyBehaviour and QuackBehaviour and still there can be ducks, e.g. the RubberDuck, which can't fly. They could have also made the Duck extend a Bird-class but then they would have given up some flexibility, because every Duck would be able to fly, even the poor RubberDuck.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

First of all: I'm the author of the The Single Page Interface Manifesto cited by raganwald

As raganwald has explained very well, the most important aspect of the Single Page Interface (SPI) approach used in FaceBook and Twitter is the use of hash # in URLs

The character ! is added only for Google purposes, this notation is a Google "standard" for crawling web sites intensive on AJAX (in the extreme Single Page Interface web sites). When Google's crawler finds an URL with #! it knows that an alternative conventional URL exists providing the same page "state" but in this case on load time.

In spite of #! combination is very interesting for SEO, is only supported by Google (as far I know), with some JavaScript tricks you can build SPI web sites SEO compatible for any web crawler (Yahoo, Bing...).

The SPI Manifesto and demos do not use Google's format of ! in hashes, this notation could be easily added and SPI crawling could be even easier (UPDATE: now ! notation is used and remains compatible with other search engines).

Take a look to this tutorial, is an example of a simple ItsNat SPI site but you can pick some ideas for other frameworks, this example is SEO compatible for any web crawler.

The hard problem is to generate any (or selected) "AJAX page state" as plain HTML for SEO, in ItsNat is very easy and automatic, the same site is in the same time SPI or page based for SEO (or when JavaScript is disabled for accessibility). With other web frameworks you can ever follow the double site approach, one site is SPI based and another page based for SEO, for instance Twitter uses this "double site" technique.

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Close a div by clicking outside

 //for closeing the popover when user click outside it will close all popover 
 var hidePopover = function(element) {
        var elementScope = angular.element($(element).siblings('.popover')).scope().$parent;
        elementScope.isOpen = false;
        elementScope.$apply();
        //Remove the popover element from the DOM
        $(element).siblings('.popover').remove();
    };
 $(document).ready(function(){
 $('body').on('click', function (e) {
       $("a").each(function () {
                    //Only do this for all popovers other than the current one that cause this event
           if (!($(this).is(e.target) || $(this).has(e.target).length > 0) 
                && $(this).siblings('.popover').length !== 0 && $(this).siblings('.popover').has(e.target).length === 0)                  
                    {
                         hidePopover(this);
                    }
        });
    });
 });

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.

If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.

Find what 2 numbers add to something and multiply to something

With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:

$factors = array();
for($i = 0; $i < $target; $i++){
    if($target % $i == 0){
        $temp = array()
        $a = $i;
        $b = $target / $i;
        $temp["a"] = $a;
        $temp["b"] = $b;
        $temp["index"] = $i;
        array_push($factors, $temp);
    }
}

This would leave you with an array of factors of the target number.

'nuget' is not recognized but other nuget commands working

Nuget.exe is placed at .nuget folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.

My steps to solve are:


Update

NuGet can be easily installed in your project using the following command:

Install-Package NuGet.CommandLine

Facebook Graph API, how to get users email?

Open base_facebook.php Add Access_token at function getLoginUrl()

array_merge(array(
                  'access_token' => $this->getAccessToken(),
                  'client_id' => $this->getAppId(),
                  'redirect_uri' => $currentUrl, // possibly overwritten
                  'state' => $this->state),
             $params);

and Use scope for Email Permission

if ($user) {
   echo $logoutUrl = $facebook->getLogoutUrl();
} else {
   echo $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
}

Python: Assign Value if None Exists

One-liner solution here:

var1 = locals().get("var1", "default value")

Instead of having NameError, this solution will set var1 to default value if var1 hasn't been defined yet.

Here's how it looks like in Python interactive shell:

>>> var1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
>>> var1 = locals().get("var1", "default value 1")
>>> var1
'default value 1'
>>> var1 = locals().get("var1", "default value 2")
>>> var1
'default value 1'
>>>

How to cancel a local git commit

Use below command:

$ git reset HEAD~1

After this you also able to view files what revert back like below response.

Unstaged changes after reset:
M   application/config/config.php
M   application/config/database.php

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

How does one generate a random number in Apple's Swift language?

Example for random number in between 10 (0-9);

import UIKit

let randomNumber = Int(arc4random_uniform(10))

Very easy code - simple and short.

How to import set of icons into Android Studio project

what u need to do is icons downloaded from material design, open that folder there are lots of icons categories specified, open any of it choose any icon and go to this folder -> drawable-anydpi-v21. this folder contains xml files copy any xml file and paste it to this location -> C:\Users\Username\AndroidStudioProjects\ur project name\app\src\main\res\drawable. That's it !! now you can use the icon in ur project.

Modifying list while iterating

Use a while loop that checks for the truthfulness of the array:

while array:
    value = array.pop(0)
    # do some calculation here

And it should do it without any errors or funny behaviour.

How to read line by line of a text area HTML tag

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

HTML5 Video Autoplay not working correctly

<video width="1000px" loop="true" autoplay="autoplay" controls muted></video> worked for me

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Do you mean like:

$val1 = rand( 1, 10 ); // gives one integer between 1 and 10
$val2 = rand( 20, 40 ) ; // gives one integer between 20 and 40

or perhaps:

$range = range( 1, 10 ); // gives array( 1, 2, ..., 10 );
$range2 = range( 20, 40 ); // gives array( 20, 21, ..., 40 );

or maybe:

$truth1 = $val >= 1 && $val <= 10; // true if 1 <= x <= 10
$truth2 = $val >= 20 && $val <= 40; // true if 20 <= x <= 40

suppose you wanted:

$in_range = ( $val > 1 && $val < 10 ) || ( $val > 20 && $val < 40 ); // true if 1 < x < 10 OR 20 < x < 40

What does '&' do in a C++ declaration?

One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

void foo(int &x)
{
    x = x + 1;
}

void foo(int *x)
{
    *x = *x + 1;
}

The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

What is IPV6 for localhost and 0.0.0.0?

Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).

Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr (which will be converted to http://[::ffff:7f00:1]:19983/solr)

C++ deprecated conversion from string constant to 'char*'

The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):

#include <iostream>

void Swap(const char * & left, const char * & right) {
    const char *const temp = left;
    left = right;
    right = temp;
}

int main() {
    const char * x = "Hello"; // These works because you are making a variable
    const char * y = "World"; // pointer to a constant string
    std::cout << "x = " << x << ", y = " << y << '\n';
    Swap(x, y);
    std::cout << "x = " << x << ", y = " << y << '\n';
}

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Javascript Append Child AFTER Element

after is now a JavaScript method

MDN Documentation

Quoting MDN

The ChildNode.after() method inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes.

The browser support is Chrome(54+), Firefox(49+) and Opera(39+). It doesn't support IE and Edge.

Snippet

_x000D_
_x000D_
var elm=document.getElementById('div1');
var elm1 = document.createElement('p');
var elm2 = elm1.cloneNode();
elm.append(elm1,elm2);

//added 2 paragraphs
elm1.after("This is sample text");
//added a text content
elm1.after(document.createElement("span"));
//added an element
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

In the snippet, I used another term append too

How can I check if string contains characters & whitespace, not just whitespace?

if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

"Untrusted App Developer" message when installing enterprise iOS Application

This issue comes when trust verification of app fails.

Screenshot 1

You can trust app from Settings shown in below images.

Screenshot 2

Screenshot 3

Screenshot 4

If this dosen't work then delete app and re-install it.

How do I rename a local Git branch?

Rename the branch using this command:

git branch -m [old_branch_name] [new_branch_name]

-m: It renames/moves the branch. If there is already a branch, you will get an error.

If there is already a branch and you want to rename with that branch, use:

 git rename -M [old_branch_name] [new_branch_name]

For more information about help, use this command in the terminal:

git branch --help

or

man git branch

Modify SVG fill color when being served as Background-Image

Download your svg as text.

Modify your svg text using javascript to change the paint/stroke/fill color[s].

Then embed the modified svg string inline into your css as described here.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I was facing this issue in ionic and tried many solutions but solved this by running this.

For MAC: node --max-old-space-size=4096 /usr/local/bin/ionic cordova build android --prod

For Windows: node --max-old-space-size=4096 /Users/{your user}/AppData/Roaming/npm/node_modules/ionic/bin/ionic cordova build windows --prod

An efficient way to transpose a file in Bash

A hackish perl solution can be like this. It's nice because it doesn't load all the file in memory, prints intermediate temp files, and then uses the all-wonderful paste

#!/usr/bin/perl
use warnings;
use strict;

my $counter;
open INPUT, "<$ARGV[0]" or die ("Unable to open input file!");
while (my $line = <INPUT>) {
    chomp $line;
    my @array = split ("\t",$line);
    open OUTPUT, ">temp$." or die ("unable to open output file!");
    print OUTPUT join ("\n",@array);
    close OUTPUT;
    $counter=$.;
}
close INPUT;

# paste files together
my $execute = "paste ";
foreach (1..$counter) {
    $execute.="temp$counter ";
}
$execute.="> $ARGV[1]";
system $execute;

How many bytes does one Unicode character take?

Strangely enough, nobody pointed out how to calculate how many bytes is taking one Unicode char. Here is the rule for UTF-8 encoded strings:

Binary    Hex          Comments
0xxxxxxx  0x00..0x7F   Only byte of a 1-byte character encoding
10xxxxxx  0x80..0xBF   Continuation byte: one of 1-3 bytes following the first
110xxxxx  0xC0..0xDF   First byte of a 2-byte character encoding
1110xxxx  0xE0..0xEF   First byte of a 3-byte character encoding
11110xxx  0xF0..0xF7   First byte of a 4-byte character encoding

So the quick answer is: it takes 1 to 4 bytes, depending on the first one which will indicate how many bytes it'll take up.

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

How to position a div in the middle of the screen when the page is bigger than the screen

Well, below is the working example for this.

This will handle the center position if you resize the webpage or load in anysize.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
.loader {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-top: -50px;_x000D_
  margin-left: -50px;_x000D_
  border: 10px solid #dcdcdc;_x000D_
  border-radius: 50%;_x000D_
  border-top: 10px solid #3498db;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
  animation: spin 1s linear infinite;  _x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin {_x000D_
  0% { -webkit-transform: rotate(0deg); }_x000D_
  100% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0% { transform: rotate(0deg); }_x000D_
  100% { transform: rotate(360deg); }_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
_x000D_
<div class="loader" style="display:block"></div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

In above sample loading div will always be in center.

Hoping this will help you :)

Linux shell script for database backup

#!/bin/bash

# Add your backup dir location, password, mysql location and mysqldump        location
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/var/www/back"
MYSQL_USER="root"
MYSQL_PASSWORD=""
MYSQL='/usr/bin/mysql'
MYSQLDUMP='/usr/bin/mysqldump'
DB='demo'

#to empty the backup directory and delete all previous backups
rm -r $BACKUP_DIR/*  

mysqldump -u root -p'' demo | gzip -9 > $BACKUP_DIR/demo$date_format.sql.$DATE.gz

#changing permissions of directory 
chmod -R 777 $BACKUP_DIR

How do you set EditText to only accept numeric values in Android?

the simplest for me

android:numeric="integer" 

although this also more customize

android:digits="0123456789"

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

Edit

gulp-util is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util already used.

So I've changed some lines in my gulpfile to remove gulp-util:

var argv = require('minimist')(process.argv.slice(2));

gulp.task('styles', function() {
  return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss'])
    …
});

Original

In my project I use the following flag:

gulp styles --theme literature

Gulp offers an object gulp.env for that. It's deprecated in newer versions, so you must use gulp-util for that. The tasks looks like this:

var util = require('gulp-util');

gulp.task('styles', function() {
  return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss'])
    .pipe(compass({
        config_file: './config.rb',
        sass   : 'src/styles',
        css    : 'dist/styles',
        style  : 'expanded'

    }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(livereload(server))
    .pipe(gulp.dest('dist/styles'))
    .pipe(notify({ message: 'Styles task complete' }));
});

The environment setting is available during all subtasks. So I can use this flag on the watch task too:

gulp watch --theme literature

And my styles task also works.

Ciao Ralf

Django datetime issues (default=datetime.now())

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

UTF-8 problems while reading CSV file with fgetcsv

Try putting this into the top of your file (before any other output):

<?php

header('Content-Type: text/html; charset=UTF-8');

?>

jQuery selector for inputs with square brackets in the name attribute

You can use backslash to quote "funny" characters in your jQuery selectors:

$('#input\\[23\\]')

For attribute values, you can use quotes:

$('input[name="weirdName[23]"]')

Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?

edit fixed bogosity; thanks @Dancrumb

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

How do I convert a string to a number in PHP?

Late to the party, but here is another approach:

function cast_to_number($input) {
    if(is_float($input) || is_int($input)) {
        return $input;
    }
    if(!is_string($input)) {
        return false;
    }
    if(preg_match('/^-?\d+$/', $input)) {
        return intval($input);
    }
    if(preg_match('/^-?\d+\.\d+$/', $input)) {
        return floatval($input);
    }
    return false;
}

cast_to_number('123.45');       // (float) 123.45
cast_to_number('-123.45');      // (float) -123.45
cast_to_number('123');          // (int) 123
cast_to_number('-123');         // (int) -123
cast_to_number('foo 123 bar');  // false

Cast to generic type in C#

As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.

Regex to match 2 digits, optional decimal, two digits

EDIT: Changed to fit other feedback.

I understood you to mean that if there is no decimal point, then there shouldn't be two more digits. So this should be it:

\d{0,2}(\.\d{1,2})?

That should do the trick in most implementations. If not, you can use:

[0-9]?[0-9]?(\.[0-9][0-9]?)?

And that should work on every implementation I've seen.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Start Eclipse with the option -Dosgi.locking=none.

I got the trick here and it works.

Don't do this unless you know nobody can work on the same file at the same time.

What does "exited with code 9009" mean during this build?

I caused this error to happen when I redacted my Path environment variable. After editing, I accidentally added Path= to the beginning of the path string. With such a malformed path variable, I was unable to run XCopy at the command line (no command or file not found), and Visual Studio refused to run post-build step, citing error with code 9009.

XCopy commonly resides in C:\Windows\System32. Once the Path environment variable allowed XCopy to get resolved at DOS prompt, Visual Studio built my solution well.

Getting the number of filled cells in a column (VBA)

One way is to: (Assumes index column begins at A1)

MsgBox Range("A1").End(xlDown).Row

Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.

You can select the next empty cell with:

Range("A1").End(xlDown).Offset(1, 0).Select

If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row

How to determine whether code is running in DEBUG / RELEASE build?

Check your project's build settings under 'Apple LLVM - Preprocessing', 'Preprocessor Macros' for debug to ensure that DEBUG is being set - do this by selecting the project and clicking on the build settings tab. Search for DEBUG and look to see if indeed DEBUG is being set.

Pay attention though. You may see DEBUG changed to another variable name such as DEBUG_MODE.

Build Settings tab of my project settings

then conditionally code for DEBUG in your source files

#ifdef DEBUG

// Something to log your sensitive data here

#else

// 

#endif

How to replace DOM element in place using Javascript?

by using replaceChild():

<html>
<head>
</head>
<body>
  <div>
    <a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
  </div>
<script type="text/JavaScript">
  var myAnchor = document.getElementById("myAnchor");
  var mySpan = document.createElement("span");
  mySpan.innerHTML = "replaced anchor!";
  myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>

Is JavaScript object-oriented?

I think a lot of people answer this question "no" because JavaScript does not implement classes, in the traditional OO sense. Unfortunately (IMHO), that is coming in ECMAScript 4. Until then, viva la prototype! :-)

Checking if a double (or float) is NaN in C++

As for me the solution could be a macro to make it explicitly inline and thus fast enough. It also works for any float type. It bases on the fact that the only case when a value is not equals itself is when the value is not a number.

#ifndef isnan
  #define isnan(a) (a != a)
#endif

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.

Typing SET /? explains the thing reasonably well:

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "%VAR%" == "after" @echo If you see this, it worked
)

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:

set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked
)

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

Another example is this batch file:

@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
 set b=%%a
 echo !b:1=2!
)

This prints x2 and y2: every 1 gets replaced by a 2.

Without setlocal enabledelayedexpansion, exclamation marks are just that, so it will echo !b:1=2! twice.

Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2% uses the value b has before the loop: z2 (but y2 when not set).

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

How to create a sticky footer that plays well with Bootstrap 3

For those who are searching for a light answer, you can get a simple working example from here:

html {
    position: relative;
    min-height: 100%;
}
body {
    margin-bottom: 60px /* Height of the footer */
}
footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px /* Example value */
}

Just play with the body's margin-bottom for adding space between the content and footer.

html select scroll bar

Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:

1. First create a css class

<style type="text/css">
 .scrollable{
   overflow: auto;
   width: 70px; /* adjust this width depending to amount of text to display */
   height: 80px; /* adjust height depending on number of options to display */
   border: 1px silver solid;
 }
 .scrollable select{
   border: none;
 }
</style>

2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.

<div class="scrollable">
<select size="6" multiple="multiple">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>
</div>

How can I save application settings in a Windows Forms application?

The ApplicationSettings class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.

You can fight the system with the ConfigurationManager class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.

How to query a CLOB column in Oracle

When getting the substring of a CLOB column and using a query tool that has size/buffer restrictions sometimes you would need to set the BUFFER to a larger size. For example while using SQL Plus use the SET BUFFER 10000 to set it to 10000 as the default is 4000.

Running the DBMS_LOB.substr command you can also specify the amount of characters you want to return and the offset from which. So using DBMS_LOB.substr(column, 3000) might restrict it to a small enough amount for the buffer.

See oracle documentation for more info on the substr command


    DBMS_LOB.SUBSTR (
       lob_loc     IN    CLOB   CHARACTER SET ANY_CS,
       amount      IN    INTEGER := 32767,
       offset      IN    INTEGER := 1)
      RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;

Proper way to initialize a C# dictionary with values?

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

Render Partial View Using jQuery in ASP.NET MVC

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

How can I find where Python is installed on Windows?

It would be either of

  • C:\Python36
  • C:\Users\(Your logged in User)\AppData\Local\Programs\Python\Python36

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

Is it possible to forward-declare a function in Python?

What you can do is to wrap the invocation into a function of its own.

So that

foo()

def foo():
    print "Hi!"

will break, but

def bar():
    foo()

def foo():
    print "Hi!"

bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

How to find the length of an array list?

System.out.println(myList.size());

Since no elements are in the list

output => 0

myList.add("newString");  // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());

Since one element is added to the list

output => 1

Scraping html tables into R data frames using the XML package

Another option using Xpath.

library(RCurl)
library(XML)

theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)

# Extract table header and contents
tablehead <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/th", xmlValue)
results <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/td", xmlValue)

# Convert character vector to dataframe
content <- as.data.frame(matrix(results, ncol = 8, byrow = TRUE))

# Clean up the results
content[,1] <- gsub(" ", "", content[,1])
tablehead <- gsub(" ", "", tablehead)
names(content) <- tablehead

Produces this result

> head(content)
   Opponent Played Won Drawn Lost Goals for Goals against % Won
1 Argentina     94  36    24   34       148           150 38.3%
2  Paraguay     72  44    17   11       160            61 61.1%
3   Uruguay     72  33    19   20       127            93 45.8%
4     Chile     64  45    12    7       147            53 70.3%
5      Peru     39  27     9    3        83            27 69.2%
6    Mexico     36  21     6    9        69            34 58.3%

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:

powershell

Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

How to insert current_timestamp into Postgres via python

from datetime import datetime as dt

then use this in your code:

cur.execute('INSERT INTO my_table (dt_col) VALUES (%s)', (dt.now(),))

Effective method to hide email from spam bots

One possibility would be to use isTrusted property (Javascript).

The isTrusted read-only property of the Event interface is a Boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via EventTarget.dispatchEvent().

eg in your case:

getEmail() {
  if (event.isTrusted) {
    /* The event is trusted */
    return '[email protected]';
  } else {
    /* The event is not trusted */
    return '[email protected]';
  }
}

? IE isn't compatible !

Read more from doc: https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted

Can't compare naive and aware datetime.now() <= challenge.datetime_end

So the way I would solve this problem is to make sure the two datetimes are in the right timezone.

I can see that you are using datetime.now() which will return the systems current time, with no tzinfo set.

tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()

seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.

Take a look at Delorean, it makes dealing with this sort of thing much easier.

DTO pattern: Best way to copy properties between two objects

I suggest you should use one of the mappers' libraries: Mapstruct, ModelMapper, etc. With Mapstruct your mapper will look like:

@Mapper
public interface UserMapper {     
    UserMapper INSTANCE = Mappers.getMapper( UserMapper.class ); 

    UserDTO toDto(User user);
}

The real object with all getters and setters will be automatically generated from this interface. You can use it like:

UserDTO userDTO = UserMapper.INSTANCE.toDto(user);

You can also add some logic for your activeText filed using @AfterMapping annotation.

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

How to create a DOM node as an object?

var template = $( "<li>", { id: "1234", html:
  $( "<div>", { class: "bar", text: "bla" } )
});
$('body').append(template);

What about this?

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

Date Conversion from String to sql Date in Java giving different output?

mm is minutes. You want MM for months:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Don't feel bad - this exact mistake comes up a lot.

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

How can I get CMake to find my alternative Boost installation?

The short version

You only need BOOST_ROOT, but you're going to want to disable searching the system for your local Boost if you have multiple installations or cross-compiling for iOS or Android. In which case add Boost_NO_SYSTEM_PATHS is set to false.

set( BOOST_ROOT "" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )

Normally this is passed on the CMake command-line using the syntax -D<VAR>=value.

The longer version

Officially speaking the FindBoost page states these variables should be used to 'hint' the location of Boost.

This module reads hints about search locations from variables:

BOOST_ROOT             - Preferred installation prefix
 (or BOOSTROOT)
BOOST_INCLUDEDIR       - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR       - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS  - Set to ON to disable searching in locations not
                         specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
                       - List of Boost versions not known to this module
                         (Boost install locations may contain the version)

This makes a theoretically correct incantation:

cmake -DBoost_NO_SYSTEM_PATHS=TRUE \
      -DBOOST_ROOT=/path/to/boost-dir

When you compile from source

include( ExternalProject )

set( boost_URL "http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.bz2" )
set( boost_SHA1 "9f1dd4fa364a3e3156a77dc17aa562ef06404ff6" )
set( boost_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/third_party/boost )
set( boost_INCLUDE_DIR ${boost_INSTALL}/include )
set( boost_LIB_DIR ${boost_INSTALL}/lib )

ExternalProject_Add( boost
        PREFIX boost
        URL ${boost_URL}
        URL_HASH SHA1=${boost_SHA1}
        BUILD_IN_SOURCE 1
        CONFIGURE_COMMAND
        ./bootstrap.sh
        --with-libraries=filesystem
        --with-libraries=system
        --with-libraries=date_time
        --prefix=<INSTALL_DIR>
        BUILD_COMMAND
        ./b2 install link=static variant=release threading=multi runtime-link=static
        INSTALL_COMMAND ""
        INSTALL_DIR ${boost_INSTALL} )

set( Boost_LIBRARIES
        ${boost_LIB_DIR}/libboost_filesystem.a
        ${boost_LIB_DIR}/libboost_system.a
        ${boost_LIB_DIR}/libboost_date_time.a )
message( STATUS "Boost static libs: " ${Boost_LIBRARIES} )

Then when you call this script you'll need to include the boost.cmake script (mine is in the a subdirectory), include the headers, indicate the dependency, and link the libraries.

include( boost )
include_directories( ${boost_INCLUDE_DIR} )
add_dependencies( MyProject boost )
target_link_libraries( MyProject
                       ${Boost_LIBRARIES} )

How can I exclude all "permission denied" messages from "find"?

If you want to start search from root "/" , you will probably see output somethings like:

find: /./proc/1731/fdinfo: Permission denied
find: /./proc/2032/task/2032/fd: Permission denied

It's because of permission. To solve this:

  1. You can use sudo command:

    sudo find /. -name 'toBeSearched.file'
    

It asks super user's password, when enter the password you will see result what you really want. If you don't have permission to use sudo command which means you don't have super user's password, first ask system admin to add you to the sudoers file.

  1. You can use redirect the Standard Error Output from (Generally Display/Screen) to some file and avoid seeing the error messages on the screen! redirect to a special file /dev/null :

    find /. -name 'toBeSearched.file' 2>/dev/null
    
  2. You can use redirect the Standard Error Output from (Generally Display/Screen) to Standard output (Generally Display/Screen), then pipe with grep command with -v "invert" parameter to not to see the output lines which has 'Permission denied' word pairs:

    find /. -name 'toBeSearched.file' 2>&1 | grep -v 'Permission denied'
    

How to programmatically set the SSLContext of a JAX-WS client?

I tried the following and it didn't work on my environment:

bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory());

But different property worked like a charm:

bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, getCustomSocketFactory());

The rest of the code was taken from the first reply.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

Vue.js toggle class on click

Without the need of a method:

// html element, will display'active' class if showMobile is true
//clicking on the elment will toggle showMobileMenu to true and false alternatively
<div id="mobile-toggle"
 :class="{ active: showMobileMenu }"
 @click="showMobileMenu = !showMobileMenu">
</div>

//in your vue.js app
data: {
    showMobileMenu: false
}

Android, How to read QR code in my application?

Zxing is an excellent library to perform Qr code scanning and generation. The following implementation uses Zxing library to scan the QR code image Don't forget to add following dependency in the build.gradle

implementation 'me.dm7.barcodescanner:zxing:1.9'

Code scanner activity:

    public class QrCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private ZXingScannerView mScannerView;

        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
            // Programmatically initialize the scanner view
            mScannerView = new ZXingScannerView(this);
            // Set the scanner view as the content view
            setContentView(mScannerView);
        }

        @Override
        public void onResume() {
            super.onResume();
            // Register ourselves as a handler for scan results.
            mScannerView.setResultHandler(this);
            // Start camera on resume
            mScannerView.startCamera();
        }

        @Override
        public void onPause() {
            super.onPause();
            // Stop camera on pause
            mScannerView.stopCamera();
        }

        @Override
        public void handleResult(Result rawResult) {
            // Do something with the result here
            // Prints scan results
            Logger.verbose("result", rawResult.getText());
            // Prints the scan format (qrcode, pdf417 etc.)
            Logger.verbose("result", rawResult.getBarcodeFormat().toString());
            //If you would like to resume scanning, call this method below:
            //mScannerView.resumeCameraPreview(this);
            Intent intent = new Intent();
            intent.putExtra(AppConstants.KEY_QR_CODE, rawResult.getText());
            setResult(RESULT_OK, intent);
            finish();
        }
    }

Fast way of finding lines in one file that are not in another?

You can use Python:

python -c '
lines_to_remove = set()
with open("file2", "r") as f:
    for line in f.readlines():
        lines_to_remove.add(line.strip())

with open("f1", "r") as f:
    for line in f.readlines():
        if line.strip() not in lines_to_remove:
            print(line.strip())
'

Pointer to class data member "::*"

Here is an example where pointer to data members could be useful:

#include <iostream>
#include <list>
#include <string>

template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
    for (const typename Container::value_type& x : container) {
        if (x->*ptr == t)
            return x;
    }
    return typename Container::value_type{};
}

struct Object {
    int ID, value;
    std::string name;
    Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};

std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
    new Object(2,11,"Tom"), new Object(15,16,"John") };

int main() {
    const Object* object = searchByDataMember (objects, 11, &Object::value);
    std::cout << object->name << '\n';  // Tom
}

How do I remove the passphrase for the SSH key without having to create a new key?

You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.

if [ -f ~/.agent.env ] ; then
    . ~/.agent.env > /dev/null
    if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
        echo "Stale agent file found. Spawning new agent… "
        eval `ssh-agent | tee ~/.agent.env`
        ssh-add
    fi 
else
    echo "Starting ssh-agent"
    eval `ssh-agent | tee ~/.agent.env`
    ssh-add
fi

On some Linux distros (Ubuntu, Debian) you can use:

ssh-copy-id -i ~/.ssh/id_dsa.pub username@host

This will copy the generated id to a remote machine and add it to the remote keychain.

You can read more here and here.

How can I make a countdown with NSTimer?

this for the now swift 5.0 and newst

var secondsRemaining = 60


Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
    if secondsRemaining > 0 {
    print("\(secondsRemaining) seconds.")
    secondsRemaining -= 1
            }
        }

How to show "if" condition on a sequence diagram?

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

How to Install gcc 5.3 with yum on CentOS 7.2?

Command to install GCC and Development Tools on a CentOS / RHEL 7 server

Type the following yum command as root user:

yum group install "Development Tools"

OR

sudo yum group install "Development Tools"

If above command failed, try:

yum groupinstall "Development Tools"

Create a new cmd.exe window from within another cmd.exe prompt

Here is the code you need:

start cmd.exe @cmd /k "Command"

Are there constants in JavaScript?

Mozillas MDN Web Docs contain good examples and explanations about const. Excerpt:

// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

But it is sad that IE9/10 still does not support const. And the reason it's absurd:

So, what is IE9 doing with const? So far, our decision has been to not support it. It isn’t yet a consensus feature as it has never been available on all browsers.

...

In the end, it seems like the best long term solution for the web is to leave it out and to wait for standardization processes to run their course.

They don't implement it because other browsers didn't implement it correctly?! Too afraid of making it better? Standards definitions or not, a constant is a constant: set once, never changed.

And to all the ideas: Every function can be overwritten (XSS etc.). So there is no difference in var or function(){return}. const is the only real constant.

Update: IE11 supports const:

IE11 includes support for the well-defined and commonly used features of the emerging ECMAScript 6 standard including let, const, Map, Set, and WeakMap, as well as __proto__ for improved interoperability.

How to get numbers after decimal point?

You can use this:

number = 5.55
int(str(number).split('.')[1])

Where does forever store console.log output?

Based on bryanmac's answer. I'm just saving all logs into one file and then reading it with tail. Simple, but effective way to do this.

forever -o common.log -e common.log index.js && tail -f common.log

how to call a variable in code behind to aspx page

For

<%=clients%>

to work you need to have a public or protected variable clients in the code-behind.

Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

How to convert wstring into string?

// Embarcadero C++ Builder 

// convertion string to wstring
string str1 = "hello";
String str2 = str1;         // typedef UnicodeString String;   -> str2 contains now u"hello";

// convertion wstring to string
String str2 = u"hello";
string str1 = UTF8string(str2).c_str();   // -> str1 contains now "hello"

How to specify test directory for mocha?

Use this:

mocha server-test

Or if you have subdirectories use this:

mocha "server-test/**/*.js"

Note the use of double quotes. If you omit them you may not be able to run tests in subdirectories.

pip install from git repo branch

Prepend the url prefix git+ (See VCS Support):

pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6

And specify the branch name without the leading /.

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

php refresh current page?

header('Location: '.$_SERVER['REQUEST_URI']);

insert data into database with codeigniter

Just insert $this->load->database(); in your model:

function order_summary_insert($data){
    $this->load->database();
    $this->db->insert('Customer_Orders',$data);
}

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

DAYS(start_date,end_date):

For example:

DAYS(A1,TODAY())

PHP: Update multiple MySQL fields in single query

I guess you can use:

$con = new mysqli("localhost", "my_user", "my_password", "world");
$sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
if ($mysqli->query($sql, $con)) {
    print "wallet $wallet updated";
}else{
    printf("Errormessage: %s\n", $con->error);
}
$con->close();

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

How to convert a timezone aware string to datetime in Python without dateutil?

You can convert like this.

date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

Searching word in vim?

For basic searching:

  • /pattern - search forward for pattern
  • ?pattern - search backward
  • n - repeat forward search
  • N - repeat backward

Some variables you might want to set:

  • :set ignorecase - case insensitive
  • :set smartcase - use case if any caps used
  • :set incsearch - show match as search

Git Remote: Error: fatal: protocol error: bad line length character: Unab

For GitExtension users:

I faced the same issue after upgrading git to 2.19.0

Solution:

Tools > Settings > Git Extensions > SSH

Select [OpenSSH] instead of [PuTTY]

enter image description here

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

How can I hide a TD tag using inline JavaScript or CSS?

Everything is possible (or almost) with css, just use:

display: none; //to hide

display: table-cell //to show

Looping through dictionary object

You can do it like this.

Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
    Console.Write(item.Key);
    Console.Write(item.Value.name);
    Console.Write(item.Value.age);
}

The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line

Dictionary<int, dynamic> sp = new Dictionary<int, dynamic> 

You should be able to access it from the function inside your controller.

Edit: Adding functional example of the full TestModels implementation.

Your TestModels class should look something like this.

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}

You probably want to read up on the dynamic keyword as well.

Server configuration is missing in Eclipse

You need to define the server instance in the Servers view.

In the box at the right bottom, press the Servers tab and add the server there. You by the way don't necessarily need to add it through global IDE preferences. It will be automagically added when you define it in Servers view. The preference you've modified just defines default locations, not the whole server instance itself. If you for instance upgrade/move the server, you can change the physical location there.

Once defining the server in the Servers view, you need to add the newly created server instance to the project through its Server and Targeted runtime preference.

Converting a sentence string to a string array of words in Java

Following is a code snippet which splits a sentense to word and give its count too.

 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;

 public class StringToword {
public static void main(String[] args) {
    String s="a a a A A";
    String[] splitedString=s.split(" ");
    Map m=new HashMap();
    int count=1;
    for(String s1 :splitedString){
         count=m.containsKey(s1)?count+1:1;
          m.put(s1, count);
        }
    Iterator<StringToword> itr=m.entrySet().iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());         
    }
    }

}

Add another class to a div

I use below function to animate UiKit gear icon using Just JavaScript

_x000D_
_x000D_
document.getElementById("spin_it").onmouseover=function(e){_x000D_
var el = document.getElementById("spin_it");_x000D_
var Classes = el.className;_x000D_
var NewClass = Classes+" uk-icon-spin";_x000D_
el.className = NewClass;_x000D_
console.log(e);_x000D_
}
_x000D_
<span class="uk-icon uk-icon-small uk-icon-gear" id="spin_it"></span>
_x000D_
_x000D_
_x000D_

This code not work here...you must add UIKit Style to it

Checking for directory and file write permissions in .NET

Deny takes precedence over Allow. Local rules take precedence over inherited rules. I have seen many solutions (including some answers shown here), but none of them takes into account whether rules are inherited or not. Therefore I suggest the following approach that considers rule inheritance (neatly wrapped into a class):

public class CurrentUserSecurity
{
    WindowsIdentity _currentUser;
    WindowsPrincipal _currentPrincipal;

    public CurrentUserSecurity()
    {
        _currentUser = WindowsIdentity.GetCurrent();
        _currentPrincipal = new WindowsPrincipal(_currentUser);
    }

    public bool HasAccess(DirectoryInfo directory, FileSystemRights right)
    {
        // Get the collection of authorization rules that apply to the directory.
        AuthorizationRuleCollection acl = directory.GetAccessControl()
            .GetAccessRules(true, true, typeof(SecurityIdentifier));
        return HasFileOrDirectoryAccess(right, acl);
    }

    public bool HasAccess(FileInfo file, FileSystemRights right)
    {
        // Get the collection of authorization rules that apply to the file.
        AuthorizationRuleCollection acl = file.GetAccessControl()
            .GetAccessRules(true, true, typeof(SecurityIdentifier));
        return HasFileOrDirectoryAccess(right, acl);
    }

    private bool HasFileOrDirectoryAccess(FileSystemRights right,
                                          AuthorizationRuleCollection acl)
    {
        bool allow = false;
        bool inheritedAllow = false;
        bool inheritedDeny = false;

        for (int i = 0; i < acl.Count; i++) {
            var currentRule = (FileSystemAccessRule)acl[i];
            // If the current rule applies to the current user.
            if (_currentUser.User.Equals(currentRule.IdentityReference) ||
                _currentPrincipal.IsInRole(
                                (SecurityIdentifier)currentRule.IdentityReference)) {

                if (currentRule.AccessControlType.Equals(AccessControlType.Deny)) {
                    if ((currentRule.FileSystemRights & right) == right) {
                        if (currentRule.IsInherited) {
                            inheritedDeny = true;
                        } else { // Non inherited "deny" takes overall precedence.
                            return false;
                        }
                    }
                } else if (currentRule.AccessControlType
                                                  .Equals(AccessControlType.Allow)) {
                    if ((currentRule.FileSystemRights & right) == right) {
                        if (currentRule.IsInherited) {
                            inheritedAllow = true;
                        } else {
                            allow = true;
                        }
                    }
                }
            }
        }

        if (allow) { // Non inherited "allow" takes precedence over inherited rules.
            return true;
        }
        return inheritedAllow && !inheritedDeny;
    }
}

However, I made the experience that this does not always work on remote computers as you will not always have the right to query the file access rights there. The solution in that case is to try; possibly even by just trying to create a temporary file, if you need to know the access right before working with the "real" files.

If statement in select (ORACLE)

In one line, answer is as below;

[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]

What is the yield keyword used for in C#?

A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.

In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.

For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:

  • Scalability, reliability and predictability are likely to improve since the number of records does not significantly affect the application’s resource requirements.
  • Performance and responsiveness are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.
  • Recoverability and utilisation are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.
  • Continuous processing is possible in environments where constant workload streams are added.

Here is a comparison between build a collection first such as a list compared to using yield.

List Example

    public class ContactListStore : IStore<ContactModel>
    {
        public IEnumerable<ContactModel> GetEnumerator()
        {
            var contacts = new List<ContactModel>();
            Console.WriteLine("ContactListStore: Creating contact 1");
            contacts.Add(new ContactModel() { FirstName = "Bob", LastName = "Blue" });
            Console.WriteLine("ContactListStore: Creating contact 2");
            contacts.Add(new ContactModel() { FirstName = "Jim", LastName = "Green" });
            Console.WriteLine("ContactListStore: Creating contact 3");
            contacts.Add(new ContactModel() { FirstName = "Susan", LastName = "Orange" });
            return contacts;
        }
    }

    static void Main(string[] args)
    {
        var store = new ContactListStore();
        var contacts = store.GetEnumerator();

        Console.WriteLine("Ready to iterate through the collection.");
        Console.ReadLine();
    }

Console Output
ContactListStore: Creating contact 1
ContactListStore: Creating contact 2
ContactListStore: Creating contact 3
Ready to iterate through the collection.

Note: The entire collection was loaded into memory without even asking for a single item in the list

Yield Example

public class ContactYieldStore : IStore<ContactModel>
{
    public IEnumerable<ContactModel> GetEnumerator()
    {
        Console.WriteLine("ContactYieldStore: Creating contact 1");
        yield return new ContactModel() { FirstName = "Bob", LastName = "Blue" };
        Console.WriteLine("ContactYieldStore: Creating contact 2");
        yield return new ContactModel() { FirstName = "Jim", LastName = "Green" };
        Console.WriteLine("ContactYieldStore: Creating contact 3");
        yield return new ContactModel() { FirstName = "Susan", LastName = "Orange" };
    }
}

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();

    Console.WriteLine("Ready to iterate through the collection.");
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection.

Note: The collection wasn't executed at all. This is due to the "deferred execution" nature of IEnumerable. Constructing an item will only occur when it is really required.

Let's call the collection again and obverse the behaviour when we fetch the first contact in the collection.

static void Main(string[] args)
{
    var store = new ContactYieldStore();
    var contacts = store.GetEnumerator();
    Console.WriteLine("Ready to iterate through the collection");
    Console.WriteLine("Hello {0}", contacts.First().FirstName);
    Console.ReadLine();
}

Console Output
Ready to iterate through the collection
ContactYieldStore: Creating contact 1
Hello Bob

Nice! Only the first contact was constructed when the client "pulled" the item out of the collection.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How do I use cascade delete with SQL Server?

You can do this with SQL Server Management Studio.

? Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.

SQL Server Management Studio

CodeIgniter - Correct way to link to another page in a view

Best and easiest way is to use anchor tag in CodeIgniter like eg.

<?php 
    $this->load->helper('url'); 
    echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => '')); 
?>

Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details

This will surely work.

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

How to center HTML5 Videos?

I will not prefer to center just using video tag as @user142019 says. I will prefer doing it like this:

_x000D_
_x000D_
.videoDiv_x000D_
{_x000D_
    width: 70%; /*or whatever % you prefer*/_x000D_
    margin: 0 auto;_x000D_
    display: block;_x000D_
}
_x000D_
<div class="videoDiv">_x000D_
  <video width="100%" controls>_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">_x000D_
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">_x000D_
  Your browser does not support the video tag._x000D_
  </video>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will make your video responsive at the same time the panel for controls will have the same size as the video rectangle (I tried what @user142019 says and the video was centered, but it looked ugly in Google Chrome).

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

Get div to take up 100% body height, minus fixed-height header and footer

As far as it is not cross browser solution, you might be take advantage of using calc(expression) to achive that.

html, body { 
 height: 100%;
}
header {        
 height: 50px;
 background-color: tomato
}

#content { 
 height: -moz-calc(100% - 100px); /* Firefox */
 height: -webkit-calc(100% - 100px); /* Chrome, Safari */
 height: calc(100% - 100px); /* IE9+ and future browsers */
 background-color: yellow 
}
footer { 
 height: 50px;
 background-color: grey;
}

Example at JsFiddle

If you want to know more about calc(expression) you'd better to visit this site.

SQL Server: how to select records with specific date from datetime column

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

PHP - Copy image to my server direct from URL

$url = "http://www.example/images/image.gif";
$save_name = "image.gif";
$save_directory = "/var/www/example/downloads/";

if(is_writable($save_directory)) {
    file_put_contents($save_directory . $save_name, file_get_contents($url));
} else {
    exit("Failed to write to directory "{$save_directory}");
}

Insert a line at specific line number with sed or awk

POSIX sed (and for example OS X's sed, the sed below) require i to be followed by a backslash and a newline. Also at least OS X's sed does not include a newline after the inserted text:

$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3

To replace a line, you can use the c (change) or s (substitute) commands with a numeric address:

$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3

Alternatives using awk:

$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3

awk interprets backslashes in variables passed with -v but not in variables passed using ENVIRON:

$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3

Both ENVIRON and -v are defined by POSIX.

How to write an inline IF statement in JavaScript?

To add to this you can also use inline if condition with && and || operators. Like this

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

How do you determine the ideal buffer size when using FileInputStream?

Reading files using Java NIO's FileChannel and MappedByteBuffer will most likely result in a solution that will be much faster than any solution involving FileInputStream. Basically, memory-map large files, and use direct buffers for small ones.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

How to debug Ruby scripts

Debugging by raising exceptions is far easier than squinting through print log statements, and for most bugs, its generally much faster than opening up an irb debugger like pry or byebug. Those tools should not always be your first step.


Debugging Ruby/Rails Quickly:

1. Fast Method: Raise an Exception then and .inspect its result

The fastest way to debug Ruby (especially Rails) code is to raise an exception along the execution path of your code while calling .inspect on the method or object (e.g. foo):

raise foo.inspect

In the above code, raise triggers an Exception that halts execution of your code, and returns an error message that conveniently contains .inspect information about the object/method (i.e. foo) on the line that you're trying to debug.

This technique is useful for quickly examining an object or method (e.g. is it nil?) and for immediately confirming whether a line of code is even getting executed at all within a given context.

2. Fallback: Use a ruby IRB debugger like byebug or pry

Only after you have information about the state of your codes execution flow should you consider moving to a ruby gem irb debugger like pry or byebug where you can delve more deeply into the state of objects within your execution path.


General Beginner Advice

When you are trying to debug a problem, good advice is to always: Read The !@#$ing Error Message (RTFM)

That means reading error messages carefully and completely before acting so that you understand what it's trying to tell you. When you debug, ask the following mental questions, in this order, when reading an error message:

  1. What class does the error reference? (i.e. do I have the correct object class or is my object nil?)
  2. What method does the error reference? (i.e. is their a type in the method; can I call this method on this type/class of object?)
  3. Finally, using what I can infer from my last two questions, what lines of code should I investigate? (remember: the last line of code in the stack trace is not necessarily where the problem lies.)

In the stack trace pay particular attention to lines of code that come from your project (e.g. lines starting with app/... if you are using Rails). 99% of the time the problem is with your own code.


To illustrate why interpreting in this order is important...

E.g. a Ruby error message that confuses many beginners:

You execute code that at some point executes as such:

@foo = Foo.new

...

@foo.bar

and you get an error that states:

undefined method "bar" for Nil:nilClass

Beginners see this error and think the problem is that the method bar is undefined. It's not. In this error the real part that matters is:

for Nil:nilClass

for Nil:nilClass means that @foo is Nil! @foo is not a Foo instance variable! You have an object that is Nil. When you see this error, it's simply ruby trying to tell you that the method bar doesn't exist for objects of the class Nil. (well duh! since we are trying to use a method for an object of the class Foo not Nil).

Unfortunately, due to how this error is written (undefined method "bar" for Nil:nilClass) its easy to get tricked into thinking this error has to do with bar being undefined. When not read carefully this error causes beginners to mistakenly go digging into the details of the bar method on Foo, entirely missing the part of the error that hints that the object is of the wrong class (in this case: nil). It's a mistake that's easily avoided by reading error messages in their entirety.

Summary:

Always carefully read the entire error message before beginning any debugging. That means: Always check the class type of an object in an error message first, then its methods, before you begin sleuthing into any stacktrace or line of code where you think the error may be occurring. Those 5 seconds can save you 5 hours of frustration.

tl;dr: Don't squint at print logs: raise exceptions or use an irb debugger instead. Avoid rabbit holes by reading errors carefully before debugging.

Python, how to read bytes from file and save it?

Here's how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.

in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()

out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()

We can do this more succinctly by using the with keyboard to handle closing the file.

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    out_file.write(in_file.read())

If you don't want to store the entire file in memory, you can transfer it in pieces.

piece_size = 4096 # 4 KiB

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    while True:
        piece = in_file.read(piece_size)

        if piece == "":
            break # end of file

        out_file.write(piece)

How to embed a SWF file in an HTML page?

<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01" 
style="width:640px;height:480px;margin:10px 36px;">

<param name="movie" value="http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="wmode" value="opaque" />
<param name="quality" value="high" />
<param name="menu" value="false" />

</object>

Bootstrap 3 Collapse show state with Chevron icon

Here's a couple of pure css helper classes which lets you handle any kind of toggle content right in your html.

It works with any element you need to switch. Whatever your layout is you just put it inside a couple of elements with the .if-collapsed and .if-not-collapsed classes within the toggle element.

The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.

It also requires the :not selector, it doesn't work on IE8.

HTML example:

<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
  <!--You can put any valid html inside these!-->
  <span class="if-collapsed">Open</span>
  <span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>

Less version:

[data-toggle="collapse"] {
    &.collapsed .if-not-collapsed {
         display: none;
    }
    &:not(.collapsed) .if-collapsed {
         display: none;
    }
}

CSS version:

[data-toggle="collapse"].collapsed .if-not-collapsed {
  display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
  display: none;
}

Getting a list of associative array keys

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

My error was define the view like this:

view = inflater.inflate(R.layout.qr_fragment, container);

It was missing:

view = inflater.inflate(R.layout.qr_fragment, container, false);

Django: How can I call a view function from template?

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

Call a global variable inside module

For those who didn't know already, you would have to put the declare statement outside your class just like this:

declare var Chart: any;

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent {
    //you can use Chart now and compiler wont complain
    private color = Chart.color;
}

In TypeScript the declare keyword is used where you want to define a variable that may not have originated from a TypeScript file.

It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

How to get the element clicked (for the whole document)?

You can find the target element in event.target:

$(document).click(function(event) {
    console.log($(event.target).text());
});

References:

How do I pass multiple parameters in Objective-C?

(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa

me:

(returnTypeOfSecontArgument) secondArgumentName ;

as in other languages we use following syntax void add(int one, int second) but way of assigning arguments in OBJ_c is different as described above

Why is volatile needed in C?

My simple explanation is:

In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The volatile keyword prevents a variable being optimised.

For example:

bool usb_interface_flag = 0;
while(usb_interface_flag == 0)
{
    // execute logic for the scenario where the USB isn't connected 
}

From the above code, the compiler may think usb_interface_flag is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as while(true) all the time, resulting in an infinite loop.

To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile.