Programs & Examples On #Nerdtree

NERD tree is a plugin for the vim text editor. It allows users to view and navigate the filesystem while editing.

How to jump back to NERDTree from file in tab?

gt = next Tap gT = previous Tab

Efficiently finding the last line in a text file

If you can pick a reasonable maximum line length, you can seek to nearly the end of the file before you start reading.

myfile.seek(-max_line_length, os.SEEK_END)
line = myfile.readlines()[-1]

How can I refresh a page with jQuery?

Use onclick="return location.reload();" within the button tag.

<button id="refersh-page" name="refersh-page" type="button" onclick="return location.reload();">Refesh Page</button>

What Language is Used To Develop Using Unity

You can use C#, Javascript, Boo.

Unless computing requirement for the function you write cause heavy load on processor, Javascript gives good enough performance for most cases.

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

How do I decode a string with escaped unicode?

Edit (2017-10-12):

@MechaLynx and @Kevin-Weber note that unescape() is deprecated from non-browser environments and does not exist in TypeScript. decodeURIComponent is a drop-in replacement. For broader compatibility, use the below instead:

decodeURIComponent(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'

Original answer:

unescape(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'

You can offload all the work to JSON.parse

Splitting string into multiple rows in Oracle

If you have Oracle APEX 5.1 or later installed, you can use the convenient APEX_STRING.split function, e.g.:

select q.Name, q.Project, s.column_value as Error
from mytable q,
     APEX_STRING.split(q.Error, ',') s

The second parameter is the delimiter string. It also accepts a 3rd parameter to limit how many splits you want it to perform.

https://docs.oracle.com/en/database/oracle/application-express/20.1/aeapi/SPLIT-Function-Signature-1.html#GUID-3BE7FF37-E54F-4503-91B8-94F374E243E6

Rotating a two-dimensional array in Python

Consider the following two-dimensional list:

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

Lets break it down step by step:

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

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

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

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

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Readably print out a python dict() sorted by key

Actually pprint seems to sort the keys for you under python2.5

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

But not always under python 2.4

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

Reading the source code of pprint.py (2.5) it does sort the dictionary using

items = object.items()
items.sort()

for multiline or this for single line

for k, v in sorted(object.items()):

before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

Python3 Update

Pretty print by sorted keys (lambda x: x[0]):

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

Pretty print by sorted values (lambda x: x[1]):

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

My BIOS VT-X was on, but I had to turn PAE/NX off to get the VM to run.

Using ffmpeg to encode a high quality video

Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH

Bash tool to get nth line from a file

All the above answers directly answer the question. But here's a less direct solution but a potentially more important idea, to provoke thought.

Since line lengths are arbitrary, all the bytes of the file before the nth line need to be read. If you have a huge file or need to repeat this task many times, and this process is time-consuming, then you should seriously think about whether you should be storing your data in a different way in the first place.

The real solution is to have an index, e.g. at the start of the file, indicating the positions where the lines begin. You could use a database format, or just add a table at the start of the file. Alternatively create a separate index file to accompany your large text file.

e.g. you might create a list of character positions for newlines:

awk 'BEGIN{c=0;print(c)}{c+=length()+1;print(c+1)}' file.txt > file.idx

then read with tail, which actually seeks directly to the appropriate point in the file!

e.g. to get line 1000:

tail -c +$(awk 'NR=1000' file.idx) file.txt | head -1
  • This may not work with 2-byte / multibyte characters, since awk is "character-aware" but tail is not.
  • I haven't tested this against a large file.
  • Also see this answer.
  • Alternatively - split your file into smaller files!

What does "select count(1) from table_name" on any database tables mean?

You can test like this:

create table test1(
 id number,
 name varchar2(20)
);

insert into test1 values (1,'abc');
insert into test1 values (1,'abc');

select * from test1;
select count(*) from test1;
select count(1) from test1;
select count(ALL 1) from test1;
select count(DISTINCT 1) from test1;

How can I get the class name from a C++ object?

You could try using "typeid".

This doesn't work for "object" name but YOU know the object name so you'll just have to store it somewhere. The Compiler doesn't care what you namned an object.

Its worth bearing in mind, though, that the output of typeid is a compiler specific thing so even if it produces what you are after on the current platform it may not on another. This may or may not be a problem for you.

The other solution is to create some kind of template wrapper that you store the class name in. Then you need to use partial specialisation to get it to return the correct class name for you. This has the advantage of working compile time but is significantly more complex.

Edit: Being more explicit

template< typename Type > class ClassName
{
public:
    static std::string name()
    {
        return "Unknown";
    }
};

Then for each class somethign liek the following:

template<> class ClassName<MyClass>
{
public:
    static std::string name()
    {
        return "MyClass";
    }
};

Which could even be macro'd as follows:

#define DefineClassName( className ) \
\
template<> class ClassName<className> \
{ \
public: \
    static std::string name() \
    { \
        return #className; \
    } \
}; \

Allowing you to, simply, do

DefineClassName( MyClass );

Finally to Get the class name you'd do the following:

ClassName< MyClass >::name();

Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function.

Edit3: And thinking about it ... Its obviously bad posting first thing in the morning as you may as well just define a member function "classname()" as follows:

std::string classname()
{
     return "MyClass";
}

which can be macro'd as follows:

DefineClassName( className ) \
std::string classname()  \
{ \
     return #className; \
}

Then you can simply just drop

DefineClassName( MyClass );

into the class as you define it ...

How do I do logging in C# without using 3rd party libraries?

I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.

How to put img inline with text

This should display the image inline:

.content-dir-item img.mail {
    display: inline-block;
    *display: inline; /* for older IE */
    *zoom: 1; /* for older IE */
}

SyntaxError: expected expression, got '<'

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.

Android Shared preferences for creating one time activity (example)

Shared Preferences is so easy to learn, so take a look on this simple tutorial about sharedpreference

import android.os.Bundle;
import android.preference.PreferenceActivity;

    public class UserSettingActivity extends PreferenceActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

      addPreferencesFromResource(R.xml.settings);

    }
}

mysql_config not found when installing mysqldb python interface

I was installing python-mysql on Ubuntu 12.04 using

pip install mysql-python

First I had the same problem:

Not Found "mysql_config"

This worked for me

$ sudo apt-get install libmysqlclient-dev

Then I had this problem:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

Then I tried with

apt-get install python-dev

And then I was happy :)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

jQuery scroll to ID from different page

I would like to recommend using the scrollTo plugin

http://demos.flesler.com/jquery/scrollTo/

You can the set scrollto by jquery css selector.

$('html,body').scrollTo( $(target), 800 );

I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset() or .position() have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.

What is the easiest way to parse an INI file in Java?

Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:

HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile); 

// Get Section names in ini file     
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();

while(sectionNames.hasNext()){

 String sectionName = sectionNames.next().toString();

 SubnodeConfiguration sObj = iniObj.getSection(sectionName);
 Iterator it1 =   sObj.getKeys();

    while (it1.hasNext()) {
    // Get element
    Object key = it1.next();
    System.out.print("Key " + key.toString() +  " Value " +  
                     sObj.getString(key.toString()) + "\n");
}

Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).

The Completest Cocos2d-x Tutorial & Guide List

Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.

How to check if "Radiobutton" is checked?

radioButton.isChecked() function returns true if the Radion button is chosen, false otherwise.

Source

2D array values C++

One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.

Another alternative is to represent a 2D array as an std::vector<std::vector<int> >. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.

jQuery Event : Detect changes to the html/text of a div

Use MutationObserver as seen in this snippet provided by Mozilla, and adapted from this blog post

Alternatively, you can use the JQuery example seen in this link

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

XCOPY switch to create specified directory if it doesn't exist?

I hate the PostBuild step, it allows for too much stuff to happen outside of the build tool's purview. I believe that its better to let MSBuild manage the copy process, and do the updating. You can edit the .csproj file like this:

  <Target Name="AfterBuild" Inputs="$(TargetPath)\**">
    <Copy SourceFiles="$(TargetPath)\**" DestinationFiles="$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\**" OverwriteReadOnlyFiles="true"></Copy>
  </Target>

How do you create a Swift Date object?

Personally I think it should be a failable initialiser:

extension Date {

    init?(dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        if let d = dateStringFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since: d)
        } else {
            return nil
        }
    }
}

Otherwise a string with an invalid format will raise an exception.

How to run a python script from IDLE interactive shell?

In IDLE, the following works :-

_x000D_
_x000D_
import helloworld
_x000D_
_x000D_
_x000D_

I don't know much about why it works, but it does..

javac option to compile all java files under a given directory recursively

I've been using this in an Xcode JNI project to recursively build my test classes:

find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}

Unresolved external symbol in object files

