Programs & Examples On #Metaweblog

The MetaWeblog API is an application programming interface that enables weblog entries to be written, edited, and deleted using web services.

Cannot delete or update a parent row: a foreign key constraint fails

The main problem with this erorr Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails is that it doesn't let you know which table contains the FK failure, so it is difficult to solve the conflict.

If you use MySQL or similar, I found out that you can create an ER diagram for your database, then you can review and safely remove any conflicts triggering the error.

  1. Use MySQL workbench
  2. Click on Database -> Reverse Engineering
  3. Select a correct connection
  4. Next till the end, remember to select database & tables that need examine
  5. Now you have the ER diagram, you can see which table have FK conflict

Reset textbox value in javascript

I know this is an old post, but this may help clarify:

$('#searchField')
    .val('')// [property value] e.g. what is visible / will be submitted
    .attr('value', '');// [attribute value] e.g. <input value="preset" ...

Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

How to submit an HTML form on loading the page?

You don't need Jquery here! The simplest solution here is (based on the answer from charles):

<html>
<body onload="document.frm1.submit()">
   <form action="http://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>
</html>

How to get xdebug var_dump to show full object/array

These are configurable variables in php.ini:

; with sane limits
xdebug.var_display_max_depth = 10
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024 


; with no limits
; (maximum nesting is 1023)
xdebug.var_display_max_depth = -1 
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1 

Of course, these may also be set at runtime via ini_set(), useful if you don't want to modify php.ini and restart your web server but need to quickly inspect something more deeply.

ini_set('xdebug.var_display_max_depth', '10');
ini_set('xdebug.var_display_max_children', '256');
ini_set('xdebug.var_display_max_data', '1024');

Xdebug settings are explained in the official documentation.

Div with horizontal scrolling only

overflow-x: scroll;
overflow-y: hidden;

EDIT:

It works for me:

<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>

Pad with leading zeros

The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.

Console.WriteLine("{0:0000000}", FileRecordCount);

Forgot to end the double quotes!

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

Text blinking jQuery

I was going to post the steps-timed polyfill, but then I remembered that I really don’t want to ever see this effect, so…

function blink(element, interval) {
    var visible = true;

    setInterval(function() {
        visible = !visible;
        element.style.visibility = visible ? "visible" : "hidden";
    }, interval || 1000);
}

Postgres DB Size Command

You can get the names of all the databases that you can connect to from the "pg_datbase" system table. Just apply the function to the names, as below.

select t1.datname AS db_name,  
       pg_size_pretty(pg_database_size(t1.datname)) as db_size
from pg_database t1
order by pg_database_size(t1.datname) desc;

If you intend the output to be consumed by a machine instead of a human, you can cut the pg_size_pretty() function.

PHP equivalent of .NET/Java's toString()

For objects, you may not be able to use the cast operator. Instead, I use the json_encode() method.

For example, the following will output contents to the error log:

error_log(json_encode($args));

EditorFor() and html properties

In my practice I found that it is best to use EditorTemplates with only one HtmlHelper in it - TextBox that is in most cases. If I want a template for more complex html structure, I'll write a separate HtmlHelper.

Given that we can stick the whole ViewData object in place of htmlAttributes of the TextBox. In addition we can write some customization code for some of the properties of the ViewData if they need special treatment:

@model DateTime?
@*
    1) applies class datepicker to the input;
    2) applies additionalViewData object to the attributes of the input
    3) applies property "format" to the format of the input date.
*@
@{
    if (ViewData["class"] != null) { ViewData["class"] += " datepicker"; }
    else { ViewData["class"] = " datepicker"; }
    string format = "MM/dd/yyyy";
    if (ViewData["format"] != null)
    {
        format = ViewData["format"].ToString();
        ViewData.Remove("format");
    }
}

@Html.TextBox("", (Model.HasValue ? Model.Value.ToString(format) : string.Empty), ViewData)

Below are the examples of the syntax in the view and the outputted html:

@Html.EditorFor(m => m.Date)
<input class="datepicker" data-val="true" data-val-required="&amp;#39;Date&amp;#39; must not be empty." id="Date" name="Date" type="text" value="01/08/2012">
@Html.EditorFor(m => m.Date, new { @class = "myClass", @format = "M/dd" })
<input class="myClass datepicker" data-val="true" data-val-required="&amp;#39;Date&amp;#39; must not be empty." id="Date" name="Date" type="text" value="1/08">

Check if element exists in jQuery

If you have a class on your element, then you can try the following:

if( $('.exists_content').hasClass('exists_content') ){
 //element available
}

Get parent directory of running script

This is also a possible solution

$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;

javascript, is there an isObject function like isArray?

In jQuery there is $.isPlainObject() method for that:

Description: Check to see if an object is a plain object (created using "{}" or "new Object").

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

how to change onclick event with jquery?

If you want to change one specific onclick event with jQuery, you better use the functions .on() and .off() with a namespace (see documentation).

Use .on() to create your event and .off() to remove it. You can also create a global object like g_specific_events_set = {}; to avoid duplicates:

