Programs & Examples On #Objectoutputstream

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Parcelable encountered IOException writing serializable object getactivity()

if you POJO contains any other model inside that should also implements Serializable

How to write and read java serialized objects into a file

if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

Serialization:

LinkedList<YourObject> listOfObjects = <something>;
try {
    FileOutputStream file = new FileOutputStream(<filePath>);
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourObject obj : listOfObjects) {
        writer.writeObject(obj);
    }
    writer.close();
    file.close();
} catch (Exception ex) {
    System.err.println("failed to write " + filePath + ", "+ ex);
}

De-serialization:

try {
    FileInputStream file = new FileInputStream(<filePath>);
    ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try { 
            YourObject obj = (YourObject)reader.readObject();
            System.out.println(obj)
        } catch (Exception ex) {
            System.err.println("end of reader file ");
            break;
        }
    }
} catch (Exception ex) {
    System.err.println("failed to read " + filePath + ", "+ ex);
}

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

Listen to port via a Java socket

You need to use a ServerSocket. You can find an explanation here.

Why java.security.NoSuchProviderException No such provider: BC?

You can add security provider by editing java.security with using following code with creating static block:

static {
    Security.addProvider(new BouncyCastleProvider());
}

If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
</dependency>

If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.

http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm

java.io.StreamCorruptedException: invalid stream header: 7371007E

If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[] or List. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.

EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.

Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.

(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)

To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.

How to serialize an object into a string

XStream provides a simple utility for serializing/deserializing to/from XML, and it's very quick. Storing XML CLOBs rather than binary BLOBS is going to be less fragile, not to mention more readable.

Efficient way to remove keys with empty strings from a dict

Some benchmarking:

1. List comprehension recreate dict

In [7]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
   ...: dic = {k: v for k, v in dic.items() if v is not None} 
   1000000 loops, best of 7: 375 ns per loop

2. List comprehension recreate dict using dict()

In [8]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
   ...: dic = dict((k, v) for k, v in dic.items() if v is not None)
1000000 loops, best of 7: 681 ns per loop

3. Loop and delete key if v is None

In [10]: %%timeit dic = {str(i):i for i in xrange(10)}; dic['10'] = None; dic['5'] = None
    ...: for k, v in dic.items():
    ...:   if v is None:
    ...:     del dic[k]
    ...: 
10000000 loops, best of 7: 160 ns per loop

so loop and delete is the fastest at 160ns, list comprehension is half as slow at ~375ns and with a call to dict() is half as slow again ~680ns.

Wrapping 3 into a function brings it back down again to about 275ns. Also for me PyPy was about twice as fast as neet python.

How to get cumulative sum

The SQL solution wich combines "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" and "SUM" did exactly what i wanted to achieve. Thank you so much!

If it can help anyone, here was my case. I wanted to cumulate +1 in a column whenever a maker is found as "Some Maker" (example). If not, no increment but show previous increment result.

So this piece of SQL:

SUM( CASE [rmaker] WHEN 'Some Maker' THEN  1 ELSE 0 END) 
OVER 
(PARTITION BY UserID ORDER BY UserID,[rrank] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cumul_CNT

Allowed me to get something like this:

User 1  Rank1   MakerA      0  
User 1  Rank2   MakerB      0  
User 1  Rank3   Some Maker  1  
User 1  Rank4   Some Maker  2  
User 1  Rank5   MakerC      2
User 1  Rank6   Some Maker  3  
User 2  Rank1   MakerA      0  
User 2  Rank2   SomeMaker   1  

Explanation of above: It starts the count of "some maker" with 0, Some Maker is found and we do +1. For User 1, MakerC is found so we dont do +1 but instead vertical count of Some Maker is stuck to 2 until next row. Partitioning is by User so when we change user, cumulative count is back to zero.

I am at work, I dont want any merit on this answer, just say thank you and show my example in case someone is in the same situation. I was trying to combine SUM and PARTITION but the amazing syntax "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" completed the task.

Thanks! Groaker

Split a string by another string in C#

There's an overload of String.Split for this:

"THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How do I install cURL on Windows?

You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.

Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.

Enable the extension

You're done :-)

Can dplyr package be used for conditional mutating?

case_when is now a pretty clean implementation of the SQL-style case when:

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
8L), class = "data.frame") -> df


df %>% 
    mutate( g = case_when(
                a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
))

Using dplyr 0.7.4

The manual: http://dplyr.tidyverse.org/reference/case_when.html

How do you change library location in R?

This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

export R_LIBS="~/R/lib"

See R admin guide on complete list of options.

Configuring so that pip install can work from github

I had similar issue when I had to install from github repo, but did not want to install git , etc.

The simple way to do it is using zip archive of the package. Add /zipball/master to the repo URL:

    $ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
  Downloading master
  Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
  Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...

This way you will make pip work with github source repositories.

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

EDIT: the answer below would apply in most cases. OP however later mentioned that they could not edit anything other than the CSS file. But will leave this here so it may be of use to others.

enter image description here

The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.

You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.

In an example that I made, I targeted all <p> elements with jQuery and wrapped it with a div with a class of "colored"

$( "p" ).wrap( "<div class='colored'></div>" );

Then in my CSS i targeted the <p> and gave it the background color and changed to display: inline

.colored p {
    display: inline;
    background: green;
}

By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

tr:hover not working

Works fine for me... The tr:hover should work. Probably it won't work because:

  1. The background color you have set is very light. You don't happen to use this on a white background, do you?

  2. Your <td> tags are not closed properly.

Please note that hovering a <tr> will not work in older browsers.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

In my case I was using a custom extension for my PHP files and I had to edit /etc/apache2/conf-available/php7.2-fpm.conf and add the following code:

    <FilesMatch ".+\.YOUR_CUSTOM_EXTENSION$">
        SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
    </FilesMatch>

How to set python variables to true or false?

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Running AMP (apache mysql php) on Android

In PHP I use Server For PHP app in playstore, for MySql I use MariaDB Server, and to connect to MariaDB with PHP 7 use this code:

<?php
$your_variable = mysqli_connect('your hostname', 'root(default)', 'leave this empty', 'the database you want to connect');
?>

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Opening popup windows in HTML

I feel like this is the simplest way. (Feel free to change the width and height values).

<a href="http://www.google.com" 
target="popup" 
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>

Is it possible only to declare a variable without assigning any value in Python?

I'd heartily recommend that you read Other languages have "variables" (I added it as a related link) – in two minutes you'll know that Python has "names", not "variables".

val = None
# ...
if val is None:
   val = any_object

Calculating percentile of dataset column

If you order a vector x, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.

x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

For me it was only crashing with this error on a production environment, not on local machine; what solved it was to delete the content of /bin folder and then to regenerate it again.

How to create an array for JSON using PHP?

Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.

After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.

$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';

... etc.

After that.

json_encode($associativeArray);

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

Avoid dropdown menu close on click inside

I also found a solution.

Assuming that the Twitter Bootstrap Components related events handlers are delegated to the document object, I loop the attached handlers and check if the current clicked element (or one of its parents) is concerned by a delegated event.

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){
    var events = $._data(document, 'events') || {};
    events = events.click || [];
    for(var i = 0; i < events.length; i++) {
        if(events[i].selector) {

            //Check if the clicked element matches the event selector
            if($(event.target).is(events[i].selector)) {
                events[i].handler.call(event.target, event);
            }

            // Check if any of the clicked element parents matches the 
            // delegated event selector (Emulating propagation)
            $(event.target).parents(events[i].selector).each(function(){
                events[i].handler.call(this, event);
            });
        }
    }
    event.stopPropagation(); //Always stop propagation
});

Hope it helps any one looking for a similar solution.

Thank you all for your help.

TypeScript static classes

TypeScript is not C#, so you shouldn't expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes?

In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however.

If you're looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript's modules, e.g.

module M {
    var s = "hello";
    export function f() {
        return s;
    }
}

So that you can access M.f() externally, but not s, and you cannot extend the module.