A possible reason for the "Unresolved external symbol" error can be the function calling convention.

Make sure that all the source files are using same standard (.c or .cpp), or specify the calling convention.

Otherwise, if one file is a C file (source.c) and another file is a .cpp file, and they link to the same header, then the "unresolved external symbol" error will be thrown, because the function is first defined as a C cdecl function, but then C++ file using the same header will look for a C++ function.

To avoid the "Unresolved external symbol error", make sure that the function calling convention is kept the same among the files using it.

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

How can you strip non-ASCII characters from a string? (in C#)

I believe MonsCamus meant:

parsememo = Regex.Replace(parsememo, @"[^\u0020-\u007E]", string.Empty);

How to solve a timeout error in Laravel 5

I had a similar problem just now. However, this had nothing to do with modifying the php.ini file. It was from a for loop. If you are having nested for loops, make sure you are using the iterator properly. In my case, I was iterating the outer iterator from my inner iterator.

Convert java.util.date default format to Timestamp in Java

You can use DateFormat(java.text.*) to parse the date:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")

You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

Create empty file using python

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.

Angular-cli from css to scss

For users of the Nrwl extensions who come across this thread: all commands are intercepted by Nx (e.g., ng generate component myCompent) and then passed down to the AngularCLI.

The command to get SCSS working in an Nx workspace:

ng config schematics.@nrwl/schematics:component.styleext scss

Passing data to a jQuery UI Dialog

Just give you some idea may help you, if you want fully control dialog, you can try to avoid use of default button options, and add buttons by yourself in your #dialog div. You also can put data into some dummy attribute of link, like Click. call attr("data") when you need it.

Why are primes important in cryptography?

Simple? Yup.

If you multiply two large prime numbers, you get a huge non-prime number with only two (large) prime factors.

Factoring that number is a non-trivial operation, and that fact is the source of a lot of Cryptographic algorithms. See one-way functions for more information.

Addendum: Just a bit more explanation. The product of the two prime numbers can be used as a public key, while the primes themselves as a private key. Any operation done to data that can only be undone by knowing one of the two factors will be non-trivial to unencrypt.

Convert categorical data in pandas dataframe

First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes. This way, you can apply above operation on multiple and automatically selected columns.

First making an example dataframe:

In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})

In [76]: df['col2'] = df['col2'].astype('category')

In [77]: df['col3'] = df['col3'].astype('category')

In [78]: df.dtypes
Out[78]:
col1       int64
col2    category
col3    category
dtype: object

Then by using select_dtypes to select the columns, and then applying .cat.codes on each of these columns, you can get the following result:

In [80]: cat_columns = df.select_dtypes(['category']).columns

In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')

In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)

In [84]: df
Out[84]:
   col1  col2  col3
0     1     0     0
1     2     1     1
2     3     2     0
3     4     0     1
4     5     1     1

What does "where T : class, new()" mean?

That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor.

That means T can't be an int, float, double, DateTime or any other struct (value type).

It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

How to find integer array size in java

public class Test {

    int[] array = { 1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554,
            22, 22, 211 };

    public void Printrange() {

        for (int i = 0; i < array.length; i++) { // <-- use array.length 
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range :" + array[i]);
            }
        }
    }
}

Tools to generate database tables diagram with Postgresql?

SchemaCrawler for PostgreSQL can generate database diagrams from the command line, with the help of GraphViz. You can use regular expressions to include and exclude tables and columns. It can also infer relationships between tables using common naming conventions, if not foreign keys are defined.

How to enumerate an object's properties in Python?

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of a dictionary (which is different from an 'object' in Python), use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

Update values from one column in same table to another in SQL Server

UPDATE `tbl_user` SET `name`=concat('tbl_user.first_name','tbl_user.last_name') WHERE student_roll>965

WorksheetFunction.CountA - not working post upgrade to Office 2010

I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:

  1. It appears you are relying on VBA to determine variable types and modify accordingly. This can get confusing if you are not careful, because VBA may assign a variable type you did not intend. In your code, a type of Range should be assigned to myRange. Since a Range type is an object in VBA it needs to be Set, like this: Set myRange = Range("A:A")
  2. Your use of the worksheet function CountA() should be called with .WorksheetFunction

If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim statements, as I have done below.

The following code works for me in 2010. Hopefully it works for you too:

Dim myRange As Range
Dim NumRows As Integer

Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)

Good Luck.

How do I find the location of Python module sources?

from the standard library try imp.find_module

>>> import imp
>>> imp.find_module('fontTools')
(None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5))
>>> imp.find_module('datetime')
(None, 'datetime', ('', '', 6))

How to remove/delete a large file from commit history in Git repository?

When you run into this problem, git rm will not suffice, as git remembers that the file existed once in our history, and thus will keep a reference to it.

To make things worse, rebasing is not easy either, because any references to the blob will prevent git garbage collector from cleaning up the space. This includes remote references and reflog references.

I put together git forget-blob, a little script that tries removing all these references, and then uses git filter-branch to rewrite every commit in the branch.

Once your blob is completely unreferenced, git gc will get rid of it

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

I put this together thanks to the answers from Stack Overflow and some blog entries. Credits to them!

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Just click red button to stop all services on eclipse than re- run application as Spring Boot Application - This worked for me.

Stop absolutely positioned div from overlapping text

Thing which works for me is to use padding-bottom on the sibling just before the absolutely-positioned child. Like in your case, it will be like this:

<div style="position: relative; width:600px;">
    <p>Content of unknown length, but quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite long</p>
    <div style="padding-bottom: 100px;">Content of unknown height</div>
    <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;background-color: red;"></div>
</div>

jQuery Toggle Text?

Use this

jQuery.fn.toggleText = function() {
    var altText = this.data("alt-text");
    if (altText) {
        this.data("alt-text", this.html());
        this.html(altText);
    }
};

Here is how you sue it

_x000D_
_x000D_
 _x000D_
   jQuery.fn.toggleText = function() {_x000D_
     var altText = this.data("alt-text");_x000D_
_x000D_
     if (altText) {_x000D_
      this.data("alt-text", this.html());_x000D_
      this.html(altText);_x000D_
     }_x000D_
    };_x000D_
_x000D_
    $('[data-toggle="offcanvas"]').click(function ()  {_x000D_
_x000D_
     $(this).toggleText();_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>
_x000D_
_x000D_
_x000D_

You can even use html provided it's html encoded properly

Copy entire contents of a directory to another using php

For Linux servers you just need one line of code to copy recursively while preserving permission:

exec('cp -a '.$source.' '.$dest);

Another way of doing it is:

mkdir($dest);
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item)
{
    if ($item->isDir())
        mkdir($dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
    else
        copy($item, $dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
}

but it's slower and does not preserve permissions.

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

PostgreSQL Autoincrement

You can use any other integer data type, such as smallint.

Example :

CREATE SEQUENCE user_id_seq;
CREATE TABLE user (
    user_id smallint NOT NULL DEFAULT nextval('user_id_seq')
);
ALTER SEQUENCE user_id_seq OWNED BY user.user_id;

Better to use your own data type, rather than user serial data type.

Chrome, Javascript, window.open in new tab

You can use this code to open in new tab..

function openWindow( url )
{
  window.open(url, '_blank');
  window.focus();
}

I got it from stackoverflow..

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

Validation of radio button group using jQuery validation plugin

Puts the error message on top.

   <style> 

 .radio-group{ 
      position:relative; margin-top:40px; 
 } 

 #myoptions-error{ 
     position:absolute; 
     top: -25px; 
  } 

 </style> 

 <div class="radio-group"> 
 <input type="radio" name="myoptions" value="blue" class="required"> Blue<br /> 
 <input type="radio" name="myoptions" value="red"> Red<br /> 
 <input type="radio" name="myoptions" value="green"> Green </div>
 </div><!-- end radio-group -->

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

How to add border radius on table row

I think collapsing your borders is the wrong thing to do in this case. Collapsing them basically means that the border between two neighboring cells becomes shared. This means it's unclear as to which direction it should curve given a radius.

Instead, you can give a border radius to the two lefthand corners of the first TD and the two righthand corners of the last one. You can use first-child and last-child selectors as suggested by theazureshadow, but these may be poorly supported by older versions of IE. It might be easier to just define classes, such as .first-column and .last-column to serve this purpose.

jquery - Check for file extension before uploading

The following code allows to upload gif, png, jpg, jpeg and bmp files.

var extension = $('#your_file_id').val().split('.').pop().toLowerCase();

if($.inArray(extension, ['gif','png','jpg','jpeg','bmp']) == -1) {
    alert('Sorry, invalid extension.');
    return false;
}

When I catch an exception, how do I get the type, file, and line number?

You could achieve this without having to import traceback:

try:
    func1()
except Exception as ex:
    trace = []
    tb = ex.__traceback__
    while tb is not None:
        trace.append({
            "filename": tb.tb_frame.f_code.co_filename,
            "name": tb.tb_frame.f_code.co_name,
            "lineno": tb.tb_lineno
        })
        tb = tb.tb_next
    print(str({
        'type': type(ex).__name__,
        'message': str(ex),
        'trace': trace
    }))

Output:

{

  'type': 'ZeroDivisionError',
  'message': 'division by zero',
  'trace': [
    {
      'filename': '/var/playground/main.py',
      'name': '<module>',
      'lineno': 16
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func1',
      'lineno': 11
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func2',
      'lineno': 7
    },
    {
      'filename': '/var/playground/my.py',
      'name': 'test',
      'lineno': 2
    }
  ]
}

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

ORA-03113: end-of-file on communication channel

Is the database letting you know that the network connection is no more. This could be because:

  1. A network issue - faulty connection, or firewall issue
  2. The server process on the database that is servicing you died unexpectedly.

For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.

For 1) (network) speak to your network admin (connection could be unreliable)

For 2) Check the alert.log for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.

Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)