_x000D_
_x000D_
$('#alert').click(function()_x000D_
{_x000D_
    alert('First alert!');_x000D_
});_x000D_
_x000D_
g_specific_events_set = {};_x000D_
_x000D_
add_specific_event = function(namespace)_x000D_
{_x000D_
    if (!g_specific_events_set[namespace])_x000D_
    {_x000D_
        $('#alert').on('click.' + namespace, function()_x000D_
        {_x000D_
            alert('SECOND ALERT!!!!!!');_x000D_
        });_x000D_
        g_specific_events_set[namespace] = true;_x000D_
    }_x000D_
};_x000D_
_x000D_
remove_specific_event = function(namespace)_x000D_
{_x000D_
    $('#alert').off('click.' + namespace);_x000D_
    g_specific_events_set[namespace] = false;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
$('#add').click(function(){ add_specific_event('eventnumber2'); });_x000D_
_x000D_
$('#remove').click(function(){ remove_specific_event('eventnumber2'); });
_x000D_
div {_x000D_
  display:inline-block;_x000D_
  vertical-align:top;_x000D_
  margin:0 5px 1px 5px;_x000D_
  padding:5px 20px;_x000D_
  background:#ddd;_x000D_
  border:1px solid #aaa;_x000D_
  cursor:pointer;_x000D_
}_x000D_
div:active {_x000D_
  margin-top:1px;_x000D_
  margin-bottom:0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="alert">_x000D_
  Alert_x000D_
</div>_x000D_
<div id="add">_x000D_
  Add event_x000D_
</div>_x000D_
<div id="remove">_x000D_
  Remove event_x000D_
</div>
_x000D_
_x000D_
_x000D_

Retrieving Data from SQL Using pyodbc

you could try using Pandas to retrieve information and get it as dataframe

import pyodbc as cnn
import pandas as pd

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')

# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
    df=pd.DataFrame(argumento)
    df.to_clipboard(index=False,header=True)


tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn) 

# Copy to Clipboard
copia(tableResult)

# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')

I hope this helps! Cheers!

Check if PHP session has already started

You should reorganize your code so that you call session_start() exactly once per page execution.

Histogram with Logarithmic Scale and custom breaks

Another option would be to use the package ggplot2.

ggplot(mydata, aes(x = V3)) + geom_histogram() + scale_x_log10()

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

How to use JavaScript to change div backgroundColor

If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.

<style type="text/css">
  .content {
    background: #ccc;
  }

  .fakeLink { /* This is to make the link not look like one */
    cursor: default;
    text-decoration: none;
    color: #000;
  }

  a.fakeLink:hover .content {
    background: #000;
    color: #fff;
  }

</style>
<div id="catestory">

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

  <a href="#" onclick="return false();" class="fakeLink">
    <div class="content">
      <h2>some title here</h2>
      <p>some content here</p>
    </div>
  </a>

</div>

Link error "undefined reference to `__gxx_personality_v0'" and g++

It sounds like you're trying to link with your resulting object file with gcc instead of g++:

Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:

$ g++ -Wall -c hello.cc
$ gcc hello.o       (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
  undefined reference to `__gxx_personality_v0'

Source: An Introduction to GCC - for the GNU compilers gcc and g++

Double Iteration in List Comprehension

Additionally, you could use just the same variable for the member of the input list which is currently accessed and for the element inside this member. However, this might even make it more (list) incomprehensible.

input = [[1, 2], [3, 4]]
[x for x in input for x in x]

First for x in input is evaluated, leading to one member list of the input, then, Python walks through the second part for x in x during which the x-value is overwritten by the current element it is accessing, then the first x defines what we want to return.

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

How do I check if a string is a number (float)?

I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:

def is_float(text):
    try:
        float(text)
        # check for nan/infinity etc.
        if text.isalpha():
            return False
        return True
    except ValueError:
        return False

How to destroy an object?

May be in a situation where you are creating a new mysqli object.

$MyConnection = new mysqli($hn, $un, $pw, $db);

but even after you close the object

$MyConnection->close();

if you will use print_r() to check the contents of $MyConnection, you will get an error as below:

Error:
mysqli Object

Warning: print_r(): Property access is not allowed yet in /path/to/program on line ..
( [affected_rows] => [client_info] => [client_version] =>.................)

in which case you can't use unlink() because unlink() will require a path name string but in this case $MyConnection is an Object.

So you have another choice of setting its value to null:

$MyConnection = null;

now things go right, as you have expected. You don't have any content inside the variable $MyConnection as well as you already cleaned up the mysqli Object.

It's a recommended practice to close the Object before setting the value of your variable to null.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

How to convert any date format to yyyy-MM-dd

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Here, SourceDate is variable in which you will get selected date.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

Stratified Train/Test-split in scikit-learn

TL;DR : Use StratifiedShuffleSplit with test_size=0.25

Scikit-learn provides two modules for Stratified Splitting:

  1. StratifiedKFold : This module is useful as a direct k-fold cross-validation operator: as in it will set up n_folds training/testing sets such that classes are equally balanced in both.

Heres some code(directly from above documentation)

>>> skf = cross_validation.StratifiedKFold(y, n_folds=2) #2-fold cross validation
>>> len(skf)
2
>>> for train_index, test_index in skf:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
...    #fit and predict with X_train/test. Use accuracy metrics to check validation performance
  1. StratifiedShuffleSplit : This module creates a single training/testing set having equally balanced(stratified) classes. Essentially this is what you want with the n_iter=1. You can mention the test-size here same as in train_test_split

Code:

>>> sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
>>> len(sss)
1
>>> for train_index, test_index in sss:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
>>> # fit and predict with your classifier using the above X/y train/test

ASP.NET MVC ActionLink and post method

ActionLink will never fire post. It always trigger GET request.

Android ADB device offline, can't issue commands

I needed to kill multiple adb processes (adb kill-server & adb start-server still left a lingering process alive.)

$ ps aux | grep adb

$ killall adb

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

How to get element value in jQuery

You can do the same by using jQuery on().

$("#list").on('click','li',(function() {
    var selected = $(this).text();   //or .html()
    alert(selected);
})

incompatible character encodings: ASCII-8BIT and UTF-8

I encountered the error while migrating an app from Ruby 1.8.7 to 1.9.3 and it only occured in production. It turned out that I had some leftovers in my Memcache store. The now encoding sensitive Ruby 1.9.3 version of my app tried to mix old ASCII-8BIT values with new UTF-8.

It was as simple as flushing the cache to fix it for me.

Does Notepad++ show all hidden characters?

Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.

Download the Hex Plugin from here; http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

C# delete a folder and all files and folders within that folder

dir.Delete(true); // true => recursive delete

How do I programmatically click on an element in JavaScript?

Using jQuery you can do exactly the same thing, for example:

$("a").click();

Which will "click" all anchors on the page.

How to create a function in a cshtml template?

If you want to access your page's global variables, you can do so:

@{
    ViewData["Title"] = "Home Page";

    var LoadingButtons = Model.ToDictionary(person => person, person => false);

    string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}

What is phtml, and when should I use a .phtml extension rather than .php?

It is a file ext that some folks used for a while to denote that it was PHP generated HTML. As servers like Apache don't care what you use as a file ext as long as it is mapped to something, you could go ahead and call all your PHP files .jimyBobSmith and it would happily run them. PHTML just happened to be a trend that caught on for a while.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

First please check in module.ts file that in @NgModule all properties are only one time. If any of are more than one time then also this error come. Because I had also occur this error but in module.ts file entryComponents property were two time that's why I was getting this error. I resolved this error by removing one time entryComponents from @NgModule. So, I recommend that first you check it properly.

Bootstrap 4 img-circle class not working

Now the class is this

_x000D_
_x000D_
 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
_x000D_
_x000D_

How to make inline functions in C#

Yes, C# supports that. There are several syntaxes available.

  • Anonymous methods were added in C# 2.0:

    Func<int, int, int> add = delegate(int x, int y)
    {
        return x + y;
    };
    Action<int> print = delegate(int x)
    {
        Console.WriteLine(x);
    }
    Action<int> helloWorld = delegate // parameters can be elided if ignored
    {
        Console.WriteLine("Hello world!");
    }
    
  • Lambdas are new in C# 3.0 and come in two flavours.

    • Expression lambdas:

      Func<int, int, int> add = (int x, int y) => x + y; // or...
      Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
      
    • Statement lambdas:

      Action<int> print = (int x) => { Console.WriteLine(x); };
      Action<int> print = x => { Console.WriteLine(x); }; // inferred types
      Func<int, int, int> add = (x, y) => { return x + y; };
      
  • Local functions have been introduced with C# 7.0:

    int add(int x, int y) => x + y;
    void print(int x) { Console.WriteLine(x); }
    

There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>, which is roughly equivalent to Func<T, T, int>.

Func<string, string, int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l, r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards

These can be invoked directly as if they were regular methods:

int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
               // even though it does not make any use of it.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

The problem is due to older version of ojdbc - ojdbc14.

Place the latest version of ojdbc jar file in your application or shared library. (Only one version should be there and it should be the latest one) As of today - ojdbc6.jar

Check the application libraries and shared libraries on server.

Is there an easy way to strike through text in an app widget?

try this code

textview.setText((Html.fromHtml("<strike>hello world!</strike>")));

List file using ls command in Linux with full path

you just want the full path why not use the utility meant for that a combination of readlink and grep should get you what you want

grep -R  '--include=*.'{mkv,mp4} ? | cut -d ' ' -f3  | xargs readlink -e # 
the question mark should be replaced with the right pattern - this is almost right
# this is probably the best solution remove the grep part if you dont need a filter
find <dirname> | grep .mkv | xargs readlink -e |  xargs ls --color=auto # only matroska files in the dir and subdirs with nice color - also you can edit ls flags
find /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7 | grep .mkv 
find /mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7 | xargs grep -R  '--include=*.'{mkv,mp4} . | cut -d ' ' -f3 # I am sure you can do more with grep 
readlink -f `ls` # in the directory or 

Session state can only be used when enableSessionState is set to true either in a configuration

I have got this error only when debugging the ASP .Net Application.

I also had Session["mysession"] kind of variables added into my Watch of Visual Studio.

the issue was solved Once, I have removed the Session Variables from watch.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Kotlin:

You can also use CountDownTimer:

class Timer {
    companion object {
        @JvmStatic
        fun call(ms: Long, f: () -> Unit) {
            object : CountDownTimer(ms,ms){
                override fun onFinish() { f() }
                override fun onTick(millisUntilFinished: Long) {}
            }.start()
        }
    }
}

And in your code:

Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

Is there a jQuery unfocus method?

This works for me:

// Document click blurer
$(document).on('mousedown', '*:not(input,textarea)', function() {
    try {
        var $a = $(document.activeElement).prop("disabled", true);
        setTimeout(function() {
            $a.prop("disabled", false);
        });
    } catch (ex) {}
});

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

Alternative to deprecated getCellType

Use getCellType()

switch (cell.getCellType()) {
   case BOOLEAN :
                 //To-do
                 break;
   case NUMERIC:
                 //To-do
                 break;
   case STRING:
                 //To-do
                 break;
}

Create a copy of a table within the same database DB2

Two steps works fine:

create table bu_x as (select a,b,c,d from x ) WITH no data;

insert into bu_x (a,b,c,d) select select a,b,c,d from x ;

EXEC sp_executesql with multiple parameters

This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.

DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1  nvarchar (100) = 'test1'
DECLARE @xTxt2  nvarchar (500) = 'test2' 
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2

How to specify 64 bit integers in c

Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)

What is the use of the @Temporal annotation in Hibernate?

I use Hibernate 5.2 and @Temporal is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.

File Upload ASP.NET MVC 3.0

please pay attention this code for upload image only. I use HTMLHelper for upload image. in cshtml file put this code

@using (Html.BeginForm("UploadImageAction", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
    <div class="controls">
       @Html.UploadFile("UploadImage")
    </div>
     <button class="button">Upload Image</button>
}

then create a HTMLHelper for Upload tag

public static class UploadHelper
{
public static MvcHtmlString UploadFile(this HtmlHelper helper, string name, object htmlAttributes = null)
{
    TagBuilder input = new TagBuilder("input");
    input.Attributes.Add("type", "file");
    input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
    input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));

    if (htmlAttributes != null)
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        input.MergeAttributes(attributes);
    }

    return new MvcHtmlString(input.ToString());
   }
}

and finally in Action Upload your file

        [AjaxOnly]
        [HttpPost]
        public ActionResult UploadImageAction(HttpPostedFileBase UploadImage)
        {
           string path = Server.MapPath("~") + "Files\\UploadImages\\" + UploadImage.FileName;
           System.Drawing.Image img = new Bitmap(UploadImage.InputStream);    
           img.Save(path);

           return View();
        }

Import CSV file with mixed data types

Given the sample you posted, this simple code should do the job:

fid = fopen('file.csv','r');
C = textscan(fid, repmat('%s',1,10), 'delimiter',';', 'CollectOutput',true);
C = C{1};
fclose(fid);

Then you could format the columns according to their type. For example if the first column is all integers, we can format it as such:

C(:,1) = num2cell( str2double(C(:,1)) )

Similarly, if you wish to convert the 8th column from hex to decimals, you can use HEX2DEC:

C(:,8) = cellfun(@hex2dec, strrep(C(:,8),'0x',''), 'UniformOutput',false);

The resulting cell array looks as follows:

C = 
    [  4]    'abc'    'def'    'ghj'    'klm'    ''            ''                []    ''    ''
    [NaN]    ''       ''       ''       ''       'Test'        'text'        [ 255]    ''    ''
    [NaN]    ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    [3855]    ''    ''

How to do error logging in CodeIgniter (PHP)

To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.

First, to trigger an error:

trigger_error("Error message here", E_USER_ERROR);

By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:

ini_set('error_log', 'path/to/log/file');

Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)

To e-mail the error, you need to set up a custom error handler:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

Please see the relevant PHP documentation for more info.

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

Javascript ajax call on page onload

It's even easier to do without a library

window.onload = function() {
    // code
};

Get access to parent control from user control - C#

A generic way to get a parent of a control that I have used is:

public static T GetParentOfType<T>(this Control control)
{
    const int loopLimit = 100; // could have outside method
    var current = control;
    var i = 0;

    do
    {
        current = current.Parent;

        if (current == null) throw new Exception("Could not find parent of specified type");
        if (i++ > loopLimit) throw new Exception("Exceeded loop limit");

    } while (current.GetType() != typeof(T));

    return (T)Convert.ChangeType(current, typeof(T));
}

It needs a bit of work (e.g. returning null if not found or error) ... but hopefully could help someone.

Usage:

var parent = currentControl.GetParentOfType<TypeWanted>();

Enjoy!

Does functional programming replace GoF design patterns?

You can't have this discussion without bringing up type systems.

The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.

That's because these features don't address the same issues that OOP does... they are alternatives to imperative programming. The FP answer to OOP lies in the type systems of ML and Haskell... specifically sum types, abstract data types, ML modules, and Haskell typeclasses.

But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use)

The first thing typeclasses do is eliminate the need for singletons.

You could go through the list of 23 and eliminate more, but I don't have time to right now.

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

In my case I have moved plugins folder mistakenly to another folder while taking backup of my unnecessary projects. Then while I was trying to run the eclipse.exe I was getting the error-

The Eclipse executable launcher was unable to locate its companion shared library.

I have simply copied the plugins folder to eclipse root directory, and it was working fine for me.

If you have the folders backup in your computer then just copy and paste the folders on eclipse directory, you don't need to reinstall or change the ini file so far I realized.

T-SQL How to select only Second row from a table?

No need of row number functions if field ID is unique.

SELECT TOP 1 *
FROM (
  SELECT TOP 2 * 
  FROM yourTable
  ORDER BY ID
) z
ORDER BY ID DESC

What's a good (free) visual merge tool for Git? (on windows)

I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.

Sometimes tools should be paid for if they are very very good.

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

Display exact matches only with grep

Try this:

Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK

How to check if Location Services are enabled?

On Android 8.1 or lower the user can enable "Battery saving" mode from
Settings > Location > Mode > Battery Saving.
This mode only uses WiFi, Bluetooth or mobile data instead of GPS to determine the user location.

That's why you have to check if the network provider is enabled and locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) is not enough.

If you are using androidx this code will check which SDK version you are running and call the corresponding provider:

public boolean isLocationEnabled(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return manager != null ? LocationManagerCompat.isLocationEnabled(manager) : false;
}

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

Can you force Vue.js to reload/re-render?

Use vm.$set('varName', value). Look for details into Change_Detection_Caveats.

Session 'app': Error Installing APK

What worked for me is deleting the app from the emulator (which was an app built from an older commit) and re-running from Android Studio.

How to install pandas from pip on windows cmd?

pip install pandas make sure, this is 'pandas' not 'panda'

If you are not able to access pip, then got to C:\Python37\Scripts and run pip.exe install pandas.

Alternatively, you can add C:\Python37\Scripts in the env variables for windows machines. Hope this helps.

Git diff against a stash

@Magne's answer is the only one to (very late) date that answers the most flexible/useful interpretation of the question, but its a fair bit more complicated than necessary. Rather than committing and resetting, just stash your working copy, compare, then unstash.

git stash save "temp"
git diff stash@{0} stash@{1}
git stash pop

That shows you the differences between the top of the stash stack and your working folder by temporarily making your working folder changes become the top of the stash stack (stash@{0}), moving the original top down one (stash@{1}) then comparing using the original top in the 'new set' position so you see the changes that would result from applying it on top of your current work.

"But what if I don't have any current work?" Then you are in the normal boring case. Just use @Amber's answer

git stash show

or @czerasz's answer

git diff stash@{0}

or admit that stashing and unstashing is fast and easy anyway, just unstash the changes and inspect them. If you don't want them at the moment throw them (the current index/working folder changes) away. In full that's

git stash apply
git diff
git reset
git checkout

How do I turn off Unicode in a VC++ project?

you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".

Oracle 11g Express Edition for Windows 64bit?

There is

I used this blog post to install it in my machine: http://luminite.wordpress.com/2012/09/06/installing-oracle-database-xe-11g-on-windows-7-64-bit-machine/

The only thing you have to do is replace a registry value during the installation, I've done it about three times already, and every time found a different reference on-line, none here on stackoverflow.

EDIT: as @kc2001 noted, regedit must be run as Administrator, and added this tutorial: (a bit more colorful): http://www.hanmiaojuan.com/2013/03/install-oracle-xe-11g-for-windows7-64bits.html

Change the name of a key in dictionary

d = {1:2,3:4}

suppose that we want to change the keys to the list elements p=['a' , 'b']. the following code will do:

d=dict(zip(p,list(d.values()))) 

and we get

{'a': 2, 'b': 4}

Postman - How to see request with headers and body data with variables substituted

Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.

PHP - find entry by object property from an array of objects

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using it the way you wanted would be something like:

ArrayUtils::objArraySearch($array,'ID',$v);

How do I add comments to package.json for npm install?

As duplicate comment keys are removed running package.json tools (npm, yarn, etc.), I came to using a hashed version which allows for better reading as multiple lines and keys like:

"//": {
  "alpaca": "we use the bootstrap version",
  "eonasdan-bootstrap-datetimepicker": "instead of bootstrap-datetimepicker",
  "moment-with-locales": "is part of moment"
},

which is 'valid' according to my IDE as a root key, but within dependencies it complains expecting a string value.

ValueError: unconverted data remains: 02:05

  timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
  File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

In my case, the problem was an extra space in the input date string. So I used strip() and it started to work.

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

No, the problem is that * is a reserved character in regexes, so you need to escape it.

String [] separado = line.split("\\*");

* means "zero or more of the previous expression" (see the Pattern Javadocs), and you weren't giving it any previous expression, making your split expression illegal. This is why the error was a PatternSyntaxException.

Best Way to Refresh Adapter/ListView on Android

Just write in your Custom ArrayAdaper this code:

private List<Cart_items> customListviewList ;

refreshEvents(carts);

public void refreshEvents(List<Cart_items> events)
{
    this.customListviewList.clear();
    this.customListviewList.addAll(events);
    notifyDataSetChanged();
}

Convert normal Java Array or ArrayList to Json Array in android

ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);

This is only an example using a string arraylist

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Unable to generate an explicit migration in entity framework

Old post but might help someone. For me it happened because I renamed Assembly name and Default namespace of the project. So I had to update ContextKey in _MigrationHisotry table to the new value of Assembly name or Default namespace. Honestly I don't know which one should be used, because for me both are same!

Run AVD Emulator without Android Studio

Open your terminal and

cd path_to/Android/Sdk/emulator

And run the following to get the emulator name that you created before using android studio

./emulator -list-avds

Replace $emulator_name with the one you want to launch and run

./emulator -avd $emulator_name

Better way to convert file sizes in Python

Here is my implementation:

from bisect import bisect

def to_filesize(bytes_num, si=True):
    decade = 1000 if si else 1024
    partitions = tuple(decade ** n for n in range(1, 6))
    suffixes = tuple('BKMGTP')

    i = bisect(partitions, bytes_num)
    s = suffixes[i]

    for n in range(i):
        bytes_num /= decade

    f = '{:.3f}'.format(bytes_num)

    return '{}{}'.format(f.rstrip('0').rstrip('.'), s)

It will print up to three decimals and it strips trailing zeros and periods. The boolean parameter si will toggle usage of 10-based vs. 2-based size magnitude.

This is its counterpart. It allows to write clean configuration files like {'maximum_filesize': from_filesize('10M'). It returns an integer that approximates the intended filesize. I am not using bit shifting because the source value is a floating point number (it will accept from_filesize('2.15M') just fine). Converting it to an integer/decimal would work but makes the code more complicated and it already works as it is.

def from_filesize(spec, si=True):
    decade = 1000 if si else 1024
    suffixes = tuple('BKMGTP')

    num = float(spec[:-1])
    s = spec[-1]
    i = suffixes.index(s)

    for n in range(i):
        num *= decade

    return int(num)

open program minimized via command prompt

For the people which are looking for the opposite (aka fullscreen), it's very simple. Because you just have to replace the settings /min by /max.

Now the program will be open at the "maximized" size ! In the case, perhaps you will need an example : start /max explorer.exe.

What is the reason behind "non-static method cannot be referenced from a static context"?

The compiler actually adds an argument to non-static methods. It adds a this pointer/reference. This is also the reason why a static method can not use this, because there is no object.

ImportError: No module named PIL

In shell, run:

pip install Pillow

Attention: PIL is deprecated, and pillow is the successor.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

For me, I just wanted the text to be invisible and still use the native browser button.

input[type='file'] {
  color: transparent;
}

I like all of undefined's suggestions but I had a different use case, hope this helps someone in the same situation.

How to check for the type of a template parameter?

In C++17, we can use variants.

To use std::variant, you need to include the header:

#include <variant>

After that, you may add std::variant in your code like this:

using Type = std::variant<Animal, Person>;

template <class T>
void foo(Type type) {
    if (std::is_same_v<type, Animal>) {
        // Do stuff...
    } else {
        // Do stuff...
    }
}

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

Convert Xml to DataTable

How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.

There is also a DataTable.ReadXml method.

JavaScript: undefined !== undefined?

It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined when object.x is the real undefined. In my case I inadvertently set undefined to null.

The easiest way to see this happen is:

window.undefined = null;
alert(window.xyzw === undefined); // shows false

Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.

var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false

How many spaces will Java String.trim() remove?

trim() will remove all leading and trailing blanks. But be aware: Your string isn't changed. trim() will return a new string instance instead.

jQuery Mobile how to check if button is disabled?

try :is selector

$("#deliveryNext").is(":disabled")

When to use extern in C++

It's all about the linkage.

The previous answers provided good explainations about extern.

But I want to add an important point.

You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

In C++, a const variable has internal linkage by default (not like C).

So this scenario will lead to linking error:

Source 1 :

const int global = 255; //wrong way to make a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

It need to be like this:

Source 1 :

extern const int global = 255; //a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I also ran into this error. Restart the PC works for me.

Formatting floats without trailing zeros

You can use max() like this:

print(max(int(x), x))

How to determine if a list of polygon points are in clockwise order?

After testing several unreliable implementations, the algorithm that provided satisfactory results regarding the CW/CCW orientation out of the box was the one, posted by OP in this thread (shoelace_formula_3).

As always, a positive number represents a CW orientation, whereas a negative number CCW.

How to implement a Map with multiple keys?

I can see the following approaches:

a) Use 2 different maps. You can wrap them in a class as you suggest, but even that might be an overkill. Just use the maps directly: key1Map.getValue(k1), key2Map.getValue(k2)

b) You can create a type-aware key class, and use that (untested).

public class Key {
  public static enum KeyType { KEY_1, KEY_2 }

  public final Object k;
  public final KeyType t;

  public Key(Object k, KeyType t) {
    this.k = k;
    this.t= t;
  }

  public boolean equals(Object obj) {
    KeyType kt = (KeyType)obj;
    return k.equals(kt.k) && t == kt.t;
  }

  public int hashCode() {
   return k.hashCode() ^ t.hashCode();
  }
}

By the way, in a lot of common cases the space of key1 and the space of key2 do not intersect. In that case, you don't actually need to do anything special. Just define a map that has entries key1=>v as well as key2=>v

How would you count occurrences of a string (actually a char) within a string?

In C#, a nice String SubString counter is this unexpectedly tricky fellow:

public static int CCount(String haystack, String needle)
{
    return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}

Get screenshot on Windows with Python?

If you want to snap particular running Windows app you’ll have to acquire a handle by looping over all open windows in your system.

It’s easier if you can open this app from Python script. Then you can convert process pid into window handle.

Another challenge is to snap the app that runs in particular monitor. I have 3 monitor system and I had to figure out how to snap display 2 and 3.

This example will take multiple application snapshots and save them into JPEG files.

import wx

print(wx.version())
app=wx.App()  # Need to create an App instance before doing anything
dc=wx.Display.GetCount()
print(dc)
#e(0)
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in displays]

for (i,s) in enumerate(sizes):
    print("Monitor{} size is {}".format(i,s))   
screen = wx.ScreenDC()
#pprint(dir(screen))
size = screen.GetSize()

print("Width = {}".format(size[0]))
print("Heigh = {}".format(size[1]))

width=size[0]
height=size[1]
x,y,w,h =putty_rect

bmp = wx.Bitmap(w,h)
mem = wx.MemoryDC(bmp)

for i in range(98):
    if 1:
        #1-st display:

        #pprint(putty_rect)
        #e(0)

        mem.Blit(-x,-y,w+x,h+y, screen, 0,0)

    if 0:
        #2-nd display:
        mem.Blit(0, 0, x,y, screen, width,0)
    #e(0)

    if 0:
        #3-rd display:
        mem.Blit(0, 0, width, height, screen, width*2,0)

    bmp.SaveFile(os.path.join(home,"image_%s.jpg" % i), wx.BITMAP_TYPE_JPEG)    
    print (i)
    sleep(0.2)
del mem

Details are here

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

This is how it worked for me. For Windows users testing with Bracket and AngularJS

1) Go to your desktop

2) Right click on your desktop and look for "NEW" in the popup drop down dialog box and it will expand

3) Choose Shortcut

4) A dialog box will open

5) Click on Browse and look for Google Chrome.

6) Click Ok->Next->Finish and it will create the google shortcut on your desktop

7) Now Right Click on the Google Chrome icon you just created

8) Click properties

9) Enter this in the target path

"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security

10) Save it

11) Double click on your newly created chrome shortcut and past your link in the address bar and it will work.

Can Json.NET serialize / deserialize to / from a stream?

public static void Serialize(object value, Stream s)
{
    using (StreamWriter writer = new StreamWriter(s))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        JsonSerializer ser = new JsonSerializer();
        ser.Serialize(jsonWriter, value);
        jsonWriter.Flush();
    }
}

public static T Deserialize<T>(Stream s)
{
    using (StreamReader reader = new StreamReader(s))
    using (JsonTextReader jsonReader = new JsonTextReader(reader))
    {
        JsonSerializer ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

Calling Python in PHP

Your call_python_file.php should look like this:

<?php
    $item='Everything is awesome!!';
    $tmp = exec("py.py $item");
    echo $tmp;
?>

This executes the python script and outputs the result to the browser. While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:

import sys

list1 = ' '.join(sys.argv[1:])

def main():
  print list1

if __name__ == '__main__':
    main()

Get Application Directory

Just use this in your code

 context.getApplicationInfo().dataDir

Maximum value for long integer

In python3, you can send the float value into the int function the get that number 1.7976931348623157e+308 in integer representation.

import sys    
int(sys.float_info.max)

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

How to pass parameters on onChange of html select

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

How to sort an associative array by its values in Javascript?

There really isn't any such thing as an "associative array" in JavaScript. What you've got there is just a plain old object. They work kind-of like associative arrays, of course, and the keys are available but there's no semantics around the order of keys.

You could turn your object into an array of objects (key/value pairs) and sort that:

function sortObj(object, sortFunc) {
  var rv = [];
  for (var k in object) {
    if (object.hasOwnProperty(k)) rv.push({key: k, value:  object[k]});
  }
  rv.sort(function(o1, o2) {
    return sortFunc(o1.key, o2.key);
  });
  return rv;
}

Then you'd call that with a comparator function.

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

How to install packages offline?

For Pip 8.1.2 you can use pip download -r requ.txt to download packages to your local machine.

Why does ++[[]][+[]]+[+[]] return the string "10"?

This one evaluates to the same but a bit smaller

+!![]+''+(+[])
  • [] - is an array is converted that is converted to 0 when you add or subtract from it, so hence +[] = 0
  • ![] - evaluates to false, so hence !![] evaluates to true
  • +!![] - converts the true to a numeric value that evaluates to true, so in this case 1
  • +'' - appends an empty string to the expression causing the number to be converted to string
  • +[] - evaluates to 0

so is evaluates to

+(true) + '' + (0)
1 + '' + 0
"10"

So now you got that, try this one:

_=$=+[],++_+''+$

Setting the default Java character encoding

Solve this problem in my project. Hope it helps someone.

I use LIBGDX java framework and also had this issue in my android studio project. In Mac OS encoding is correct, but in Windows 10 special characters and symbols and also russian characters show as questions like: ????? and other incorrect symbols.

  1. Change in android studio project settings: File->Settings...->Editor-> File Encodings to UTF-8 in all three fields (Global Encoding, Project Encoding and Default below).

  2. In any java file set:

    System.setProperty("file.encoding","UTF-8");

  3. And for test print debug log:

    System.out.println("My project encoding is : "+ Charset.defaultCharset());

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Radio button validation in javascript

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

What is the proper REST response code for a valid request but an empty data?

In previous projects, I've used 404. If there's no user 9, then the object was not found. Therefore 404 Not Found is appropriate.

For object exists, but there is no data, 204 No Content would be appropriate. I think in your case, the object does not exist though.

How to check if a stored procedure exists before creating it

If you're looking for the simplest way to check for a database object's existence before removing it, here's one way (example uses a SPROC, just like your example above but could be modified for tables, indexes, etc...):

IF (OBJECT_ID('MyProcedure') IS NOT NULL)
  DROP PROCEDURE MyProcedure
GO

This is quick and elegant, but you need to make sure you have unique object names across all object types since it does not take that into account.

I Hope this helps!

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I don't have enough context to give you a correct answer, but I'll suggest you to make you code immutable as much as possible. Use public final fields. No more getters or setters : every field has to be defined by the constructor. Your code is shorter, more readable and prevents you from writing code with side effects.

It doesn't prevent you from passing null arguments to your constructor though... You can still check every argument as suggested by @cletus, but I'll suggest you to throw IllegalArgumentException instead of NullPointerException that doesn't give no new hint about what you've done.

Anyway, that's what I do as much as I can and it improved my code (readability, stability) to a great extend. Everyone in my team does so and we are very happy with that. We learned that when we try to write some erlang code where everything is immutable.

Hope this helps.

How can I get the executing assembly version?

using System.Reflection;
{
    string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}

Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

Create a folder if it doesn't already exist

What about a helper function like this:

function makeDir($path)
{
     $ret = mkdir($path); // use @mkdir if you want to suppress warnings/errors
     return $ret === true || is_dir($path);
}

It will return true if the directory was successfully created or already exists, and false if the directory couldn't be created.

A better alternative is this (shouldn't give any warnings):

function makeDir($path)
{
     return is_dir($path) || mkdir($path);
}

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

Understanding .get() method in Python

Start here http://docs.python.org/tutorial/datastructures.html#dictionaries

Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict

Then here http://docs.python.org/library/stdtypes.html#dict.get

characters.get( key, default )

key is a character

default is 0

If the character is in the dictionary, characters, you get the dictionary object.

If not, you get 0.


Syntax:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Is mathematics necessary for programming?

Certian kinds of math I think are indispensible. For instance, every software engineer should know and understand De Morgan's laws, and O notation.

Other kinds are just very useful. In simulation we often have to do a lot of physics modeling. If you are doing graphics work, you will often find yourself needing to write coordinate transformation algorithms. I've had many other situations in my 20 year career where I needed to write up and solve simultanious linear equations to figure out what constants to put into an algorithm.

Background color for Tk in Python

root.configure(background='black')

or more generally

<widget>.configure(background='black')

if statement in ng-click

From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:

ng-click="variable = (condition=='X' ? 'Y' : 'X')"

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

Why is my Git Submodule HEAD detached from master?

I am also still figuring out the internals of git, and have figured out this so far:

  1. HEAD is a file in your .git/ directory that normally looks something like this:
% cat .git/HEAD
ref: refs/heads/master
  1. refs/heads/master is itself a file that normally has the hash value of the latest commit:
% cat .git/refs/heads/master 
cbf01a8e629e8d884888f19ac203fa037acd901f
  1. If you git checkout a remote branch that is ahead of your master, this may cause your HEAD file to be updated to contain the hash of the latest commit in the remote master:
% cat .git/HEAD
8e2c815f83231f85f067f19ed49723fd1dc023b7

This is called a detached HEAD. The remote master is ahead of your local master. When you do git submodule --remote myrepo to get the latest commit of your submodule, it will by default do a checkout, which will update HEAD. Since your current branch master is behind, HEAD becomes 'detached' from your current branch, so to speak.

multiple where condition codeigniter

it's late for this answer but i think maybe still can help, i try the both methods above, using two where conditions and the method with the array, none of those work for me i did several test and the condition was never getting executed, so i did a workaround, here is my code:

public function validateLogin($email, $password){
        $password = md5($password);
        $this->db->select("userID,email,password");
        $query = $this->db->get_where("users", array("email" => $email));
        $p = $query->row_array();

        if($query->num_rows() == 1 && $password == $p['password']){  
            return $query->row();
        }

    }

Eclipse C++: Symbol 'std' could not be resolved

The includes folder in the project is probably missing /usr/include/c++. Goto your project in project explorer, right click -> Properties -> C\C++ Build -> Environment -> add -> value= /usr/include/c++. Restart eclipse.

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

Using ls to list directories and their total sizes

If you want more control over the size that you want to list the directories over, you can use the threshold (-t) switch as in:

$ du -ht 1000000000 | sort --reverse

du - disk usage
h - human readable format
t - threshold size

Here, we want to list all directories which are greater than 1GB in size.

$ du -ht 1G | sort --reverse

Explanation:

Units that are described in wiki follows:

K, M, G, T, P, E, Z, Y (powers of 1024) or
KB, MB, GB, TB, PB, EB, ZB, YB (powers of 1000).

CSS to select/style first word

Insert Span Tag in your paragraph text. For Example- <p><span>Hello</span>My Name Is Dot</p and then style the first letter.

Use find command but exclude files in two directories

You can try below:

find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'

Swift's guard keyword

Unlike if, guard creates the variable that can be accessed from outside its block. It is useful to unwrap a lot of Optionals.

What does '?' do in C++?

It is called the conditional operator.

You can replace it with:

int qempty(){ 
    if (f == r) return 1;
    else return 0;
}

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

How to add a new audio (not mixing) into a video using ffmpeg?

mp3 music to wav

ffmpeg -i music.mp3 music.wav

truncate to fit video

ffmpeg -i music.wav -ss 0 -t 37 musicshort.wav

mix music and video

ffmpeg -i musicshort.wav -i movie.avi final_video.avi

C# try catch continue execution

Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.

I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.

There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finally block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!

Last edit (probably):

In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:

public Something? function2()
{
    try
    {
        //all of your function goes here
        return anActualObjectOfTypeSomething;
    }
    catch(Exception ex)
    {
        //logging goes here
        return null;
    }
}

That way, since you use a nullable return type, returning null doesn't hurt you.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

How to define a two-dimensional array?

That's what dictionary is made for!

matrix = {}

You can define keys and values in two ways:

matrix[0,0] = value

or

matrix = { (0,0)  : value }

Result:

   [ value,  value,  value,  value,  value],
   [ value,  value,  value,  value,  value],
   ...

UTL_FILE.FOPEN() procedure not accepting path for directory?

Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Add header:

#include<math.h>

Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.

abs()- provides absolute values;

example, abs(-3) =3

Include -lm at the end of your command during compilation time:

gcc <filename.extension> -lm

APT command line interface-like yes/no input?

def question(question, answers):
    acceptable = False
    while not acceptable:
        print(question + "specify '%s' or '%s'") % answers
        answer = raw_input()
        if answer.lower() == answers[0].lower() or answers[0].lower():
            print('Answer == %s') % answer
            acceptable = True
    return answer

raining = question("Is it raining today?", ("Y", "N"))

This is how I'd do it.

Output

Is it raining today? Specify 'Y' or 'N'
> Y
answer = 'Y'

VBA: Selecting range by variables

I tried using:

Range(cells(1, 1), cells(lastRow, lastColumn)).Select 

where lastRow and lastColumn are integers, but received run-time error 1004. I'm using an older VB (6.5).

What did work was to use the following:

Range(Chr(64 + firstColumn) & firstRow & ":" & Chr(64 + lastColumn) & firstColumn).Select.  

Tensorflow: Using Adam optimizer

The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.

See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.

These variables must be initialized before you can train a model.

The normal way to initialize variables is to call tf.initialize_all_variables() which adds ops to initialize the variables present in the graph when it is called.

(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)

What you must do is call initialize_all_variables() after you have added the optimizer:

...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables.  These will include 
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

Create zip file and ignore directory structure

You can use -j.

-j
--junk-paths
          Store just the name of a saved file (junk the path), and do  not
          store  directory names. By default, zip will store the full path
          (relative to the current directory).

How do we use runOnUiThread in Android?

Below is corrected Snippet of runThread Function.

private void runThread() {

    new Thread() {
        public void run() {
            while (i++ < 1000) {
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            btn.setText("#" + i);
                        }
                    });
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

How to check heap usage of a running JVM from the command line?

All procedure at once. Based on @Till Schäfer answer.

In KB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'

In MB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'

"Awk sum" reference:

 a[1] - S0C
 a[2] - S1C
 a[3] - S0U
 a[4] - S1U
 a[5] - EC
 a[6] - EU
 a[7] - OC
 a[8] - OU
 a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT

Used for "Awk sum":

a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).

[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]

Thanks!

NOTE: Works to OpenJDK!

FURTHER QUESTION: Wrong information?

If you check memory usage with the ps command, you will see that the java process consumes much more...

ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1

UPDATE (2021-02-16):

According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps command and the jstat command.

According to our understanding, the most "realistic" information would be the ps output since we will have an effective response of how much of the system's memory is compromised. The command jstat serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.

[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]

How to access List elements

Tried list[:][0] to show all first member of each list inside list is not working. Result is unknowingly will same as list[0][:]

So i use list comprehension like this:

[i[0] for i in list] which return first element value for each list inside list.

Get filename from input [type='file'] using jQuery

This was a very important issue for me in order for my site to be multilingual. So here is my conclusion tested in Firefox and Chrome.

jQuery trigger comes in handy.

So this hides the standard boring type=file labels. You can place any label you want and format anyway. I customized a script from http://demo.smarttutorials.net/ajax1/. The script allows multiple file uploads with thumbnail preview and uses PHP and MySQL.

<form enctype="multipart/form-data" name='imageform' role="form"    ="imageform" method="post" action="upload_ajax.php">
    <div class="form-group">
        <div id="select_file">Select a file</div>
        <input class='file' type="file" style="display: none " class="form-control" name="images_up" id="images_up" placeholder="Please choose your image">
        <div id="my_file"></div>
        <span class="help-block"></span>
    </div>
    <div id="loader" style="display: none;">
        Please wait image uploading to server....
    </div>
    <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>

$('#select_file').click(function() {
    $('#images_up').trigger('click');
    $('#images_up').change(function() {
        var filename = $('#images_up').val();
        if (filename.substring(3,11) == 'fakepath') {
            filename = filename.substring(12);
        } // Remove c:\fake at beginning from localhost chrome
        $('#my_file').html(filename);
   });
});

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

Grep to find item in Perl array

I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.

Perhaps,

if (grep(/^$match$/, @array)) more apt.

sed edit file in place

The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

Example:

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

and

sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

on macOS.

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

Just get column names from hive table

If you simply want to see the column names this one line should provide it without changing any settings:

describe database.tablename;

However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:

use database;
describe tablename;

How to add,set and get Header in request of HttpClient?

On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

You have something like this:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

How to embed images in html email

Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.

define("EMAIL_DOMAIN", "yourdomain.com");

public function send_email_html($to, $from, $subject, $html) {
  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();
  foreach ($matches[1] as $img) {
    $img_old = $img;
    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }
  $uniqid   = md5(uniqid(time()));
  $boundary = "--==_mimepart_".$uniqid;

  $headers = "From: ".$from."\n".
  'Reply-to: '.$from."\n".
  'Return-Path: '.$from."\n".
  'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
  'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
  'Mime-Version: 1.0'."\n".
  'Content-Type: multipart/related;'."\n".
  '  boundary='.$boundary.";\n".
  '  charset=UTF-8'."\n".
  'X-Mailer: PHP/' . phpversion();

  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'UTF-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
  $multipart .= "$html\n\n";
  foreach ($paths as $path) {
    if (file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }
    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);
    $message_part = "";
    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }
    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";
  }
  $multipart .= "--$boundary--\n";
  mail($to, $subject, $multipart, $headers);
}

Display only date and no time

Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:

[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }

It will hide the time button from the date picker too.

Sorry if this answer is a little late ;)

Javascript "Uncaught TypeError: object is not a function" associativity question

Your code experiences a case where the Automatic Semicolon Insertion (ASI) process doesn't happen.

You should never rely on ASI. You should use semicolons to properly separate statements:

var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!

(function() { alert('hello there') })();

Your code was actually trying to invoke the array object.

Why does PEP-8 specify a maximum line length of 79 characters?

Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.

Readability is also one of the reasons for enforced line indentation.

Override back button to act like home button

I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:

Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.

  @Override
  public void onBackPressed() {
      Intent intent = new Intent(this, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
  }

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Even though that this question was already answered I feel that there are missing examples in the answer that was answered.

Therefore I'll bring here what I wrote in a blog post "Android Log Levels"

Verbose

Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.

Debug

Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.

Info

For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.

Warning

When there is a potentially harmful situation.

This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.

Error

Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.

WTF (What a Terrible Failure)

Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.

How to get the absolute path to the public_html folder?

put anyfile on the directories you wanted to find, in this case, place 'root' at public_html

/home/user/public_html/root <- note that 'root' is not a folder (you can use root.txt if u want)

And use this function

function findThis($get){
    $d = '';
    for($i = 0; $i < 20; $i++){//this will try 20 times recursively on upper folder
        if(file_exists($d.$get)){
            return $d;
        }else{
            $d.="../";
        }
    }
}

and get the value by calling it

$pathToRoot = findThis('root');

And it will return, for example the the dir of php script is

/home/user/public_html/test/another-dir/test.php

so the $pathToRoot will be

$pathToRoot => "../../../"

Is this the one you want??

Strip HTML from strings in Python

Here's my solution for python 3.

import html
import re

def html_to_txt(html_text):
    ## unescape html
    txt = html.unescape(html_text)
    tags = re.findall("<[^>]+>",txt)
    print("found tags: ")
    print(tags)
    for tag in tags:
        txt=txt.replace(tag,'')
    return txt

Not sure if it is perfect, but solved my use case and seems simple.

Greater than and less than in one statement

This is one ugly way to do this. I would just use a local variable.

EDIT: If size() > 0 as well.

if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)

Store text file content line by line into array

JAVA 8 :

Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());

How to find and restore a deleted file in a Git repository

If the deletion has not been committed, the command below will restore the deleted file in the working tree.

$ git checkout -- <file>

You can get a list of all the deleted files in the working tree using the command below.

$ git ls-files --deleted

If the deletion has been committed, find the commit where it happened, then recover the file from this commit.

$ git rev-list -n 1 HEAD -- <file>
$ git checkout <commit>^ -- <file>

In case you are looking for the path of the file to recover, the following command will display a summary of all deleted files.

$ git log --diff-filter=D --summary

powershell - list local users and their groups

Update as an alternative to the excellent answer from 2010:

You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups

Example:

PS C:\WINDOWS\system32> Get-LocalGroupMember -name users

ObjectClass Name                             PrincipalSource 
----------- ----                             --------------- 
User        DESKTOP-R05QDNL\someUser1        Local           
User        DESKTOP-R05QDNL\someUser2        MicrosoftAccount
Group       NT AUTHORITY\INTERACTIVE         Unknown  

You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.

In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:

$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"

New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description

Compare given date with today

If you do things with time and dates Carbon is you best friend;

Install the package then:

$theDay = Carbon::make("2010-01-21 00:00:00.0");

$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))

lt = less than, gt = greater than

As in the question:

$theDay->gt(Carbon::today()) ? true : false;

and much more;

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

For wireless debugging, Mac system and iPhone/Device should be on same network. For making on same network you can do as - Either you can start hotspot on Mac & connect that on iPhone/Device or vice versa.

On Mac

enter image description here

OR

On iPhone-

enter image description here

Xcode ? Window ? Devices and Simulators ? select devices Tab ? click connect via network enter image description here

https://help.apple.com/xcode/mac/9.0/index.html?localePath=en.lproj#/devbc48d1bad

Zip lists in Python

It's worth adding here as it is such a highly ranking question on zip. zip is great, idiomatic Python - but it doesn't scale very well at all for large lists.

Instead of:

books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]

for book, word in zip(books, words):
   print('{}: {}'.format(book, word))

Use izip. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i:

for book, word in izip(books, words):
   print('{}: {}'.format(book, word))

Linux command to check if a shell script is running or not

The simplest and efficient solution is :

pgrep -fl aa.sh

How can I make a link from a <td> table cell

Use this code. It expands an <a> to fill the cell horizontally. To fill vertically, use the height property as well.

_x000D_
_x000D_
td a {_x000D_
  width: 100%;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
td {_x000D_
  /* Cell styles for demonstration purposes only */_x000D_
  border: 1px solid black;_x000D_
  width: 10em;_x000D_
}
_x000D_
<table><tr>_x000D_
  <td>_x000D_
    <a href="http://example.com">_x000D_
      Hello World_x000D_
    </a>_x000D_
  </td>_x000D_
</tr></table>
_x000D_
_x000D_
_x000D_

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

Try-catch-finally-return clarification

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

Python: Passing variables between functions

passing variable from one function as argument to other functions can be done like this

define functions like this

def function1():
global a
a=input("Enter any number\t")

def function2(argument):
print ("this is the entered number - ",argument)

call the functions like this

function1()
function2(a)

PostgreSQL error: Fatal: role "username" does not exist

In local user prompt, not root user prompt, type

sudo -u postgres createuser <local username>

Then enter password for local user.

Then enter the previous command that generated "role 'username' does not exist."

Above steps solved the problem for me. If not, please send terminal messages for above steps.

Google Maps Api v3 - find nearest markers

Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.

Steps:-

  1. Create marker on google map.
    function addMarker(location) { var marker = new google.maps.Marker({ title: 'User added marker', icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, scale: 5 }, position: location, map: map }); }

  2. On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().

    function find_closest_marker(event) {
          var distances = [];
          var closest = -1;
          for (i = 0; i < markers.length; i++) {
            var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
            distances[i] = d;
            if (closest == -1 || d < distances[closest]) {
              closest = i;
            }
          }
          alert('Closest marker is: ' + markers[closest].getTitle());
        }
    

visit this link follow the steps. You will able to get nearer marker to your location.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I faced the issue, In my understanding, It is because of invalid combination of Android Studio And Gradle Plugin versions. I was using Gradle version 5.4.1 and Studio version 3.4, hence I updated the Android studio to 3.5 and the issue got resolved

Check if returned value is not null and if so assign it, in one line, with one method call

Since Java 9 you have Objects#requireNonNullElse which does:

public static <T> T requireNonNullElse(T obj, T defaultObj) {
    return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}

Your code would be

dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());

Which is 1 line and calls getChicken() only once, so both requirements are satisfied.

Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.

Consider also the alternative Objects#requireNonNullElseGet:

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.