See the TypeScript specification for more details.

Tensorflow import error: No module named 'tensorflow'

The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.

create a new separate environment in Anaconda dedicated to TensorFlow as follows:

conda create -n newenvt anaconda python=python_version

replace python_version by your python version

activate the new environment as follows:

activate newenvt

Then install tensorflow into the new environment (newenvt) as follows:

conda install tensorflow

Now you can check it by issuing the following python code and it will work fine.

import tensorflow

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

What is the difference between String and string in C#?

You don't need import namespace (using System;) to use string because it is a global alias of System.String.

To know more about aliases you can check this link.

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Is there a command to refresh environment variables from the command prompt in Windows?

The best method I came up with was to just do a Registry query. Here is my example.

In my example I did an install using a Batch file that added new environment variables. I needed to do things with this as soon as the install was complete, but was unable to spawn a new process with those new variables. I tested spawning another explorer window and called back to cmd.exe and this worked but on Vista and Windows 7, Explorer only runs as a single instance and normally as the person logged in. This would fail with automation since I need my admin creds to do things regardless of running from local system or as an administrator on the box. The limitation to this is that it does not handle things like path, this only worked on simple enviroment variables. This allowed me to use a batch to get over to a directory (with spaces) and copy in files run .exes and etc. This was written today from may resources on stackoverflow.com

Orginal Batch calls to new Batch:

testenvget.cmd SDROOT (or whatever the variable)

@ECHO OFF
setlocal ENABLEEXTENSIONS
set keyname=HKLM\System\CurrentControlSet\Control\Session Manager\Environment
set value=%1
SET ERRKEY=0

REG QUERY "%KEYNAME%" /v "%VALUE%" 2>NUL| FIND /I "%VALUE%"
IF %ERRORLEVEL% EQU 0 (
ECHO The Registry Key Exists 
) ELSE (
SET ERRKEY=1
Echo The Registry Key Does not Exist
)

Echo %ERRKEY%
IF %ERRKEY% EQU 1 GOTO :ERROR

FOR /F "tokens=1-7" %%A IN ('REG QUERY "%KEYNAME%" /v "%VALUE%" 2^>NUL^| FIND /I "%VALUE%"') DO (
ECHO %%A
ECHO %%B
ECHO %%C
ECHO %%D
ECHO %%E
ECHO %%F
ECHO %%G
SET ValueName=%%A
SET ValueType=%%B
SET C1=%%C
SET C2=%%D
SET C3=%%E
SET C4=%%F
SET C5=%%G
)

SET VALUE1=%C1% %C2% %C3% %C4% %C5%
echo The Value of %VALUE% is %C1% %C2% %C3% %C4% %C5%
cd /d "%VALUE1%"
pause
REM **RUN Extra Commands here**
GOTO :EOF

:ERROR
Echo The the Enviroment Variable does not exist.
pause
GOTO :EOF

Also there is another method that I came up with from various different ideas. Please see below. This basically will get the newest path variable from the registry however, this will cause a number of issues beacuse the registry query is going to give variables in itself, that means everywhere there is a variable this will not work, so to combat this issue I basically double up the path. Very nasty. The more perfered method would be to do: Set Path=%Path%;C:\Program Files\Software....\

Regardless here is the new batch file, please use caution.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
set org=%PATH%
for /f "tokens=2*" %%A in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path ^|FIND /I "Path"') DO (
SET path=%%B
)
SET PATH=%org%;%PATH%
set path

When should null values of Boolean be used?

Use boolean rather than Boolean every time you can. This will avoid many NullPointerExceptions and make your code more robust.

Boolean is useful, for example

  • to store booleans in a collection (List, Map, etc.)
  • to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
  • each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format().

Make UINavigationBar transparent

Another Way That worked for me is to Subclass UINavigationBar And leave the drawRect Method empty !!

@IBDesignable class MONavigationBar: UINavigationBar {


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
    // Drawing code
}}

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I have faced the similar issue while host the appication in IIS

Solution

I change the Pool Identity and its work me

ApplicationPoolIdentity -> NetworkService

Show just the current branch in Git

You may be interested in the output of

git symbolic-ref HEAD

In particular, depending on your needs and layout you may wish to do

basename $(git symbolic-ref HEAD)

or

git symbolic-ref HEAD | cut -d/ -f3-

and then again there is the .git/HEAD file which may also be of interest for you.

Print list without brackets in a single row

Here is a simple one.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

the star unpacks the list and return every element in the list.

How to install mysql-connector via pip

If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

MongoError: connect ECONNREFUSED 127.0.0.1:27017

because you didn't start mongod process before you try starting mongo shell.

Start mongod server

mongod

Open another terminal window

Start mongo shell

mongo

How to hide collapsible Bootstrap 4 navbar on click

You can add the collapse component to the links like this..

<ul class="navbar-nav mr-auto">
     <li class="nav-item active">
         <a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
     </li>
 </ul>

BS3 demo using 'data-toggle' method

Or, (perhaps a better way) use jQuery like this..

$('.navbar-nav>li>a').on('click', function(){
    $('.navbar-collapse').collapse('hide');
});

BS3 demo using jQuery method


Update 2019 - Bootstrap 4

The navbar has changed, but the "close after click" method is still the same:

BS4 demo jQuery method
BS4 demo data-toggle method


Update 2021 - Bootstrap 5 (beta)

Use javascript to add a click event listener on the menu items to close the Collapse navbar..

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
})

BS5 demo javascript method

Or, Use the data-bs-toggle and data-bs-target data attributes in the markup on each link to toggle the Collapse navbar...

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
                </li>
            </ul>
            <form class="d-flex my-2 my-lg-0">
                <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </div>
    </div>
</nav>

BS5 demo data-attributes method

Open JQuery Datepicker by clicking on an image w/ no input field

Having a hidden input field leads to problems with datepicker dialog positioning (dialog is horizontally centered). You could alter the dialog's margin, but there's a better way.

Just create an input field and "hide" it by setting it's opacity to 0 and making it 1px wide. Also position it near (or under) the button, or where ever you want the datepicker to appear.

Then attach the datepicker to the "hidden" input field and show it when user presses the button.

HTML:

<button id="date-button">Show Calendar</button>
<input type="text" name="date-field" id="date-field" value="">

CSS:

#date-button {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    height 30px;
}

#date-field {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 1px;
    height: 32px; // height of the button + a little margin
    opacity: 0;
}

JS:

$(function() {
   $('#date-field').datepicker();

   $('#date-button').on('click', function() {
      $('#date-field').datepicker('show');
   });
});

Note: not tested with all browsers.

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type: http://golang.org/pkg/reflect/#Kind

You can then do checks for types outside of a switch block, like so:

import (
    "fmt"
    "reflect"
)

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
}
if yt == reflect.Float32 {
    println(">> y is float32")
}
if zt == reflect.String {
    println(">> z is string")
}

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

Windows Bat file optional argument parsing

Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.

The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...

@ECHO OFF

SET man1=%1
SET man2=%2
SHIFT & SHIFT

:loop
IF NOT "%1"=="" (
    IF "%1"=="-username" (
        SET user=%2
        SHIFT
    )
    IF "%1"=="-otheroption" (
        SET other=%2
        SHIFT
    )
    SHIFT
    GOTO :loop
)

ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%

REM ...do stuff here...

:theend

How to format a float in javascript?

There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph's solutions are wrong unfortunately.

Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok - 451.18. So it's difficult to spot this error at a first glance.

The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)

So my idea is to treat it with toFixed() before using Math.round();

function roundFix(number, precision)
{
    var multi = Math.pow(10, precision);
    return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}

Is there an equivalent of 'which' on the Windows command line?

In Windows CMD which calls where:

$ where php
C:\Program Files\PHP\php.exe

Failed to execute removeChild on Node

For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:

// Didn't work
<div>
     <TroubledComponent/>
</div>

// Worked
<div key='uniqueKey'>
     <TroubledComponent/>