How to add url parameters to Django template url tag?

This can be done in three simple steps:

1) Add item id with url tag:

{% for item in post %}
<tr>
  <th>{{ item.id }}</th>
  <td>{{ item.title }}</td>
  <td>{{ item.body }}</td>
  <td>
    <a href={% url 'edit' id=item.id %}>Edit</a>
    <a href={% url 'delete' id=item.id %}>Delete</a>
  </td>
</tr>
{% endfor %}

2) Add path to urls.py:

path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')

3) Use the id on views.py:

def delete(request, id):
    obj = post.objects.get(id=id)
    obj.delete()

    return redirect('dashboard')

logout and redirecting session in php

Use this instead:

<?
session_start();
session_unset();
session_destroy();

header("location:home.php");
exit();
?>

Simulate a specific CURL in PostMan

I tried the approach mentioned by Onkaar Singh,

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!

But the problem is it didn't work for the Apis which requires authorisation.

This was my curl request:

curl -v -H "Accept: application/json" -H "Content-type:
application/json" -X POST -d ' 
{"customer_id":"812122", "event":"add_to_cart", "email": "[email protected]", }' 
-u 9f4d7f5445e7: https://api.myapp.com/api/event

After importing the body got imported correctly, the headers and the Url also got imported. Only the api key 9f4d7f5445e7 which is

-u 9f4d7f5445e7: https://api.myapp.com/api/v1/event 

in the curl request did not import.

The way I solved it is, -u is basically used for Authorization. So while using it in Postman, you have to take the API key (which is 9f4d7f5445e7 in this case) and do Base64 Encode. Once encoded it will return the value OWY0ZDdmNTQ0NWU3. Then add a new header, the key name would be Authorization and key value would be Basic OWY0ZDdmNTQ0NWU3. After making that changes, the request worked for me.

There are online Base64 Encoders available, the one I used is http://www.url-encode-decode.com/base64-encode-decode/

Hope it helps!!!

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

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

Hope this helps! :)

Python equivalent of D3.js

I've got a good example of automatically generating D3.js network diagrams using Python here: http://brandonrose.org/ner2sna

The cool thing is that you end up with auto-generated HTML and JS and can embed the interactive D3 chart in a notebook with an IFrame

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Download files in laravel using Response::download