</div>

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

Create a temporary table in MySQL with an index from a select

I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.

Basic information about the statement is available at the following MySQL links:

CREATE TABLE SELECT and CREATE TABLE.

At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.

  1. Add multiple indexes

    This statement shows how to add multiple indexes (note that index names - in lower case - are optional):

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
    SELECT * FROM core.my_big_table
    WHERE my_val = 1
    
  2. Add a new primary key:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (PRIMARY KEY my_pkey (order_number),
    INDEX cmpd_key (user_id, time))
    SELECT * FROM core.my_big_table
    
  3. Create additional columns

    You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (my_new_id BIGINT NOT NULL AUTO_INCREMENT,  
    PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
    SELECT * FROM core.my_big_table
    
  4. Redefining data types for the columns from SELECT

    You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (tag BIGINT,
    my_time DATETIME,  
    INDEX my_unique_index_name (tag) )
    SELECT * FROM core.my_big_table
    
  5. Advanced field definitions during create

    All the usual column definitions are available as when you create a normal table. Example:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
    location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
    country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",  
    INDEX my_index_name (location))
    ENGINE=MyISAM 
    SELECT * FROM core.my_big_table
    

The view 'Index' or its master was not found.

You most likely did not create your own view engine.
The default view engine looks for the views in ~/Views/[Controller]/ and ~/Views/Shared/.

You need to create your own view engine to make sure the views are searched in area views folder.

Take a look this post by Phil Haack.

ImportError: No module named 'google'

kindly executed these commands.

pip install google
pip install google-core-api

will definitely solve your problem

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

ReSharper "Cannot resolve symbol" even when project builds

For me for VS2015, I had to update Resharper to version 2016.2.2 to resolve the issue.

I had already tried (of which none worked for me):

  • suspending / resuming
  • suspending / clearing cach (using tools > options button) / resuming
  • suspending / clearing cach (using Windows file system) / resuming
  • moving cache to solution folder / restarting visual studio
  • many other combinations of all or some of above

I hope that may help someone.

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

pip install access denied on Windows

When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

I had the same problem with a ClickOnce deployment.

I solved the problem by going to the 'Publish' tab in the project properties and then selecting the 'Application Files' button.

I then selected the options:

  • 'File Name' of 'stdole.dll'
  • 'Publish status' to 'Include' and
  • 'Download Group' to 'Required'.

This fixed my problem when I re-published.

I hope this help you :D

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

How to implement onBackPressed() in Fragments?

According to the AndroidX release notes, androidx.activity 1.0.0-alpha01 is released and introduces ComponentActivity, a new base class of the existing FragmentActivity and AppCompatActivity. And this release brings us a new feature:

You can now register an OnBackPressedCallback via addOnBackPressedCallback to receive onBackPressed() callbacks without needing to override the method in your activity.

How do I load the contents of a text file into a javascript variable?

XMLHttpRequest, i.e. AJAX, without the XML.

The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.

Regular expression to match URLs in Java

In line with billjamesdev answer, here is another approach to validate an URL without using a RegEx:

From Apache Commons Validator lib, look at class UrlValidator. Some example code:

Construct a UrlValidator with valid schemes of "http", and "https".

String[] schemes = {"http","https"}.
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("url is valid");
} else {
   System.out.println("url is invalid");
}

prints "url is invalid"

If instead the default constructor is used.

UrlValidator urlValidator = new UrlValidator();
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("url is valid");
} else {
   System.out.println("url is invalid");
}

prints out "url is valid"

How do I unset an element in an array in javascript?

http://www.internetdoc.info/javascript-function/remove-key-from-array.htm

removeKey(arrayName,key);

function removeKey(arrayName,key)
{
 var x;
 var tmpArray = new Array();
 for(x in arrayName)
 {
  if(x!=key) { tmpArray[x] = arrayName[x]; }
 }
 return tmpArray;
}

Check if an element contains a class in JavaScript?

This is supported on IE8+.

First we check if classList exists if it does we can use the contains method which is supported by IE10+. If we are on IE9 or 8 it falls back to using a regex, which is not as efficient but is a concise polyfill.

if (el.classList) {
  el.classList.contains(className);
} else {
  new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}

Alternatively if you are compiling with babel you can simply use: el.classList.contains(className);

"int cannot be dereferenced" in Java

Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)

id.equals(list[pos].getItemNumber())

Should be...

id == list[pos].getItemNumber()

Practical uses of different data structures

The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.

For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.

The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.

Another great resource is the NIST Dictionary of Data structures and algorithms.

estimating of testing effort as a percentage of development time

Are you talking about automated unit/integration tests or manual tests?

For the former, my rule of thumb (based on measurements) is 40-50% added to development time i.e. if developing a use case takes 10 days (before an QA and serious bugfixing happens), writing good tests takes another 4 to 5 days - though this should best happen before and during development, not afterwards.

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Neither!

If you're asking; "what would a website visitor rather type, htm or html" - it's much better to give them a nice descriptive URL with no extension. If they get used to going to yoursite/contact.html and you change it to yoursite/contact.php you've broken that link. If you use yoursite/contact/ then there's no problem when you switch technology.

Compile error: package javax.servlet does not exist

place jakarta and delete javax

if you download servlet.api.jar :

NOTICE : this answer every time is not correct ( can be javax in JEE )

Correct

jakarta.servlet.*;

Incorrect

javax.servlet.*;

else :

place jar files into JAVA_HOME/jre/lib/ext

Try-catch speeding up my code?

One of the Roslyn engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the JIT compiler does register scheduling in the corresponding x86 code. The result is suboptimal code generation on the loads and stores of the locals.

For some reason unclear to all of us, the problematic code generation path is avoided when the JITter knows that the block is in a try-protected region.

This is pretty weird. We'll follow up with the JITter team and see whether we can get a bug entered so that they can fix this.

Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the JITter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.

Thanks for bringing this to our attention, and apologies for the odd behaviour.

Alter a MySQL column to be AUTO_INCREMENT

The SQL to do this would be:

ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;

There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):

ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;

You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.

Javascript how to split newline

The simplest and safest way to split a string using new lines, regardless of format (CRLF, LFCR or LF), is to remove all carriage return characters and then split on the new line characters. "text".replace(/\r/g, "").split(/\n/);

This ensures that when you have continuous new lines (i.e. \r\n\r\n, \n\r\n\r, or \n\n) the result will always be the same.

In your case the code would look like:

(function ($) {
    $(document).ready(function () {
        $('#data').submit(function (e) {
            var ks = $('#keywords').val().replace(/\r/g, "").split(/\n/);
            e.preventDefault();
            alert(ks[0]);
            $.each(ks, function (k) {
                alert(k);
            });
        });
    });
})(jQuery);

Here are some examples that display the importance of this method:

_x000D_
_x000D_
var examples = ["Foo\r\nBar", "Foo\r\n\r\nBar", "Foo\n\r\n\rBar", "Foo\nBar\nFooBar"];_x000D_
_x000D_
examples.forEach(function(example) {_x000D_
  output(`Example "${example}":`);_x000D_
  output(`Split using "\n": "${example.split("\n")}"`);_x000D_
  output(`Split using /\r?\n/: "${example.split(/\r?\n/)}"`);_x000D_
  output(`Split using /\r\n|\n|\r/: "${example.split(/\r\n|\n|\r/)}"`);_x000D_
  output(`Current method: ${example.replace(/\r/g, "").split("\n")}`);_x000D_
  output("________");_x000D_
});_x000D_
_x000D_
function output(txt) {_x000D_
  console.log(txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));_x000D_
}
_x000D_
_x000D_
_x000D_

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

What does LayoutInflater in Android do?

LayoutInflater is a class used to instantiate layout XML file into its corresponding view objects which can be used in Java programs. In simple terms, there are two ways to create UI in android. One is a static way and another is dynamic or programmatically. Suppose we have a simple layout main.xml having one textview and one edittext as follows.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/layout1"
    >
<TextView
        android:id="@+id/namelabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter your name"
        android:textAppearance="?android:attr/textAppearanceLarge" >
    </TextView>
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="14dp"
        android:ems="10">
    </EditText>
</LinearLayout>

We can display this layout in static way by

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

A dynamic way of creating a view means the view is not mentioned in our main.xml but we want to show with this in run time. For example, we have another XML in layout folder as footer.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Add your record"
    android:textSize="24sp" >
 </TextView>

We want to show this textbox in run time within our main UI. So here we will inflate text.xml. See how:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  TextView t = (TextView)inflater.inflate(R.layout.footer,null);

  lLayout = (LinearLayout)findViewById(R.id.layout1);
  lLayout.addView(t);

Here I have used getSystemService (String) to retrieve a LayoutInflater instance. I can use getLayoutInflator() too to inflate instead of using getSystemService (String) like below:

LayoutInflator inflater = getLayoutInflater();
TextView t = (TextView) inflater.inflate(R.layout.footer, null);
lLayout.addView(t);

Is it possible to embed animated GIFs in PDFs?

I do it for beamer presentations,

provide tmp-0.png through tmp-34.png

\usepackage{animate}

\begin{frame}{Torque Generating Mechanism}
  \animategraphics[loop,controls,width=\linewidth]{12}{output/tmp-}{0}{34}
\end{frame}

How to align form at the center of the page in html/css

Wrap the <form> element inside a div container and apply css to the div instead which makes things easier.

_x000D_
_x000D_
#aDiv{width: 300px; height: 300px; margin: 0 auto;}
_x000D_
<html>_x000D_
_x000D_
<head></head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <form>_x000D_
      <div id="aDiv">_x000D_
        <table>_x000D_
          <tr>_x000D_
            <td>Name :</td>_x000D_
            <td>_x000D_
              <input type="text" name="name">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Email :</td>_x000D_
            <td>_x000D_
              <input type="text" name="email">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Password :</td>_x000D_
            <td>_x000D_
              <input type="password" name="pwd">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Confirm Password :</td>_x000D_
            <td>_x000D_
              <input type="password" name="cpwd">_x000D_
              <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              <input type="submit" value="Submit">_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
    </form>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Switch case with fallthrough?

If the values are integer then you can use [2-3] or you can use [5,7,8] for non continuous values.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

If the values are string then you can use |.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.

var myformData = new FormData();        
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());

$.ajax({
    method: 'post',
    processData: false,
    contentType: false,
    cache: false,
    data: myformData,
    enctype: 'multipart/form-data',
    url: 'include/ajax.php',
    success: function (response) {
        $("#subform").html(response).delay(4000).hide(1); 
    }
});

How to pull specific directory with git

git clone --filter from git 2.19 now works on GitHub (tested 2020-09-18, git 2.25.1)

I'm not sure about pull/fetch, but at least for the initial clone, this option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.

E.g., to clone only objects required for d1 of this repository: https://github.com/cirosantilli/test-git-partial-clone I can do:

git clone \
  --depth 1 \
  --filter=blob:none \
  --no-checkout \
  https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git checkout master -- d1

I have covered this in more detail at: Git: How do I clone a subdirectory only of a Git repository?

It is very likely that whatever gets implemented for git clone in that area will also have git pull analogues, but I couldn't find it very easily yet.

An efficient compression algorithm for short text strings

Huffman has a static cost, the Huffman table, so I disagree it's a good choice.

There are adaptative versions which do away with this, but the compression rate may suffer. Actually, the question you should ask is "what algorithm to compress text strings with these characteristics". For instance, if long repetitions are expected, simple Run-Lengh Encoding might be enough. If you can guarantee that only English words, spaces, punctiation and the occasional digits will be present, then Huffman with a pre-defined Huffman table might yield good results.

Generally, algorithms of the Lempel-Ziv family have very good compression and performance, and libraries for them abound. I'd go with that.

With the information that what's being compressed are URLs, then I'd suggest that, before compressing (with whatever algorithm is easily available), you CODIFY them. URLs follow well-defined patterns, and some parts of it are highly predictable. By making use of this knowledge, you can codify the URLs into something smaller to begin with, and ideas behind Huffman encoding can help you here.

For example, translating the URL into a bit stream, you could replace "http" with the bit 1, and anything else with the bit "0" followed by the actual procotol (or use a table to get other common protocols, like https, ftp, file). The "://" can be dropped altogether, as long as you can mark the end of the protocol. Etc. Go read about URL format, and think on how they can be codified to take less space.

Disabling and enabling a html input button

While not directly related to the question, if you hop onto this question looking to disable something other than the typical input elements button, input, textarea, the syntax won't work.

To disable a div or a span, use setAttribute

document.querySelector('#somedivorspan').setAttribute('disabled', true);

P.S: Gotcha, only call this if you intend to disable. A bug in chrome Version 83 causes this to always disable even when the second parameter is false.

Search an array for matching attribute

Must be too late now, but the right version would be:

for(var i = 0; i < restaurants.restaurant.length; i++)
{
  if(restaurants.restaurant[i].food == 'chicken')
  {
    return restaurants.restaurant[i].name;
  }
}

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

How to change the display name for LabelFor in razor in mvc3?

You could decorate your view model property with the [DisplayName] attribute and specify the text to be used:

[DisplayName("foo bar")]
public string SomekingStatus { get; set; }

Or use another overload of the LabelFor helper which allows you to specify the text:

@Html.LabelFor(model => model.SomekingStatus, "foo bar")

And, no, you cannot specify a class name in MVC3 as you tried to do, as the LabelFor helper doesn't support that. However, this would work in MVC4 or 5.

How to get the size of a file in MB (Megabytes)?

You can use FileChannel in Java.

FileChannel has the size() method to determine the size of the file.

    String fileName = "D://words.txt";

    Path filePath = Paths.get(fileName);

    FileChannel fileChannel = FileChannel.open(filePath);
    long fileSize = fileChannel.size();

    System.out.format("The size of the file: %d bytes", fileSize);

Or you can determine the file size using Apache Commons' FileUtils' sizeOf() method. If you are using maven, add this to pom.xml file.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Try the following coding,

    String fileName = "D://words.txt";
    File f = new File(fileName);

    long fileSize = FileUtils.sizeOf(f);        

    System.out.format("The size of the file: %d bytes", fileSize);

These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).

Now you can simply use the if-else conditions since the size is captured in MB.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

remove this work for me:

<filtering>true</filtering>

I guess it is caused by this filtering bug

Checking Value of Radio Button Group via JavaScript?

Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).

document.querySelector('input[name="gender"]:checked').value

Is it possible to have a multi-line comments in R?

You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { } blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.

"This function takes a value x, and does things and returns things that
 take several lines to explain"
doEverythingOften <- function(x) {
     # Non! Comment it out! We'll just do it once for now.
     "if (x %in% 1:9) {
          doTenEverythings()
     }"
     doEverythingOnce()
     ...
     return(list(
         everythingDone = TRUE, 
         howOftenDone = 1
     ))
}

The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE) block.

The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.

Regarding what do in which IDE: I'm a Vim user, and I find NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.

Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.

How to delete rows from a pandas DataFrame based on a conditional expression

In pandas you can do str.len with your boundary and using the Boolean result to filter it .

df[df['column name'].str.len().lt(2)]

Styling an anchor tag to look like a submit button

HTML

<a href="#" class="button"> HOME </a>

CSS