While using laravel 5 use this code as you don`t need headers.

return response()->download($pathToFile); .

If you are using Fileentry you can use below function for downloading.

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    $pathToFile=storage_path()."/app/".$entry->filename;
    return response()->download($pathToFile);           
}

Practical uses of git reset --soft?

Another potential use is as an alternative to stashing (which some people don't like, see e.g. https://codingkilledthecat.wordpress.com/2012/04/27/git-stash-pop-considered-harmful/).

For example, if I'm working on a branch and need to fix something urgently on master, I can just do:

git commit -am "In progress."

then checkout master and do the fix. When I'm done, I return to my branch and do

git reset --soft HEAD~1

to continue working where I left off.

Javascript: Unicode string to hex

Here is a tweak of McDowell's algorithm that doesn't pad the result:

  function toHex(str) {
    var result = '';
    for (var i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
  }

Run react-native on android emulator

I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,

android avd

Once the emulator is running, you can check with adb devices if the emulator shows up. Then you can simply use react-native run-android to run the app on the emulator.

Make sure you've platform tools installed to be able to use adb. Or you can use

brew install android-platform-tools

Access parent URL from iframe

I've had issues with this. If using a language like php when your page first loads in the iframe grab $_SERVER['HTTP_REFFERER'] and set it to a session variable.

This way when the page loads in the iframe you know the full parent url and query string of the page that loaded it. With cross browser security it's a bit of a headache counting on window.parent anything if you you different domains.

Why doesn't list have safe "get" method like dictionary?

This works if you want the first element, like my_list.get(0)

>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'

I know it's not exactly what you asked for but it might help others.

A generic list of anonymous class

static void Main()
{
    List<int> list = new List<int>();
    list.Add(2);
    list.Add(3);
    list.Add(5);
    list.Add(7);
}

jQuery ajax error function

Try this:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

If you want to inform your frontend about a validation error, try to return json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {
   console.log(data.error);
}

Your asp script schould return:

{"error": true}

Django Template Variables and Javascript

Here is what I'm doing very easily: I modified my base.html file for my template and put that at the bottom:

{% if DJdata %}
    <script type="text/javascript">
        (function () {window.DJdata = {{DJdata|safe}};})();
    </script>
{% endif %}

then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)

Hope it helps!

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Root certificates issued by CAs are just self-signed certificates (which may in turn be used to issue intermediate CA certificates). They have not much special about them, except that they've managed to be imported by default in many browsers or OS trust anchors.

While browsers and some tools are configured to look for the trusted CA certificates (some of which may be self-signed) in location by default, as far as I'm aware the openssl command isn't.

As such, any server that presents the full chain of certificate, from its end-entity certificate (the server's certificate) to the root CA certificate (possibly with intermediate CA certificates) will have a self-signed certificate in the chain: the root CA.

openssl s_client -connect myweb.com:443 -showcerts doesn't have any particular reason to trust Verisign's root CA certificate, and because it's self-signed you'll get "self signed certificate in certificate chain".

If your system has a location with a bundle of certificates trusted by default (I think /etc/pki/tls/certs on RedHat/Fedora and /etc/ssl/certs on Ubuntu/Debian), you can configure OpenSSL to use them as trust anchors, for example like this:

openssl s_client -connect myweb.com:443 -showcerts -CApath /etc/ssl/certs

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

How to rename a directory/folder on GitHub website?

You could use a workflow for this.

# ./.github/workflows/rename.yaml
name: Rename Directory

on:
  push:

jobs:
  rename:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: git mv old_name new_name
      - uses: EndBug/[email protected]

Then just delete the workflow file, which you can do in the UI

How to pass parameters in GET requests with jQuery

Try adding this:

$.ajax({
    url: "ajax.aspx",
    type:'get',
    data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
    dataType: 'json',
    success: function(response) {
      //Do Something
    },
    error: function(xhr) {
    //Do Something to handle error
    }
});

Depends on what datatype is expected, you can assign html, json, script, xml

updating Google play services in Emulator

Running the app on a virtual device with system image, 'Google Play API' instead of 'Google API' will solve your issue smoothly..

  • Virtual devices Nexus 5x and Nexus 5 supports 'Google Play API' image.

  • Google Play API comes with Nougat 7.1.1 and O 8.0.

Just follow the below simple steps and make sure your pc is connected to internet.

  1. Create a new virtual device by selecting Create Virtual Device(left-bottom corner) from Android Virtual Devices Manager.

  2. Select the Hardware 'Nexus 5x' or 'Nexus 5'.

  3. Download the system image 'Nougat' with Google Play or 'O' with Google Play. 'O' is the latest Android 8.0 version.

  4. Click on Next and Finish.

  5. Run your app again on the new virtual device and click on the 'Upgrade now ' option that shows along with the warning message.

  6. You will be directed to the Play Store and you can update your Google Play services easily.

See your app runs smoothly!

  • Note: If you plan to use APIs from Google Play services, you must use the Google APIs System Image.

Render HTML string as real HTML in a React component

I could not get npm build to work with react-html-parser. However, in my case, I was able to successfully make use of https://reactjs.org/docs/fragments.html. I had a requirement to show few html unicode characters , but they should not be directly embedded in the JSX. Within the JSX, it had to be picked from the Component's state. Component code snippet is given below :

constructor() 
{
this.state = {
      rankMap : {"5" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9733;</Fragment> , 
                 "4" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9734;</Fragment>, 
                 "3" : <Fragment>&#9733; &#9733; &#9733; &#9734; &#9734;</Fragment> , 
                 "2" : <Fragment>&#9733; &#9733; &#9734; &#9734; &#9734;</Fragment>, 
                 "1" : <Fragment>&#9733; &#9734; &#9734; &#9734; &#9734;</Fragment>}
                };
}

render() 
{
       return (<div class="card-footer">
                    <small class="text-muted">{ this.state.rankMap["5"] }</small>
               </div>);
}

How to get cell value from DataGridView in VB.Net?

This helped me get close to what I needed and I will throw this out there for anyone else who needs it.

If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)

This will copy the result to the clipboard: Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)

Tests not running in Test Explorer

For me having a property called TestContext in a base class was causing this behavior. For example:

[TestClass]
public abstract class TestClassBase
{
    protected object TestContext { get; private set; }
}

[TestClass]
public class TestClass : TestClassBase
{
    // This method not found
    [TestMethod]
    public void TestCase() {}
}

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

fist get the certificate from the provider
create a file ends wirth .cer and pase the certificate

copy the text file or  past   it  somewhere you can access it 
then use the cmd prompt as an admin and cd to the bin of the jdk,
the cammand that will be used is the:  keytool 

change the  password of the keystore with :

keytool  -storepasswd -keystore "path of the key store from c\ and down"

the password is : changeit 
 then you will be asked to enter the new password twice 

then type the following :

keytool -importcert -file  "C:\Program Files\Java\jdk-13.0.2\lib\security\certificateFile.cer"   -alias chooseAname -keystore  "C:\Program Files\Java\jdk-13.0.2\lib\security\cacerts"

Passing functions with arguments to another function in Python?

You can use the partial function from functools like so.

from functools import partial

def perform(f):
    f()

perform(Action1)
perform(partial(Action2, p))
perform(partial(Action3, p, r))

Also works with keywords

perform(partial(Action4, param1=p))

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

This is the simplest way for an amateur like me who is studying C++ on their own:

First Unzip the boost library to any directory of your choice. I recommend c:\directory.

  1. Open your visual C++.
  2. Create a new project.
  3. Right click on the project.
  4. Click on property.
  5. Click on C/C++.
  6. Click on general.
  7. Select additional include library.
  8. Include the library destination. e.g. c:\boost_1_57_0.
  9. Click on pre-compiler header.
  10. Click on create/use pre-compiled header.
  11. Select not using pre-compiled header.

Then go over to the link library were you experienced your problems.

  1. Go to were the extracted file was c:\boost_1_57_0.
  2. Click on booststrap.bat (don't bother to type on the command window just wait and don't close the window that is the place I had my problem that took me two weeks to solve. After a while the booststrap will run and produce the same file, but now with two different names: b2, and bjam.
  3. Click on b2 and wait it to run.
  4. Click on bjam and wait it to run. Then a folder will be produce called stage.
  5. Right click on the project.
  6. Click on property.
  7. Click on linker.
  8. Click on general.
  9. Click on include additional library directory.
  10. Select the part of the library e.g. c:\boost_1_57_0\stage\lib.

And you are good to go!

How to get the root dir of the Symfony2 application?

UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...

Append an object to a list in R in amortized constant time, O(1)?

The OP (in the April 2012 updated revision of the question) is interested in knowing if there's a way to add to a list in amortized constant time, such as can be done, for example, with a C++ vector<> container. The best answer(s?) here so far only show the relative execution times for various solutions given a fixed-size problem, but do not address any of the various solutions' algorithmic efficiency directly. Comments below many of the answers discuss the algorithmic efficiency of some of the solutions, but in every case to date (as of April 2015) they come to the wrong conclusion.

Algorithmic efficiency captures the growth characteristics, either in time (execution time) or space (amount of memory consumed) as a problem size grows. Running a performance test for various solutions given a fixed-size problem does not address the various solutions' growth rate. The OP is interested in knowing if there is a way to append objects to an R list in "amortized constant time". What does that mean? To explain, first let me describe "constant time":

  • Constant or O(1) growth:

    If the time required to perform a given task remains the same as the size of the problem doubles, then we say the algorithm exhibits constant time growth, or stated in "Big O" notation, exhibits O(1) time growth. When the OP says "amortized" constant time, he simply means "in the long run"... i.e., if performing a single operation occasionally takes much longer than normal (e.g. if a preallocated buffer is exhausted and occasionally requires resizing to a larger buffer size), as long as the long-term average performance is constant time, we'll still call it O(1).

    For comparison, I will also describe "linear time" and "quadratic time":

  • Linear or O(n) growth:

    If the time required to perform a given task doubles as the size of the problem doubles, then we say the algorithm exhibits linear time, or O(n) growth.

  • Quadratic or O(n2) growth:

    If the time required to perform a given task increases by the square of the problem size, them we say the algorithm exhibits quadratic time, or O(n2) growth.

There are many other efficiency classes of algorithms; I defer to the Wikipedia article for further discussion.

I thank @CronAcronis for his answer, as I am new to R and it was nice to have a fully-constructed block of code for doing a performance analysis of the various solutions presented on this page. I am borrowing his code for my analysis, which I duplicate (wrapped in a function) below:

library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj} 
runBenchmark <- function(n) {
    microbenchmark(times = 5,  
        env_with_list_ = {
            listptr <- new.env(parent=globalenv())
            listptr$list <- NULL
            for(i in 1:n) {envAppendList(listptr, i)}
            listptr$list
        },
        c_ = {
            a <- list(0)
            for(i in 1:n) {a = c(a, list(i))}
        },
        list_ = {
            a <- list(0)
            for(i in 1:n) {a <- list(a, list(i))}
        },
        by_index = {
            a <- list(0)
            for(i in 1:n) {a[length(a) + 1] <- i}
            a
        },
        append_ = { 
            a <- list(0)    
            for(i in 1:n) {a <- append(a, i)} 
            a
        },
        env_as_container_ = {
            listptr <- new.env(parent=globalenv())
            for(i in 1:n) {lPtrAppend(listptr, i, i)} 
            listptr
        }   
    )
}

The results posted by @CronAcronis definitely seem to suggest that the a <- list(a, list(i)) method is fastest, at least for a problem size of 10000, but the results for a single problem size do not address the growth of the solution. For that, we need to run a minimum of two profiling tests, with differing problem sizes:

> runBenchmark(2e+3)
Unit: microseconds
              expr       min        lq      mean    median       uq       max neval
    env_with_list_  8712.146  9138.250 10185.533 10257.678 10761.33 12058.264     5
                c_ 13407.657 13413.739 13620.976 13605.696 13790.05 13887.738     5
             list_   854.110   913.407  1064.463   914.167  1301.50  1339.132     5
          by_index 11656.866 11705.140 12182.104 11997.446 12741.70 12809.363     5
           append_ 15986.712 16817.635 17409.391 17458.502 17480.55 19303.560     5
 env_as_container_ 19777.559 20401.702 20589.856 20606.961 20939.56 21223.502     5
> runBenchmark(2e+4)
Unit: milliseconds
              expr         min         lq        mean    median          uq         max neval
    env_with_list_  534.955014  550.57150  550.329366  553.5288  553.955246  558.636313     5
                c_ 1448.014870 1536.78905 1527.104276 1545.6449 1546.462877 1558.609706     5
             list_    8.746356    8.79615    9.162577    8.8315    9.601226    9.837655     5
          by_index  953.989076 1038.47864 1037.859367 1064.3942 1065.291678 1067.143200     5
           append_ 1634.151839 1682.94746 1681.948374 1689.7598 1696.198890 1706.683874     5
 env_as_container_  204.134468  205.35348  208.011525  206.4490  208.279580  215.841129     5
> 

First of all, a word about the min/lq/mean/median/uq/max values: Since we are performing the exact same task for each of 5 runs, in an ideal world, we could expect that it would take exactly the same amount of time for each run. But the first run is normally biased toward longer times due to the fact that the code we are testing is not yet loaded into the CPU's cache. Following the first run, we would expect the times to be fairly consistent, but occasionally our code may be evicted from the cache due to timer tick interrupts or other hardware interrupts that are unrelated to the code we are testing. By testing the code snippets 5 times, we are allowing the code to be loaded into the cache during the first run and then giving each snippet 4 chances to run to completion without interference from outside events. For this reason, and because we are really running the exact same code under the exact same input conditions each time, we will consider only the 'min' times to be sufficient for the best comparison between the various code options.

Note that I chose to first run with a problem size of 2000 and then 20000, so my problem size increased by a factor of 10 from the first run to the second.

Performance of the list solution: O(1) (constant time)

Let's first look at the growth of the list solution, since we can tell right away that it's the fastest solution in both profiling runs: In the first run, it took 854 microseconds (0.854 milliseconds) to perform 2000 "append" tasks. In the second run, it took 8.746 milliseconds to perform 20000 "append" tasks. A naïve observer would say, "Ah, the list solution exhibits O(n) growth, since as the problem size grew by a factor of ten, so did the time required to execute the test." The problem with that analysis is that what the OP wants is the growth rate of a single object insertion, not the growth rate of the overall problem. Knowing that, it's clear then that the list solution provides exactly what the OP wants: a method of appending objects to a list in O(1) time.

Performance of the other solutions

None of the other solutions come even close to the speed of the list solution, but it is informative to examine them anyway:

Most of the other solutions appear to be O(n) in performance. For example, the by_index solution, a very popular solution based on the frequency with which I find it in other SO posts, took 11.6 milliseconds to append 2000 objects, and 953 milliseconds to append ten times that many objects. The overall problem's time grew by a factor of 100, so a naïve observer might say "Ah, the by_index solution exhibits O(n2) growth, since as the problem size grew by a factor of ten, the time required to execute the test grew by a factor of 100." As before, this analysis is flawed, since the OP is interested in the growth of a single object insertion. If we divide the overall time growth by the problem's size growth, we find that the time growth of appending objects increased by a factor of only 10, not a factor of 100, which matches the growth of the problem size, so the by_index solution is O(n). There are no solutions listed which exhibit O(n2) growth for appending a single object.

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Difference between HashMap and Map in Java..?

HashMap is an implementation of Map. Map is just an interface for any type of map.

How can I check if mysql is installed on ubuntu?

"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".

Faster than rpm -qa | grep mysqld is:

which mysqld

How to redirect to Login page when Session is expired in Java web application?

You could use a Filter and do the following test:

HttpSession session = request.getSession(false);// don't create if it doesn't exist
if(session != null && !session.isNew()) {
    chain.doFilter(request, response);
} else {
    response.sendRedirect("/login.jsp");
}

The above code is untested.

This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. Be paranoid!

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between window.location.href and top.location.href

window.location.href returns the location of the current page.

top.location.href (which is an alias of window.top.location.href) returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window === window.top).

top is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html with the following script:

var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');

The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href would return.

To answer your question about redirecting, go with window.location.assign(url);

What's the difference between using "let" and "var"?

Scoping rules

Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo"
    let baz = "Bazz";
    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();

The reason why let keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.

Take a look at this example from another stackoverflow question:

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

My value: 3 was output to console each time funcs[j](); was invoked since anonymous functions were bound to the same variable.

People had to create immediately invoked functions to capture correct value from the loops but that was also hairy.

Hoisting

While variables declared with var keyword are hoisted (initialized with undefined before the code is run) which means they are accessible in their enclosing scope even before they are declared:

function run() {
  console.log(foo); // undefined
  var foo = "Foo";
  console.log(foo); // Foo
}

run();

let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in "temporal dead zone" from the start of the block until the initialization is processed.

function checkHoisting() {
  console.log(foo); // ReferenceError
  let foo = "Foo";
  console.log(foo); // Foo
}

checkHoisting();

Creating global object property

At the top level, let, unlike var, does not create a property on the global object:

var foo = "Foo";  // globally scoped
let bar = "Bar"; // globally scoped

console.log(window.foo); // Foo
console.log(window.bar); // undefined

Redeclaration

In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.

'use strict';
var foo = "foo1";
var foo = "foo2"; // No problem, 'foo' is replaced.

let bar = "bar1";
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared

Append Char To String in C?

In my case, this was the best solution I found:

snprintf(str, sizeof str, "%s%c", str, c);

cor shows only NA or 1 for correlations - Why?

The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.

How to correct TypeError: Unicode-objects must be encoded before hashing?

You must have to define encoding format like utf-8, Try this easy way,

This example generates a random number using the SHA256 algorithm:

>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'

Dynamic loading of images in WPF

This is strange behavior and although I am unable to say why this is occurring, I can recommend some options.

First, an observation. If you include the image as Content in VS and copy it to the output directory, your code works. If the image is marked as None in VS and you copy it over, it doesn't work.

Solution 1: FileStream

The BitmapImage object accepts a UriSource or StreamSource as a parameter. Let's use StreamSource instead.

        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = stream;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

The problem: stream stays open. If you close it at the end of this method, the image will not show up. This means that the file stays write-locked on the system.

Solution 2: MemoryStream

This is basically solution 1 but you read the file into a memory stream and pass that memory stream as the argument.

        MemoryStream ms = new MemoryStream();
        FileStream stream = new FileStream("picture.png", FileMode.Open, FileAccess.Read);
        ms.SetLength(stream.Length);
        stream.Read(ms.GetBuffer(), 0, (int)stream.Length);

        ms.Flush();
        stream.Close();

        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.StreamSource = ms;
        src.EndInit();
        i.Source = src;
        i.Stretch = Stretch.Uniform;
        panel.Children.Add(i);

Now you are able to modify the file on the system, if that is something you require.

Can I set background image and opacity in the same property?

Solution with 1 div and NO transparent image:

You can use the multibackground CSS3 feature and put two backgrounds: one with the image, another with a transparent panel over it (cause I think there's no way to set directly the opacity of the background image):

background: -moz-linear-gradient(top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.7) 100%), url(bg.png) repeat 0 0, url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -moz-linear-gradient(top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.7)), color-stop(100%,rgba(255,255,255,0.7))), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -webkit-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -o-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: -ms-linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

background: linear-gradient(to bottom, rgba(255,255,255,0.7) 0%,rgba(255,255,255,0.7) 100%), url(https://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png) repeat 0 0;

You can't use rgba(255,255,255,0.5) because alone it is only accepted on the back, so you I've used generated gradients for each browser for this example (that's why it is so long). But the concept is the following:

background: tranparentColor, url("myImage"); 

http://jsfiddle.net/pBVsD/1/

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Remove border from buttons

This seems to work for me perfectly.

button:focus { outline: none; }

How to find and replace all occurrences of a string recursively in a directory tree?

On macOS, none of the answers worked for me. I discovered that was due to differences in how sed works on macOS and other BSD systems compared to GNU.

In particular BSD sed takes the -i option but requires a suffix for the backup (but an empty suffix is permitted)

grep version from this answer.

grep -rl 'foo' ./ | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

find version from this answer.

find . \( ! -regex '.*/\..*' \) -type f | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

Don't omit the Regex to ignore . folders if you're in a Git repo. I realized that the hard way!

That LC_ALL=C option is to avoid getting sed: RE error: illegal byte sequence if sed finds a byte sequence that is not a valid UTF-8 character. That's another difference between BSD and GNU. Depending on the kind of files you are dealing with, you may not need it.

For some reason that is not clear to me, the grep version found more occurrences than the find one, which is why I recommend to use grep.

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

'Source code does not match the bytecode' when debugging on a device

This is the steps that worked for me (For both Mac and Windows):

  1. Click on "File"
  2. Click on "Invalidate Caches / Restart ..."
  3. Choose: "Invalidate and Restart"
  4. Wait for 20 minutes

React-Native: Application has not been registered error

I think the node server is running from another folder. So kill it and run in the current folder.

Find running node server:-

lsof -i :8081

Kill running node server :-

kill -9 <PID>

Eg:-

kill -9 1653

Start node server from current react native folder:-

react-native run-android

How to check type of files without extensions in python?

also you can use this code (pure python by 3 byte of header file):

full_path = os.path.join(MEDIA_ROOT, pathfile)

try:
    image_data = open(full_path, "rb").read()
except IOError:
    return "Incorrect Request :( !!!"

header_byte = image_data[0:3].encode("hex").lower()

if header_byte == '474946':
    return "image/gif"
elif header_byte == '89504e':
    return "image/png"
elif header_byte == 'ffd8ff':
    return "image/jpeg"
else:
    return "binary file"

without any package install [and update version]

trying to align html button at the center of the my page

You can center a button without using text-align on the parent div by simple using margin:auto; display:block;

For example:

HTML

<div>
  <button>Submit</button>
</div>

CSS

button {
  margin:auto;
  display:block;
}

SEE IT IN ACTION: CodePen

How to check if a string contains a substring in Bash

Exact word match:

string='My long string'
exactSearch='long'

if grep -E -q "\b${exactSearch}\b" <<<${string} >/dev/null 2>&1
  then
    echo "It's there"
  fi

How to detect the OS from a Bash script?

I tried the above messages across a few Linux distros and found the following to work best for me. It’s a short, concise exact word answer that works for Bash on Windows as well.

OS=$(cat /etc/*release | grep ^NAME | tr -d 'NAME="') #$ echo $OS # Ubuntu

How do I compile a Visual Studio project from the command-line?

MSBuild usually works, but I've run into difficulties before. You may have better luck with

devenv YourSolution.sln /Build 

SQLAlchemy default DateTime

As per PostgreSQL documentation, https://www.postgresql.org/docs/9.6/static/functions-datetime.html

now, CURRENT_TIMESTAMP, LOCALTIMESTAMP return the time of transaction.

This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.

You might want to use statement_timestamp or clock_timestamp if you don't want transaction timestamp.

statement_timestamp()

returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp

clock_timestamp()

returns the actual current time, and therefore its value changes even within a single SQL command.

How do I compare two Integers?

Minor note: since Java 1.7 the Integer class has a static compare(Integer, Integer) method, so you can just call Integer.compare(x, y) and be done with it (questions about optimization aside).

Of course that code is incompatible with versions of Java before 1.7, so I would recommend using x.compareTo(y) instead, which is compatible back to 1.2.

Getting the actual usedrange

This function returns the actual used range to the lower right limit. It returns "Nothing" if the sheet is empty.

'2020-01-26
Function fUsedRange() As Range
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim rngLastCell As Range
    On Error Resume Next
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in rows
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastRow = rngLastCell.Row
    End If
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in columns
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastCol = rngLastCell.Column
    End If
    Set fUsedRange = ActiveSheet.Range(Cells(1, 1), Cells(lngLastRow, lngLastCol))  'set up range
End Function

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I'd use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos fork also has the ability to work directly with multiple argument functions, as you need for class methods.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
... 
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>> 
>>> class Foo(object):
...   @staticmethod
...   def work(self, x):
...     return x+1
... 
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101

Get pathos (and if you like, dill) here: https://github.com/uqfoundation

npm start error with create-react-app

For me it was simply that I hadn't added react-scripts to the project so:

npm i -S react-scripts

If this doesn't work, then rm node_modules as suggested by others

rm -r node_modules
npm i

How do I request and receive user input in a .bat and use it to run a certain program?

Depending on the version of Windows you might find the use of the "Choice" option to be helpful. It is not supported in most if not all x64 versions as far as I can tell. A handy substitution called Choice.vbs along with examples of use can be found on SourceForge under the name Choice.zip

Can you do a partial checkout with Subversion?

Not in any especially useful way, no. You can check out subtrees (as in Bobby Jack's suggestion), but then you lose the ability to update/commit them atomically; to do that, they need to be placed under their common parent, and as soon as you check out the common parent, you'll download everything under that parent. Non-recursive isn't a good option, because you want updates and commits to be recursive.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

How to convert JSON string to array

Make sure that the string is in the following JSON format which is something like this:

{"result":"success","testid":"1"} (with " ") .

If not, then you can add "responsetype => json" in your request params.

Then use json_decode($response,true) to convert it into an array.

Create an array of strings

Another option:

names = repmat({'Sample Text'}, 10, 1)

How can I cast int to enum?

enter image description here

To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.

The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

Change background color for selected ListBox item

If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.

In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.

Here is a skeleton of how the markup should look:

    <ScrollViewer>
        <ItemsControl>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    ...
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>

How to set max width of an image in CSS

Try this

 div#ImageContainer { width: 600px; }
 #ImageContainer img{ max-width: 600px}

Difference between JE/JNE and JZ/JNZ

  je : Jump if equal:

  399  3fb:   64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  400  402:   00 00
  401  404:   74 05                   je     40b <sims_get_counter+0x51>

Detect Scroll Up & Scroll down in ListView

Simple way to detect scroll up/down on android listview

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
  if(prevVisibleItem != firstVisibleItem){
    if(prevVisibleItem < firstVisibleItem)
      //ScrollDown
    else
      //ScrollUp

  prevVisibleItem = firstVisibleItem;
}

dont forget

yourListView.setOnScrollListener(yourScrollListener);

How to get duration, as int milli's and float seconds from <chrono>?

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

Replacement for deprecated sizeWithFont: in iOS 7?

Building on @bitsand, this is a new method I just added to my NSString+Extras category:

- (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
{
    // set paragraph style
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:lineBreakMode];

    // make dictionary of attributes with paragraph style
    NSDictionary *sizeAttributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};

    CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];

    /*
    // OLD
    CGSize stringSize = [self sizeWithFont:font
                              constrainedToSize:constraintSize
                                  lineBreakMode:lineBreakMode];
    // OLD
    */

    return frame;
}

I just use the size of the resulting frame.

System.loadLibrary(...) couldn't find native library in my case

please add all suport

app/build.gradle

ndk {
        moduleName "serial_port"
        ldLibs "log", "z", "m"
        abiFilters "arm64-v8a","armeabi", "armeabi-v7a", "x86","x86_64","mips","mips64"
}

app\src\jni\Application.mk

APP_ABI := arm64-v8a armeabi armeabi-v7a x86 x86_64 mips mips64

Preferred way to create a Scala list

To create a list of string, use the following:

val l = List("is", "am", "are", "if")

How can I remove the decimal part from JavaScript number?

If you don't care about rouding, just convert the number to a string, then remove everything after the period including the period. This works whether there is a decimal or not.

const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];

Identifying country by IP address

Yes, countries have specific IP address ranges as you mentioned.

For example, Australia is between 16777216 - 16777471. China is between 16777472 - 16778239. But one country may have multiple ranges. For example, Australia also has this range between 16778240 - 16779263

(These are numerical conversions of IP addresses. It depends whether you use IPv4 or IPv6)

More information about these ranges can be seen here: http://software77.net/cidr-101.html

We get the ip addresses of our website visitors and sometimes want to make relevant campaign for a specific country. We were using bulk conversion tools but later on decided to define the rules in an Excel file and convert it in the tool. And we have built this Excel template: https://www.someka.net/excel-template/ip-to-country-converter/

Now we use this for our own needs and also sell it. I don't want it to be a sales pitch but for those who are looking for an easy solution can benefit from this.

Where do I put image files, css, js, etc. in Codeigniter?

I usually put all my files like that into an "assets" folder in the application root, and then I make sure to use an Asset_Helper to point to those files for me. This is what CodeIgniter suggests.

How to display a readable array - Laravel

Maybe try kint: composer require raveren/kint "dev-master" More information: Why is my debug data unformatted?

Which selector do I need to select an option by its text?

This works for me

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

Thanks for all the posts.

Select All as default value for Multivalue parameter

It works better

CREATE TABLE [dbo].[T_Status](
   [Status] [nvarchar](20) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO

DECLARE @GetStatus nvarchar(20) = null
--DECLARE @GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE  [Status] = CASE WHEN (isnull(@GetStatus, '')='') THEN [Status]
ELSE @GetStatus END

CSS Input with width: 100% goes outside parent's bound

If all above fail, try setting the following properties for your input, to have it take max space but not overflow:

input {
    min-width: 100%;
    max-width: 100%;
}

"Could not find Developer Disk Image"

If you want to develop with Xcode 7 on your iOS10 device :
(Note: you can adapt this command to other Xcode and iOS versions)

  1. Rename your Xcode.app to Xcode7.app and download Xcode 8 from the app store.
  2. Run Xcode 8 once to install it.
  3. Open the terminal and create a symbolic link from Xcode 8 Developer Disk Image 10.0 to Xcode 8 Developer Disk Image folder using this command:

    ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0\ \(14A345\)/ /Applications/Xcode7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
    

Source

Loop through an array of strings in Bash?

If you are using Korn shell, there is "set -A databaseName ", else there is "declare -a databaseName"

To write a script working on all shells,

 set -A databaseName=("db1" "db2" ....) ||
        declare -a databaseName=("db1" "db2" ....)
# now loop 
for dbname in "${arr[@]}"
do
   echo "$dbname"  # or whatever

done

It should be work on all shells.

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

Converting a generic list to a CSV string

I like a nice simple extension method

 public static string ToCsv(this List<string> itemList)
         {
             return string.Join(",", itemList);
         }

Then you can just call the method on the original list:

string CsvString = myList.ToCsv();

Cleaner and easier to read than some of the other suggestions.

How do I specify different layouts for portrait and landscape orientations?

For Mouse lovers! I say right click on resources folder and Add new resource file, and from Available qualifiers select the orientation :

enter image description here


But still you can do it manually by say, adding the sub-folder "layout-land" to

"Your-Project-Directory\app\src\main\res"

since then any layout.xml file under this sub-folder will only work for landscape mode automatically.

Use "layout-port" for portrait mode.

Why is Visual Studio 2010 not able to find/open PDB files?

I'm pretty sure those are warnings, not errors. Your project should still run just fine.

However, since you should always try to fix compiler warnings, let's see what we can discover. I'm not at all familiar with OpenCV, and you don't link to the wiki tutorial that you're following. But it looks to me like the problem is that you're running a 64-bit version of Windows (as evidenced by the "SysWOW64" folder in the path to the DLL files), but the OpenCV stuff that you're trying is built for a 32-bit platform. So you might need to rebuild the project using CMake, as explained here.

More specifically, the files that are listed are Windows system files. PDB files contain debugging information that Visual Studio uses to allow you to step into and debug compiled code. You don't actually need the PDB files for system libraries to be able to debug your own code. But if you want, you can download the symbols for the system libraries as well. Go to the "Debug" menu, click on "Options and Settings", and scroll down the listbox on the right until you see "Enable source server support". Make sure that option is checked. Then, in the treeview to the left, click on "Symbols", and make sure that the "Microsoft Symbol Servers" option is selected. Click OK to dismiss the dialog, and then try rebuilding.

Order by in Inner Join

You have to sort it if you want the data to come back a certain way. When you say you are expecting "Mohit" to be the first row, I am assuming you say that because "Mohit" is the first row in the [One] table. However, when SQL Server joins tables, it doesn't necessarily join in the order you think.

If you want the first row from [One] to be returned, then try sorting by [One].[ID]. Alternatively, you can order by any other column.

isset() and empty() - what to use

It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset.

Empty checks if the variable is set and if it is it checks it for null, "", 0, etc

Isset just checks if is it set, it could be anything not null

With empty, the following things are considered empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

From http://php.net/manual/en/function.empty.php


As mentioned in the comments the lack of warning is also important with empty()

PHP Manual says

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

Regarding isset

PHP Manual says

isset() will return FALSE if testing a variable that has been set to NULL


Your code would be fine as:

<?php
    $var = '23';
    if (!empty($var)){
        echo 'not empty';
    }else{
        echo 'is not set or empty';
    }
?>

For example:

$var = "";

if(empty($var)) // true because "" is considered empty
 {...}
if(isset($var)) //true because var is set 
 {...}

if(empty($otherVar)) //true because $otherVar is null
 {...}
if(isset($otherVar)) //false because $otherVar is not set 
 {...}

Best way to randomize an array with .NET

This algorithm is simple but not efficient, O(N2). All the "order by" algorithms are typically O(N log N). It probably doesn't make a difference below hundreds of thousands of elements but it would for large lists.

var stringlist = ... // add your values to stringlist

var r = new Random();

var res = new List<string>(stringlist.Count);

while (stringlist.Count >0)
{
   var i = r.Next(stringlist.Count);
   res.Add(stringlist[i]);
   stringlist.RemoveAt(i);
}

The reason why it's O(N2) is subtle: List.RemoveAt() is a O(N) operation unless you remove in order from the end.

CSS flexbox not working in IE10

IE10 has uses the old syntax. So:

display: -ms-flexbox; /* will work on IE10 */
display: flex; /* is new syntax, will not work on IE10 */

see css-tricks.com/snippets/css/a-guide-to-flexbox:

(tweener) means an odd unofficial syntax from [2012] (e.g. display: flexbox;)

How to set an iframe src attribute from a variable in AngularJS

select template; iframe controller, ng model update

index.html

angularapp.controller('FieldCtrl', function ($scope, $sce) {
        var iframeclass = '';
        $scope.loadTemplate = function() {
            if ($scope.template.length > 0) {
                // add iframe classs
                iframeclass = $scope.template.split('.')[0];
                iframe.classList.add(iframeclass);
                $scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
            } else {
                iframe.classList.remove(iframeclass);
            };
        };

    });
    // custom directive
    angularapp.directive('myChange', function() {
        return function(scope, element) {
            element.bind('input', function() {
                // the iframe function
                iframe.contentWindow.update({
                    name: element[0].name,
                    value: element[0].value
                });
            });
        };
    });

iframe.html

   window.update = function(data) {
        $scope.$apply(function() {
            $scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
        });
    };

Check this link: http://plnkr.co/edit/TGRj2o?p=preview

Check if an element is present in an array

Just use indexOf:

haystack.indexOf(needle) >= 0

If you want to support old Internet Explorers (< IE9), you'll have to include your current code as a workaround though.

Unless your list is sorted, you need to compare every value to the needle. Therefore, both your solution and indexOf will have to execute n/2 comparisons on average. However, since indexOf is a built-in method, it may use additional optimizations and will be slightly faster in practice. Note that unless your application searches in lists extremely often (say a 1000 times per second) or the lists are huge (say 100k entries), the speed difference will not matter.

Should have subtitle controller already set Mediaplayer error Android

A developer recently added subtitle support to VideoView.

When the MediaPlayer starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set. It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.

Short answer: Don't care about this "Exception".


Edit :

Still present in Lollipop,

If MediaPlayer is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController to the MediaPlayer.

It should not be used in production environment and may have some side effects.

static MediaPlayer getMediaPlayer(Context context){

    MediaPlayer mediaplayer = new MediaPlayer();

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
        return mediaplayer;
    }

    try {
        Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
        Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
        Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
        Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );

        Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});

        Object subtitleInstance = constructor.newInstance(context, null, null);

        Field f = cSubtitleController.getDeclaredField("mHandler");

        f.setAccessible(true);
        try {
            f.set(subtitleInstance, new Handler());
        }
        catch (IllegalAccessException e) {return mediaplayer;}
        finally {
            f.setAccessible(false);
        }

        Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);

        setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        //Log.e("", "subtitle is setted :p");
    } catch (Exception e) {}

    return mediaplayer;
}

This code is trying to do the following from the hidden API

SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)

login to remote using "mstsc /admin" with password

to be secured, you should execute 3 commands :

cmdkey /generic:"server-address" /user:"username" /pass:"password"
mstsc /v:server-address
cmdkey /delete:server-address

first command to save the credential

second command to open remote desktop

and the third command to delete the credential

all of these commands can be saved in a batch file(bat).

WAMP 403 Forbidden message on Windows 7

This configuration in httpd.conf work fine for me.

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1 ::1
</Directory>

Understanding the main method of python

The Python approach to "main" is almost unique to the language(*).

The semantics are a bit subtle. The __name__ identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__ is set to "__main__" (the literal string: __main__).

This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.

It's important to understand that all of the code above the if __name__ line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print statement before the if __name__ line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__" to isolate a block of code which calls a suite of unit tests that apply to this module.

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

Summary: if __name__ == '__main__': has two primary use cases:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.

It's fairly common to def main(*args) and have if __name__ == '__main__': simply call main(*sys.argv[1:]) if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module() and calling test_module() in your if __name__ == '__main__:' suite.

  • (Ruby also implements a similar feature if __file__ == $0).

Replace new line/return with space using regex

I found this.

String newString = string.replaceAll("\n", " ");

Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.

If that doesn't work try doing:

string.replaceAll(System.getProperty("line.separator"), " ");

If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

How to redirect both stdout and stderr to a file

Please use command 2>file Here 2 stands for file descriptor of stderr. You can also use 1 instead of 2 so that stdout gets redirected to the 'file'

How to import a csv file using python with headers intact, where first column is a non-numerical

Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.

Assuming your file is named myclone.csv and contains

workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0

this code should give you an idea or two:

>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
...    column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
...   for h, v in zip(headers, row):
...     column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>

To get your numeric values into floats, add this

converters = [str.strip] + [float] * (len(headers) - 1)

up front, and do this

for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

for each row instead of the similar two lines above.

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

Get and Set a Single Cookie with Node.js HTTP Server

RevNoah had the best answer with the suggestion of using Express's cookie parser. But, that answer is now 3 years old and is out of date.

Using Express, you can read a cookie as follows

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/myapi', function(req, resp) {
   console.log(req.cookies['Your-Cookie-Name-Here']);
})

And update your package.json with the following, substituting the appropriate relatively latest versions.

"dependencies": {
    "express": "4.12.3",
    "cookie-parser": "1.4.0"
  },

More operations like setting and parsing cookies are described here and here

python: get directory two levels up

Assuming you want to access folder named xzy two folders up your python file. This works for me and platform independent.

".././xyz"

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

For ChromeDriver the below worked for me:

string chromeDriverDirectory = "C:\\temp\\2.37";
 var options = new ChromeOptions();
 options.AddArgument("-no-sandbox");
 driver = new ChromeDriver(chromeDriverDirectory, options, 
 TimeSpan.FromMinutes(2));

Selenium version 3.11, ChromeDriver 2.37

How to change the server port from 3000?

In package.json set the following command (example for running on port 82)

"start": "set PORT=82 && ng serve --ec=true"

then npm start

copy db file with adb pull results in 'permission denied' error

  1. Create a folder in sdcard :
adb shell "su 0 mkdir /sdcard/com.test"
  1. Move your files to the new folder :
adb shell "su 0 mv -F /data/data/com.test/files/ /sdcard/com.test/"
  1. You can now use adb pull :
adb pull /sdcard/com.test

Java Programming: call an exe from Java and passing parameters

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();

How to convert CLOB to VARCHAR2 inside oracle pl/sql

ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;

ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;

Converting char* to float or double

printf("price: %d, %f",temp,ftemp); 
              ^^^

This is your problem. Since the arguments are type double and float, you should be using %f for both (since printf is a variadic function, ftemp will be promoted to double).

%d expects the corresponding argument to be type int, not double.

Variadic functions like printf don't really know the types of the arguments in the variable argument list; you have to tell it with the conversion specifier. Since you told printf that the first argument is supposed to be an int, printf will take the next sizeof (int) bytes from the argument list and interpret it as an integer value; hence the first garbage number.

Now, it's almost guaranteed that sizeof (int) < sizeof (double), so when printf takes the next sizeof (double) bytes from the argument list, it's probably starting with the middle byte of temp, rather than the first byte of ftemp; hence the second garbage number.

Use %f for both.

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

How to get the latest tag name in current branch in Git?

git log --tags --no-walk --pretty="format:%d" | sed 2q | sed 's/[()]//g' | sed s/,[^,]*$// | sed  's ......  '

IF YOU NEED MORE THAN ONE LAST TAG

(git describe --tags sometimes gives wrong hashes, i dont know why, but for me --max-count 2 doesnt work)

this is how you can get list with latest 2 tag names in reverse chronological order, works perfectly on git 1.8.4. For earlier versions of git(like 1.7.*), there is no "tag: " string in output - just delete last sed call

If you want more than 2 latest tags - change this "sed 2q" to "sed 5q" or whatever you need

Then you can easily parse every tag name to variable or so.

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name 
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)

I haven't executed it, so there may be a syntax error or two there.

How do I pass a method as a parameter in Python

Methods are objects like any other. So you can pass them around, store them in lists and dicts, do whatever you like with them. The special thing about them is they are callable objects so you can invoke __call__ on them. __call__ gets called automatically when you invoke the method with or without arguments so you just need to write methodToRun().

AngularJS: Service vs provider vs factory

Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider.

HTML:

<div ng-controller="mainCtrl as main">
    <h1>{{main.title}}*</h1>
    <h2>{{main.strapline}}</h2>
    <p>Earn {{main.earn}} per click</p>
    <p>You've earned {{main.earned}} by clicking!</p>
    <button ng-click="main.handleClick()">Click me to earn</button>
    <small>* Not actual money</small>
</div>

app

var app = angular.module('angularProviders', []);

// A CONSTANT is not going to change
app.constant('range', 100);

// A VALUE could change, but probably / typically doesn't
app.value('title', 'Earn money by clicking');
app.value('strapline', 'Adventures in ng Providers');

// A simple FACTORY allows us to compute a value @ runtime.
// Furthermore, it can have other dependencies injected into it such
// as our range constant.
app.factory('random', function randomFactory(range) {
    // Get a random number within the range defined in our CONSTANT
    return Math.random() * range;
});

// A PROVIDER, must return a custom type which implements the functionality 
// provided by our service (see what I did there?).
// Here we define the constructor for the custom type the PROVIDER below will 
// instantiate and return.
var Money = function(locale) {

    // Depending on locale string set during config phase, we'll
    // use different symbols and positioning for any values we 
    // need to display as currency
    this.settings = {
        uk: {
            front: true,
            currency: '£',
            thousand: ',',
            decimal: '.'
        },
        eu: {
            front: false,
            currency: '€',
            thousand: '.',
            decimal: ','
        }
    };

    this.locale = locale;
};

// Return a monetary value with currency symbol and placement, and decimal 
// and thousand delimiters according to the locale set in the config phase.
Money.prototype.convertValue = function(value) {

    var settings = this.settings[this.locale],
        decimalIndex, converted;

    converted = this.addThousandSeparator(value.toFixed(2), settings.thousand);

    decimalIndex = converted.length - 3;

    converted = converted.substr(0, decimalIndex) +
        settings.decimal +
        converted.substr(decimalIndex + 1);    

    converted = settings.front ?
            settings.currency + converted : 
            converted + settings.currency; 

    return converted;   
};

// Add supplied thousand separator to supplied value
Money.prototype.addThousandSeparator = function(value, symbol) {
   return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol);
};

// PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY
// are all effectively syntactic sugar built on top of the PROVIDER construct
// One of the advantages of the PROVIDER is that we can configure it before the
// application starts (see config below).
app.provider('money', function MoneyProvider() {

    var locale;

    // Function called by the config to set up the provider
    this.setLocale = function(value) {
        locale = value;   
    };

    // All providers need to implement a $get method which returns
    // an instance of the custom class which constitutes the service
    this.$get = function moneyFactory() {
        return new Money(locale);
    };
});

// We can configure a PROVIDER on application initialisation.
app.config(['moneyProvider', function(moneyProvider) {
    moneyProvider.setLocale('uk');
    //moneyProvider.setLocale('eu'); 
}]);

// The ubiquitous controller
app.controller('mainCtrl', function($scope, title, strapline, random, money) {

    // Plain old VALUE(s)
    this.title = title;
    this.strapline = strapline;

    this.count = 0;

    // Compute values using our money provider    
    this.earn = money.convertValue(random); // random is computed @ runtime
    this.earned = money.convertValue(0);

    this.handleClick = function() { 
        this.count ++;
        this.earned = money.convertValue(random * this.count);
    };
});

Working demo.

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Extract Data from PDF and Add to Worksheet

Copying and pasting by user interactions emulation could be not reliable (for example, popup appears and it switches the focus). You may be interested in trying the commercial ByteScout PDF Extractor SDK that is specifically designed to extract data from PDF and it works from VBA. It is also capable of extracting data from invoices and tables as CSV using VB code.

Here is the VBA code for Excel to extract text from given locations and save them into cells in the Sheet1:

Private Sub CommandButton1_Click()

' Create TextExtractor object
' Set extractor = CreateObject("Bytescout.PDFExtractor.TextExtractor")
Dim extractor As New Bytescout_PDFExtractor.TextExtractor

extractor.RegistrationName = "demo"
extractor.RegistrationKey = "demo"

' Load sample PDF document
extractor.LoadDocumentFromFile ("c:\sample1.pdf")

' Get page count
pageCount = extractor.GetPageCount()

Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng  As Range

Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")

For i = 0 To pageCount - 1
            RectLeft = 10
            RectTop = 10
            RectWidth = 100
            RectHeight = 100

            ' check the same text is extracted from returned coordinates
            extractor.SetExtractionArea RectLeft, RectTop, RectWidth, RectHeight
            ' extract text from given area
            extractedText = extractor.GetTextFromPage(i)

            ' insert rows
            ' Rows(1).Insert shift:=xlShiftDown
            ' write cell value
             Set TxtRng = ws.Range("A" & CStr(i + 2))
             TxtRng.Value = extractedText

Next

Set extractor = Nothing


End Sub

Disclosure: I am related to ByteScout

Specifying a custom DateTime format when serializing with Json.Net

You could use this approach:

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use it this way:

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}

The DateTimeFormat string uses the .NET format string syntax described here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

Jquery Setting Value of Input Field

change your jquery loading setting to onload in jsfiddle . . .it works . . .

Static linking vs dynamic linking

Static linking is a process in compile time when a linked content is copied into the primary binary and becomes a single binary.

Cons:

  • compile time is longer
  • output binary is bigger

Dynamic linking is a process in runtime when a linked content is loaded. This technic allows to:

  • upgrade linked binary without recompiling a primary one that increase an ABI stability[About]
  • has a single shared copy

Cons:

  • start time is slower(linked content should be copied)
  • linker errors are thrown in runtime

[iOS Static vs Dynamic framework]

Nesting await in Parallel.ForEach

An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
    {
        if (maxDegreeOfParallelism.HasValue)
        {
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
            {
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                {
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                    {
                        await action(item).ContinueWith(res =>
                        {
                            // action is completed, so decrement the number of currently running tasks
                            semaphoreSlim.Release();
                        });
                    }));
                }

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            }
        }
        else
        {
            await Task.WhenAll(enumerable.Select(item => action(item)));
        }
    }

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
    {
        await SomeAsyncMethod(item);
    },
    5);

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

How to check if array element exists or not in javascript?

I had to wrap techfoobar's answer in a try..catch block, like so:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

...that's how it worked in chrome, anyway (otherwise, the code stopped with an error).