.button { 
         background-color: #00CCFF;
         padding: 8px 16px;
         display: inline-block;
         text-decoration: none;
         color: #FFFFFF;
         border-radius: 3px;
}
.button:hover{ background-color: #0066FF;}

Watch the tutorial

https://youtu.be/euti4HAJJfk

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

If you're using cygwin, the syntax is slightly different for the basename command.

find . -name "*.zip" | while read filename; do unzip -o -d "`basename "$filename" .zip`" "$filename"; done;

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

Where is the IIS Express configuration / metabase file found?

For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":

Context menu for IIS Express system tray icon showing the alternative "Show all applications" highlighted

Then, select the relevant application and click the applicationhost.config file path:

Dialog showing arbritrary website with accompanying applicationhost.config file path

What is the main difference between PATCH and PUT request?

put:
If I want to update my first name, then I send a put request:

{ "first": "Nazmul", "last": "hasan" } 

But here is a problem with using put request: When I want to send put request I have to send all two parameters that is first and last (whereas I only need to update first) so it is mandatory to send them all again with put request.

patch:
patch request, on the other hand, says: only specify the data which you need to update and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first name? Well, It only suffices to specify first in patch request.

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Validate IPv4 address in Java

If you don care about the range, the following expression will be useful to validate from 1.1.1.1 to 999.999.999.999

"[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}"

Select the top N values by group

Since dplyr 1.0.0, the slice_max()/slice_min() functions were implemented:

mtcars %>%
 group_by(cyl) %>%
 slice_max(mpg, n = 2, with_ties = FALSE)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  33.9     4  71.1    65  4.22  1.84  19.9     1     1     4     1
2  32.4     4  78.7    66  4.08  2.2   19.5     1     1     4     1
3  21.4     6 258     110  3.08  3.22  19.4     1     0     3     1
4  21       6 160     110  3.9   2.62  16.5     0     1     4     4
5  19.2     8 400     175  3.08  3.84  17.0     0     0     3     2
6  18.7     8 360     175  3.15  3.44  17.0     0     0     3     2

The documentation on with_ties parameter:

Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.

Get Image Height and Width as integer values?

PHP's getimagesize() returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

For further information, see the documentation.

Adjust table column width to content size

If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

C++ IDE for Linux?

Shorter answer is: choosing whatever "editor" you like, then use GDB console or a simple GDB front end to debug your application. The debuggers come with fancy IDEs such as Netbeans sucks for C/C++. I use Netbeans as my editor, and Insight and GDB console as my debugger.

With insight, you have a nice GUI and the raw power of GDB.

As soon as you get used to GDB commands, you will start to love it since you can do things you will never be able to do using an GUI. You can use even use Python as your script language if you are using GDB 7 or newer version.

Most people here paid more attentions to the "Editors" of the IDEs. However, if you are developing a large project in C/C++, you could easily spend more than 70% of your time on the "debuggers". The debuggers of the fancy IDEs are at least 10 years behind Visual Studio. For instance, Netbenas has very similar interfaces with Visual Studio. But its debugger has a number of disadvantages compared to Visual Studio.

  1. Very slow to display even a array with only a few hundreds of elements
  2. No highlighting for changed value ( By default, visual studio shows changed values in the watch windows in red)
  3. Very limited ability to show memory.
  4. You cannot modify the source code then continue to run. If a bug takes a long time to hit, you would like to change the source and apply the changes live and continue to run your application.
  5. You cannot change the "next statement" to run. In Visual Studio, you can use "Set Next Statement" to change how your application runs. Although this feature could crash your application if not used properly, but it will save you a lot of time. For instance, if you found the state of your application is not correct, but you do not know what caused the problems, you might want to rerun a certain region of the your source codes without restarting your application.
  6. No built-in support for STL such as vector, list, deque and map etc.
  7. No watch points. You need to have this feature, when you need to stop your application right at the point a variable is changed. Intel based computers have hardware watch points so that the watch points will not slow down your system. It might takes many hours to find some hard-to-find bugs without using watch points. "Visual Studio" calls "watch pointer" as "Data BreakPoint".

The list can be a lot longer.

I was so frustrated by the disadvantages of the Netbeans or other similar IDEs, so that I started to learn GDB itself. I found GDB itself are very powerful. GDB does not have all the "disadvantages" mentioned above. Actually, GDB is very powerful, it is even better than Visual Studio in many ways. Here I just show you a very simple example.

For instance, you have a array like:

struct IdAndValue
{
  int ID;
  int value;
};


IdAndValue IdAndValues[1000];

When your application stops, and you want to examine the data in IdAndValues. For instance, if you want to find the ordinals and values in the array for a particular "ID", you can create a script like the following:

define PrintVal 
set $i=0
printf "ID = %d\n", $arg0
while $i<1000
  if IdAndValues[$i].ID == $arg0
    printf "ordinal = %d, value = %d\n", $i, IdAndValues[$i].vaue
    set $i++
  end
end
end

You can use all variables in your application in the current context, your own variables (in our example, it is $i), arguments passed (in our example, it is $arg0) and all GDB commands (built-in or user defined).

Use PrintVal 1 from GDB prompt to print out values for ID "1"

By the way, NetBeans does come with a GDB console, but by using the console, you could crash Netbeans. And I believe that is why the console is hidden by default in NetBeans

JUnit: how to avoid "no runnable methods" in test utils classes

In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

Retrieve only the queried element in an object array in MongoDB collection

Better you can query in matching array element using $slice is it helpful to returning the significant object in an array.

db.test.find({"shapes.color" : "blue"}, {"shapes.$" : 1})

$slice is helpful when you know the index of the element, but sometimes you want whichever array element matched your criteria. You can return the matching element with the $ operator.

Registering for Push Notifications in Xcode 8/Swift 3.0?

The answer from ast1 is very simple and useful. It works for me, thank you so much. I just want to poin it out here, so people who need this answer can find it easily. So, here is my code from registering local and remote (push) notification.

    //1. In Appdelegate: didFinishLaunchingWithOptions add these line of codes
    let mynotif = UNUserNotificationCenter.current()
    mynotif.requestAuthorization(options: [.alert, .sound, .badge]) {(granted, error) in }//register and ask user's permission for local notification

    //2. Add these functions at the bottom of your AppDelegate before the last "}"
    func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
        application.registerForRemoteNotifications()//register for push notif after users granted their permission for showing notification
}
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("Device Token: \(tokenString)")//print device token in debugger console
}
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")//print error in debugger console
}

How to detect Windows 64-bit platform with .NET?

From Chriz Yuen blog

C# .Net 4.0 Introduced two new environment property Environment.Is64BitOperatingSystem; Environment.Is64BitProcess;

Please be careful when you use these both property. Test on Windows 7 64bits Machine

//Workspace: Target Platform x86
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess False

//Workspace: Target Platform x64
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess True

//Workspace: Target Platform Any
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess True

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

Swift - how to make custom header for UITableView?

I have had some problems in Swift 5 with this. When using this function I had a wrong alignment with the header cell:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
     return headerCell
}

The cell view was shown with a bad alignment and the top part of the tableview was shown. So I had to make some tweak like this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 90))
     let headerCell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER")
     headerCell?.frame = headerView.bounds
     headerView.addSubview(headerCell!)
     return headerView
 }

I am having this problem in Swift 5 and Xcode 12.0.1, I don't know if it is just a problem for me or it is a bug. Hope it helps ! I have lost a morning...

Using Vim's tabs like buffers

I ran into the same problem. I wanted tabs to work like buffers and I never quite manage to get them to. The solution that I finally settled on was to make buffers behave like tabs!

Check out the plugin called Mini Buffer Explorer, once installed and configured, you'll be able to work with buffers virtaully the same way as tabs without losing any functionality.

For each row in an R dataframe

I use this simple utility function:

rows = function(tab) lapply(
  seq_len(nrow(tab)),
  function(i) unclass(tab[i,,drop=F])
)

Or a faster, less clear form:

rows = function(x) lapply(seq_len(nrow(x)), function(i) lapply(x,"[",i))

This function just splits a data.frame to a list of rows. Then you can make a normal "for" over this list:

tab = data.frame(x = 1:3, y=2:4, z=3:5)
for (A in rows(tab)) {
    print(A$x + A$y * A$z)
}        

Your code from the question will work with a minimal modification:

for (well in rows(dataFrame)) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Adding this maven dependency with JUnit Jupiter (v.5.5.1) solves the issue.

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.5.1</version>
    <scope>test</scope>
</dependency>

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

Print time in a batch file (milliseconds)

Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Do you have to put Task.Run in a method to make it async?

When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.

However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.

True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html

In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

#case_date= 03/31/2020   

#Above is the value stored in case_date in format(mm/dd/yyyy )

demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it 
print(new_case_date)

Find the files that have been changed in last 24 hours

Another, more humane way:

find /<directory> -newermt "-24 hours" -ls

or:

find /<directory> -newermt "1 day ago" -ls

or:

find /<directory> -newermt "yesterday" -ls

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Convert Python dict into a dataframe

Pandas have built-in function for conversion of dict to data frame.

pd.DataFrame.from_dict(dictionaryObject,orient='index')

For your data you can convert it like below:

import pandas as pd
your_dict={u'2012-06-08': 388,
 u'2012-06-09': 388,
 u'2012-06-10': 388,
 u'2012-06-11': 389,
 u'2012-06-12': 389,
 u'2012-06-13': 389,
 u'2012-06-14': 389,
 u'2012-06-15': 389,
 u'2012-06-16': 389,
 u'2012-06-17': 389,
 u'2012-06-18': 390,
 u'2012-06-19': 390,
 u'2012-06-20': 390,
 u'2012-06-21': 390,
 u'2012-06-22': 390,
 u'2012-06-23': 390,
 u'2012-06-24': 390,
 u'2012-06-25': 391,
 u'2012-06-26': 391,
 u'2012-06-27': 391,
 u'2012-06-28': 391,
 u'2012-06-29': 391,
 u'2012-06-30': 391,
 u'2012-07-01': 391,
 u'2012-07-02': 392,
 u'2012-07-03': 392,
 u'2012-07-04': 392,
 u'2012-07-05': 392,
 u'2012-07-06': 392}

your_df_from_dict=pd.DataFrame.from_dict(your_dict,orient='index')
print(your_df_from_dict)

How to create a numpy array of all True or all False?

Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

Answer: No

import timeit

n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"

print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")

Result:

np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s


IMPORTANT

Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

>>> print(np.empty((4,4), dtype=bool))
[[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True False False]]

Determining the version of Java SDK on the Mac

Run this command in your terminal:

$ java -version

java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$ 

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to

include_path='.:/usr/share/php:/usr/share/pear' 

or append the

'.:/usr/share/php:/usr/share/pear' 

to the current value of include_path.

It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir

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

psql postgres

postgres=# CREATE ROLE username superuser;
postgres=# ALTER ROLE username WITH LOGIN;

Cannot find Dumpbin.exe

In Visual Studio Professional 2017 Version 15.9.13:

  • First, either:

    • launch the "Visual Studio Installer" from the start menu, select your Visual Studio product, and click "Modify",

    or

    • from within Visual Studio go to "Tools" -> "Get Tools and Features..."
  • Then, wait for it while it is "getting things ready..." and being "almost there..."

  • Switch to the "Individual components" tab

  • Scroll down to the "Compilers, build tools, and runtimes" section

  • Check "VC++ 2017 version 15.9 v14.16 latest v141 tools"

like this:

enter image description here

After doing this, you will be blessed with not just one, but a whopping four instances of DUMPBIN:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx64\x86\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x64\dumpbin.exe
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86\dumpbin.exe

How do I get the current username in .NET using C#?

Just in case someone is looking for user Display Name as opposed to User Name, like me.

Here's the treat :

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

Add Reference to System.DirectoryServices.AccountManagement in your project.

SDK Manager.exe doesn't work

I add new environment variable "ANDROID_SDK_HOME" and set it, like my path to android SDK folder (c:/Android) and it's work!

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

How to play a notification sound on websites?

How about the yahoo's media player Just embed yahoo's library

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

<a id="beep" href="song.mp3">Play Song</a>

To autostart

$(function() { $("#beep").click(); });

UITableView - change section header color

Here's how to change the text color.

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];

Receiver not registered exception error?

Lets assume your broadcastReceiver is defined like this:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // your code

    }
};

If you are using LocalBroadcast in an Activity, then this is how you'll unregister:

LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);

If you are using LocalBroadcast in a Fragment, then this is how you'll unregister:

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);

If you are using normal broadcast in an Activity, then this is how you'll unregister:

unregisterReceiver(broadcastReceiver);

If you are using normal broadcast in a Fragment, then this is how you'll unregister:

getActivity().unregisterReceiver(broadcastReceiver);

Can't use Swift classes inside Objective-C

Don't create the header file yourself. Delete the one you created.

Make sure your Swift classes are tagged with @objc or inherit from a class that derives (directly or indirectly) from NSObject.

Xcode won't generate the file if you have any compiler errors in your project - make sure your project builds cleanly.

Conversion failed when converting the nvarchar value ... to data type int

I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.

My invalid SQL query looked like this:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)

This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.

I changed it to:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')

And it worked.

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Calculate date from week number

this is my solution when we want to calculate a date given year, week number and day of the week.

int Year = 2014;
int Week = 48;
int DayOfWeek = 4;

DateTime FecIni = new DateTime(Year, 1, 1);
FecIni = FecIni.AddDays(7 * (Week - 1));
if ((int)FecIni.DayOfWeek > DayOfWeek)
{
    while ((int)FecIni.DayOfWeek != DayOfWeek) FecIni = FecIni.AddDays(-1);
}
else
{
    while ((int)FecIni.DayOfWeek != DayOfWeek) FecIni = FecIni.AddDays(1);
}

Why Git is not allowing me to commit even after configuration?

I had this problem even after setting the config properly. git config

My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).

Typescript sleep

You have to wait for TypeScript 2.0 with async/await for ES5 support as it now supported only for TS to ES6 compilation.

You would be able to create delay function with async:

function delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
}

And call it

await delay(300);

Please note, that you can use await only inside async function.

If you can't (let's say you are building nodejs application), just place your code in the anonymous async function. Here is an example:

    (async () => { 
        // Do something before delay
        console.log('before delay')

        await delay(1000);

        // Do something after
        console.log('after delay')
    })();

Example TS Application: https://github.com/v-andrew/ts-template

In OLD JS you have to use

setTimeout(YourFunctionName, Milliseconds);

or

setTimeout( () => { /*Your Code*/ }, Milliseconds );

However with every major browser supporting async/await it less useful.

Update: TypeScript 2.1 is here with async/await.

Just do not forget that you need Promise implementation when you compile to ES5, where Promise is not natively available.

PS

You have to export the function if you want to use it outside of the original file.

Given a DateTime object, how do I get an ISO 8601 date in string format?

System.DateTime.UtcNow.ToString("o")

=>

val it : string = "2013-10-13T13:03:50.2950037Z"

Strip / trim all strings of a dataframe

You can use DataFrame.select_dtypes to select string columns and then apply function str.strip.

Notice: Values cannot be types like dicts or lists, because their dtypes is object.

df_obj = df.select_dtypes(['object'])
print (df_obj)
0    a  
1    c  

df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)

   0   1
0  a  10
1  c   5

But if there are only a few columns use str.strip:

df[0] = df[0].str.strip()

Adding div element to body or document in JavaScript

The most underrated method is insertAdjacentElement. You can literally add your HTML using one single line.

document.body.insertAdjacentElement('beforeend', html)

Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

What is "Advanced" SQL?

At my previous job, we had a technical test which all candidates were asked to sit. 10ish questions, took about an hour. In all honesty though, 90% of failures could be screened out because they couldn't write an INNER JOIN statement. Not even an outer.

I'd consider that a prerequisite for any job description involving SQL and would leave well alone until that was mastered. From there though, talk to them - any further info on what they're actually looking for will, worst case scenario, be a useful list of things to learn as part of your professional development.

Join between tables in two different databases?

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:

SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.

Relationship between hashCode and equals method in Java

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

Running a script inside a docker container using shell script

If you want to run the same command on multiple instances you can do this :

for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done

Min/Max of dates in an array?

This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))

This is the accepted answer for this page: Finding the max value of an attribute in an array of objects

How do you serve a file for download with AngularJS or Javascript?

I didnt want Static Url. I have AjaxFactory for doing all ajax operations. I am getting url from the factory and binding it as follows.

<a target="_self" href="{{ file.downloadUrl + '/' + order.OrderId + '/' + fileName }}" download="{{fileName}}">{{fileName}}</a>

Thanks @AhlemMustapha

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Verifying a specific parameter with Moq

If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.

Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert methods to validate it. For example:

// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
        .Callback<int, MyObject>((i, obj) => saveObject = obj)
        .Returns("xyzzy");

// Act
// ...

// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));

Array definition in XML?

As its name is "numbers" it is clear it is a list of number... So an array of number... no need of the attribute type... Although I like the principle of specifying the type of field in a type attribute...

Loading a .json file into c# program

As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;

   JsonSerializer serializer = new JsonSerializer();
   MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");

The above code assumes that you have something like

public class MyObject
{
    public string prop1 { get; set; };
    public string prop2 { get; set; };
}

And your json looks like;

{
      "prop1":"value1",
      "prop2":"value2"
}

I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.

How can I setup & run PhantomJS on Ubuntu?

I have found this simpler way - Phantom dependencies + Npm

sudo apt-get update
sudo apt-get install build-essential chrpath libssl-dev libxft-dev
sudo apt-get install libfreetype6 libfreetype6-dev
sudo apt-get install libfontconfig1 libfontconfig1-dev

and npm

[sudo] npm install -g phantomjs

Done.

Set auto height and width in CSS/HTML for different screen sizes

Using bootstrap with a little bit of customization, the following seems to work for me:

I need 3 partitions in my container and I tried this:

CSS:

.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
  padding-top: 20px;
  border: 1px solid #cecece;
  height: 100%;
}
.midnav {
  padding: 0px;
}

HTML:

  <div class="container-fluid text-center"> 
    <div class="row content">
    <div class="col-md-2 sidenav text-left">Some content 1</div>
    <div class="col-md-9 midnav text-left">Some content 2</div>
    <div class="col-md-1 sidenav text-center">Some content 3</div>
    </div>
  </div>

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

Lock down Microsoft Excel macro

Protect/Lock Excel VBA Code:

When we write VBA code it is often desired to have the VBA Macro code not visible to end-users. This is to protect your intellectual property and/or stop users messing about with your code. Just be aware that Excel's protection ability is far from what would be considered secure. There are also many VBA Password Recovery [tools] for sale on the www.

To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.

(Emphasis mine)

Seems like your best bet. It won't stop people determined to steal your code but it's enough to stop casual pirates.

Remember, even if you were able to distribute a compiled copy of your code there'd be nothing to stop people decompiling it.

How to add a line to a multiline TextBox?

Try this

textBox1.Text += "SomeText\r\n" 

you can also try

textBox1.Text += "SomeText" + Environment.NewLine;

Where \r is carriage return and \n is new line

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

is there a css hack for safari only NOT chrome?

This works:

@media not all and (min-resolution:.001dpcm) { 
  @media {
    /* your code for Safari Desktop & Mobile */
    body {
      background-color: red;
      color: blue;
    }
    /* end */
  }
}

How do I set bold and italic on UILabel of iPhone/iPad?

This is very simple. Here is the code.

[yourLabel setFont:[UIFont boldSystemFontOfSize:15.0];

This will help you.

Singletons vs. Application Context in Android?

I had the same problem: Singleton or make a subclass android.os.Application?

First I tried with the Singleton but my app at some point makes a call to the browser

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));

and the problem is that, if the handset doesn't have enough memory, most of your classes (even Singletons) are cleaned to get some memory so, when returning from the browser to my app, it crashed everytime.

Solution: put needed data inside a subclass of Application class.

Detect if the device is iPhone X

According the @saswanb's response, this is a Swift 4 version :

var iphoneX = false
if #available(iOS 11.0, *) {
    if ((UIApplication.shared.keyWindow?.safeAreaInsets.top)! > CGFloat(0.0)) {
        iphoneX = true
    }
}

Are there bookmarks in Visual Studio Code?

The bookmarks extension mentioned in the accepted answer conflicts with toggling breakpoints via the margin.

You could do the same with breakpoints and select the debug tab on the left to see them listed. Better yet, use File, Preferences, Keyboard Shortcuts and set (Shift+)Ctrl+F9 to navigate between them, even across files: enter image description here

Twig for loop for arrays with keys

There's this example in the SensioLab page on the for tag:

<h1>Members</h1>
<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys

In the shell, what does " 2>&1 " mean?

2>&1 is a POSIX shell construct. Here is a breakdown, token by token:


2: "Standard error" output file descriptor.

>&: Duplicate an Output File Descriptor operator (a variant of Output Redirection operator >). Given [x]>&[y], the file descriptor denoted by x is made to be a copy of the output file descriptor y.

1 "Standard output" output file descriptor.

The expression 2>&1 copies file descriptor 1 to location 2, so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").


Further explanation:

File Descriptor: "A per-process unique, non-negative integer used to identify an open file for the purpose of file access."

Standard output/error: Refer to the following note in the Redirection section of the shell documentation:

Open files are represented by decimal numbers starting with zero. The largest possible value is implementation-defined; however, all implementations shall support at least 0 to 9, inclusive, for use by the application. These numbers are called "file descriptors". The values 0, 1, and 2 have special meaning and conventional uses and are implied by certain redirection operations; they are referred to as standard input, standard output, and standard error, respectively. Programs usually take their input from standard input, and write output on standard output. Error messages are usually written on standard error. The redirection operators can be preceded by one or more digits (with no intervening characters allowed) to designate the file descriptor number.

HTML5 Video Stop onClose

Try this:

if ($.browser.msie)
{
   // Some other solution as applies to whatever IE compatible video player used.
}
else
{
   $('video')[0].pause();
}

But, consider that $.browser is deprecated, but I haven't found a comparable solution.

How can I strip first X characters from string using sed?

The following should work:

var="pid: 1234"
var=${var:5}

Are you sure bash is the shell executing your script?

Even the POSIX-compliant

var=${var#?????}

would be preferable to using an external process, although this requires you to hard-code the 5 in the form of a fixed-length pattern.

Get the first N elements of an array?

array_slice() is best thing to try, following are the examples:

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

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

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

Java: How To Call Non Static Method From Main Method?

You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.

C++ Singleton design pattern

This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper: http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf

Convert UTC datetime string to local datetime

If using Django, you can use the timezone.localtime method:

from django.utils import timezone
date 
# datetime.datetime(2014, 8, 1, 20, 15, 0, 513000, tzinfo=<UTC>)

timezone.localtime(date)
# datetime.datetime(2014, 8, 1, 16, 15, 0, 513000, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)

Correct way to handle conditional styling in React

Another way, using inline style and the spread operator

style={{
  ...completed ? { textDecoration: completed } : {}
}}

That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.

How do I analyze a .hprof file?

You can use JHAT, The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. A very useful view is the "heap histogram" link at the very bottom.

ex: jhat -port 7401 -J-Xmx4G dump.hprof

jhat can execute OQL "these days" as well (bottom link "execute OQL")

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

I've installed Virutal PC according to Donavon's tutorial but it seems that my laptop's BIOS doesn't support Hardware Virtualization, and it's required to run Virtual PC. So, make sure your equipment supports that before you go any further wirh Virtual PC.

How do I add a new sourceset to Gradle?

This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up


To sum up both old answers (get best and minimum viable of both worlds):

some warm words first:

  1. first, we need to define the sourceSet:

    sourceSets {
        integrationTest
    }
    
  2. next we expand the sourceSet from test, therefor we use the test.runtimeClasspath (which includes all dependenciess from test AND test itself) as classpath for the derived sourceSet:

    sourceSets {
        integrationTest {
            compileClasspath += sourceSets.test.runtimeClasspath
            runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
        }
    }
    
    • note) somehow this redeclaration / extend for sourceSets.integrationTest.runtimeClasspath is needed, but should be irrelevant since runtimeClasspath always expands output + runtimeSourceSet, don't get it
  3. we define a dedicated task for just running integration tests:

    task integrationTest(type: Test) {
    }
    
  4. Configure the integrationTest test classes and classpaths use. The defaults from the java plugin use the test sourceSet

    task integrationTest(type: Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
    }
    
  5. (optional) auto run after test

    integrationTest.dependsOn test
    

  6. (optional) add dependency from check (so it always runs when build or check are executed)

    tasks.check.dependsOn(tasks.integrationTest)
    
  7. (optional) add java,resources to the sourceSet to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet directories java and resources for each set if it doesn't exist:

    sourceSets {
         integrationTest {
             java
             resources
         }
    }
    

tl;dr

apply plugin: 'java'

// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
    integrationTest {
        // not necessary but nice for IDEa's
        java
        resources

        compileClasspath += sourceSets.test.runtimeClasspath
        // somehow this redeclaration is needed, but should be irrelevant
        // since runtimeClasspath always expands compileClasspath
        runtimeClasspath += sourceSets.test.runtimeClasspath
    }
}

// define custom test task for running integration tests
task integrationTest(type: Test) {
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)

referring to:

Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!

Opening database file from within SQLite command-line shell

I think the simplest way to just open a single database and start querying is:

sqlite> .open "test.db"
sqlite> SELECT * FROM table_name ... ;

Notice: This works only for versions 3.8.2+

What is the difference between Cygwin and MinGW?

Cygwin emulates entire POSIX environment, while MinGW is minimal tool set for compilation only (compiles native Win application.) So if you want to make your project cross-platform the choice between the two is obvious, MinGW.

Although you might consider using VS on Windows, GCC on Linux/Unices. Most open source projects do that (e.g. Firefox or Python).

How to make HTML table cell editable?

You can use x-editable https://vitalets.github.io/x-editable/ its awesome library from bootstrap

Disabling vertical scrolling in UIScrollView

The most obvious solution is to forbid y-coordinate changes in your subclass.

override var contentOffset: CGPoint {
  get {
    return super.contentOffset
  }
  set {
    super.contentOffset = CGPoint(x: newValue.x, y: 0)
  }
}

This is the only suitable solution in situations when:

  1. You are not allowed or just don't want to use delegate.
  2. Your content height is larger than container height

Validation for 10 digit mobile number and focus input field on invalid

I used $form.submit() as it keeps html input validation.

Also I used input type tel as it supported by mobile browsers, only display numeric keypad.

<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>


$('#mob_frm').submit(function(e) {
            e.preventDefault();
            if(!$('#mobile').val().match('[0-9]{10}'))  {
                alert("Please put 10 digit mobile number");
                return;
            }  

        });

Bin size in Matplotlib (Histogram)

I had the same issue as OP (I think!), but I couldn't get it to work in the way that Lastalda specified. I don't know if I have interpreted the question properly, but I have found another solution (it probably is a really bad way of doing it though).

This was the way that I did it:

plt.hist([1,11,21,31,41], bins=[0,10,20,30,40,50], weights=[10,1,40,33,6]);

Which creates this:

image showing histogram graph created in matplotlib

So the first parameter basically 'initialises' the bin - I'm specifically creating a number that is in between the range I set in the bins parameter.

To demonstrate this, look at the array in the first parameter ([1,11,21,31,41]) and the 'bins' array in the second parameter ([0,10,20,30,40,50]):

  • The number 1 (from the first array) falls between 0 and 10 (in the 'bins' array)
  • The number 11 (from the first array) falls between 11 and 20 (in the 'bins' array)
  • The number 21 (from the first array) falls between 21 and 30 (in the 'bins' array), etc.

Then I'm using the 'weights' parameter to define the size of each bin. This is the array used for the weights parameter: [10,1,40,33,6].

So the 0 to 10 bin is given the value 10, the 11 to 20 bin is given the value of 1, the 21 to 30 bin is given the value of 40, etc.

use a javascript array to fill up a drop down select box

Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

var cuisines = ["Chinese","Indian"];     
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisines[i];
    opt.value = cuisines[i];
    sel.appendChild(opt);
}

DEMO

UPDATE: Using createDocumentFragment and forEach

If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();

cuisines.forEach(function(cuisine, index) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisine;
    opt.value = cuisine;
    fragment.appendChild(opt);
});

sel.appendChild(fragment);

DEMO

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

Wrap text in <td> tag

HTML tables support a "table-layout:fixed" css style that prevents the user agent from adapting column widths to their content. You might want to use it.

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Just a few lines in the /etc/mysql/mariadb.conf.d/50-server.cnf or wherever your config is:

innodb-file-format=barracuda
innodb-file-per-table=ON
innodb-large-prefix=ON
innodb_default_row_format = 'DYNAMIC'

and sudo service mysql restart

https://stackoverflow.com/a/57465235/778234

See the docs: https://dev.mysql.com/doc/refman/5.6/en/innodb-row-format.html

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

how to Call super constructor in Lombok

Lombok does not support that also indicated by making any @Value annotated class final (as you know by using @NonFinal).

The only workaround I found is to declare all members final yourself and use the @Data annotation instead. Those subclasses need to be annotated by @EqualsAndHashCode and need an explicit all args constructor as Lombok doesn't know how to create one using the all args one of the super class:

@Data
public class A {
    private final int x;
    private final int y;
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }
}

Especially the constructors of the subclasses make the solution a little untidy for superclasses with many members, sorry.

Can we pass an array as parameter in any function in PHP?

In php 5, you can also hint the type of the passed variable:

function sendemail(array $id, $userid){
  //function body
}

See type hinting.

Is it possible to use a div as content for Twitter's Popover

In addition to other replies. If you allow html in options you can pass jQuery object to content, and it will be appended to popover's content with all events and bindings. Here is the logic from source code:

  • if you pass a function it will be called to unwrap content data
  • if html is not allowed content data will be applied as text
  • if html allowed and content data is string it will be applied as html
  • otherwise content data will be appended to popover's content container
$("#popover-button").popover({
    content: $("#popover-content"),
    html: true,
    title: "Popover title"
});

How can strings be concatenated?

you can also do this:

section = "C_type"
new_section = "Sec_%s" % section

This allows you not only append, but also insert wherever in the string:

section = "C_type"
new_section = "Sec_%s_blah" % section

How can I write a byte array to a file in Java?

         File file = ...
         byte[] data = ...
         try{
            FileOutputStream fos = FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
         }catch(Exception e){
          }

but if the bytes array length is more than 1024 you should use loop to write the data.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Polling the keyboard (detect a keypress) in python

I've come across a cross-platform implementation of kbhit at http://home.wlu.edu/~levys/software/kbhit.py (made edits to remove irrelevant code):

import os
if os.name == 'nt':
    import msvcrt
else:
    import sys, select

def kbhit():
    ''' Returns True if a keypress is waiting to be read in stdin, False otherwise.
    '''
    if os.name == 'nt':
        return msvcrt.kbhit()
    else:
        dr,dw,de = select.select([sys.stdin], [], [], 0)
        return dr != []

Make sure to read() the waiting character(s) -- the function will keep returning True until you do!

How to parse a JSON string to an array using Jackson

The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Sorting {

    private String property;

    private String direction;

    public Sorting() {

    }

    public Sorting(String property, String direction) {
        this.property = property;
        this.direction = direction;
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
        ObjectMapper mapper = new ObjectMapper();
        Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
        System.out.println(sortings);
    }
}

Updating and committing only a file's permissions using git version control

@fooMonster article worked for me

# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe    script.sh

As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:

# git update-index --chmod=+x script.sh

commit the changes

# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh