Programs & Examples On #Coloranimation

Excel Define a range based on a cell value

This should be close to what you are looking for your first example:

=SUM(INDIRECT("A1:A"&B1,TRUE))

This should be close to what you are looking for your final example:

=SUM(INDIRECT("A"&1+B1&":A"&B1,TRUE))

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

In recent kernels (not sure since when) you can list the contents of /dev/serial to get a list of the serial ports on your system. They are actually symlinks pointing to the correct /dev/ node:

flu0@laptop:~$ ls /dev/serial/
total 0
drwxr-xr-x 2 root root 60 2011-07-20 17:12 by-id/
drwxr-xr-x 2 root root 60 2011-07-20 17:12 by-path/
flu0@laptop:~$ ls /dev/serial/by-id/
total 0
lrwxrwxrwx 1 root root 13 2011-07-20 17:12 usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0 -> ../../ttyUSB0
flu0@laptop:~$ ls /dev/serial/by-path/
total 0
lrwxrwxrwx 1 root root 13 2011-07-20 17:12 pci-0000:00:0b.0-usb-0:3:1.0-port0 -> ../../ttyUSB0

This is a USB-Serial adapter, as you can see. Note that when there are no serial ports on the system, the /dev/serial/ directory does not exists. Hope this helps :).

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How to set TLS version on apache HttpClient

If you have a javax.net.ssl.SSLSocket class reference in your code, you can set the enabled TLS protocols by a call to SSLSocket.setEnabledProtocols():

import javax.net.ssl.*;
import java.net.*; 
...
Socket socket = SSLSocketFactory.getDefault().createSocket();
...
if (socket instanceof SSLSocket) {
   // "TLSv1.0" gives IllegalArgumentException in Java 8
   String[] protos = {"TLSv1.2", "TLSv1.1"}
   ((SSLSocket)socket).setEnabledProtocols(protos);
}

ECMAScript 6 class destructor

I just came across this question in a search about destructors and I thought there was an unanswered part of your question in your comments, so I thought I would address that.

thank you guys. But what would be a good convention if ECMAScript doesn't have destructors? Should I create a method called destructor and call it manually when I'm done with the object? Any other idea?

If you want to tell your object that you are now done with it and it should specifically release any event listeners it has, then you can just create an ordinary method for doing that. You can call the method something like release() or deregister() or unhook() or anything of that ilk. The idea is that you're telling the object to disconnect itself from anything else it is hooked up to (deregister event listeners, clear external object references, etc...). You will have to call it manually at the appropriate time.

If, at the same time you also make sure there are no other references to that object, then your object will become eligible for garbage collection at that point.

ES6 does have weakMap and weakSet which are ways of keeping track of a set of objects that are still alive without affecting when they can be garbage collected, but it does not provide any sort of notification when they are garbage collected. They just disappear from the weakMap or weakSet at some point (when they are GCed).


FYI, the issue with this type of destructor you ask for (and probably why there isn't much of a call for it) is that because of garbage collection, an item is not eligible for garbage collection when it has an open event handler against a live object so even if there was such a destructor, it would never get called in your circumstance until you actually removed the event listeners. And, once you've removed the event listeners, there's no need for the destructor for this purpose.

I suppose there's a possible weakListener() that would not prevent garbage collection, but such a thing does not exist either.


FYI, here's another relevant question Why is the object destructor paradigm in garbage collected languages pervasively absent?. This discussion covers finalizer, destructor and disposer design patterns. I found it useful to see the distinction between the three.


Edit in 2020 - proposal for object finalizer

There is a Stage 3 EMCAScript proposal to add a user-defined finalizer function after an object is garbage collected.

A canonical example of something that would benefit from a feature like this is an object that contains a handle to an open file. If the object is garbage collected (because no other code still has a reference to it), then this finalizer scheme allows one to at least put a message to the console that an external resource has just been leaked and code elsewhere should be fixed to prevent this leak.

If you read the proposal thoroughly, you will see that it's nothing like a full-blown destructor in a language like C++. This finalizer is called after the object has already been destroyed and you have to predetermine what part of the instance data needs to be passed to the finalizer for it to do its work. Further, this feature is not meant to be relied upon for normal operation, but rather as a debugging aid and as a backstop against certain types of bugs. You can read the full explanation for these limitations in the proposal.

Cast Double to Integer in Java

Memory efficient, as it will share the already created instance of Double.

Double.valueOf(Math.floor(54644546464/60*60*24*365)).intValue()

Releasing memory in Python

I'm guessing the question you really care about here is:

Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?

No, there is not. But there is an easy workaround: child processes.

If you need 500MB of temporary storage for 5 minutes, but after that you need to run for another 2 hours and won't touch that much memory ever again, spawn a child process to do the memory-intensive work. When the child process goes away, the memory gets released.

This isn't completely trivial and free, but it's pretty easy and cheap, which is usually good enough for the trade to be worthwhile.

First, the easiest way to create a child process is with concurrent.futures (or, for 3.1 and earlier, the futures backport on PyPI):

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    result = executor.submit(func, *args, **kwargs).result()

If you need a little more control, use the multiprocessing module.

The costs are:

  • Process startup is kind of slow on some platforms, notably Windows. We're talking milliseconds here, not minutes, and if you're spinning up one child to do 300 seconds' worth of work, you won't even notice it. But it's not free.
  • If the large amount of temporary memory you use really is large, doing this can cause your main program to get swapped out. Of course you're saving time in the long run, because that if that memory hung around forever it would have to lead to swapping at some point. But this can turn gradual slowness into very noticeable all-at-once (and early) delays in some use cases.
  • Sending large amounts of data between processes can be slow. Again, if you're talking about sending over 2K of arguments and getting back 64K of results, you won't even notice it, but if you're sending and receiving large amounts of data, you'll want to use some other mechanism (a file, mmapped or otherwise; the shared-memory APIs in multiprocessing; etc.).
  • Sending large amounts of data between processes means the data have to be pickleable (or, if you stick them in a file or shared memory, struct-able or ideally ctypes-able).

Using an Alias in a WHERE clause

It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.

SELECT A.identifier
     , A.name
     , vars.MONTH_NO
     , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
     , table_b B ON A.identifier = B.identifier
OUTER APPLY (
   SELECT
        -- variables
        MONTH_NO = TO_NUMBER(DECODE( A.month_no
                     , 1, 200803 
                     , 2, 200804 
                     , 3, 200805 
                     , 4, 200806 
                     , 5, 200807 
                     , 6, 200808 
                     , 7, 200809 
                     , 8, 200810 
                     , 9, 200811 
                     , 10, 200812 
                     , 11, 200701 
                     , 12, 200702
                     , NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE

Kudos to Syed Mehroz Alam.

Object Library Not Registered When Adding Windows Common Controls 6.0

On 32-bit machines:

cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

or on 64 bit machines:

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

These need to be run as administrator.

using stored procedure in entity framework

Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

enter image description here

Entity

VehicleInfoEntities db = new VehicleInfoEntities();

Stored Procedure

dbo.prcGetMakes()

or

you can add any parameters in your stored procedure inside the brackets ()

dbo.prcGetMakes("BMW")

Controller

public class HomeController : Controller
{
    VehicleInfoEntities db = new VehicleInfoEntities();

    public ActionResult Index()
    {
        var makes = db.prcGetMakes(null);

        return View(makes);
    }
}

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

String to object in JS

You need use JSON.parse() for convert String into a Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

React.createElement: type is invalid -- expected a string

I had this problem when I added a css file to the same folder as the component file.

My import statement was:

import MyComponent from '../MyComponent'

which was fine when there was only a single file, MyComponent.jsx. (I saw this format in an example and gave it a try, then forgot I'd done it)

When I added MyComponent.scss to the same folder, the import then failed. Maybe JavaScript loaded the .scss file instead, and so there was no error.

My conclusion: always specify the file extension even if there is only one file, in case you add another one later.

Setting different color for each series in scatter plot on matplotlib

This question is a bit tricky before Jan 2013 and matplotlib 1.3.1 (Aug 2013), which is the oldest stable version you can find on matpplotlib website. But after that it is quite trivial.

Because present version of matplotlib.pylab.scatter support assigning: array of colour name string, array of float number with colour map, array of RGB or RGBA.

this answer is dedicate to @Oxinabox's endless passion for correcting the 2013 version of myself in 2015.


you have two option of using scatter command with multiple colour in a single call.

  1. as pylab.scatter command support use RGBA array to do whatever colour you want;

  2. back in early 2013, there is no way to do so, since the command only support single colour for the whole scatter point collection. When I was doing my 10000-line project I figure out a general solution to bypass it. so it is very tacky, but I can do it in whatever shape, colour, size and transparent. this trick also could be apply to draw path collection, line collection....

the code is also inspired by the source code of pyplot.scatter, I just duplicated what scatter does without trigger it to draw.

the command pyplot.scatter return a PatchCollection Object, in the file "matplotlib/collections.py" a private variable _facecolors in Collection class and a method set_facecolors.

so whenever you have a scatter points to draw you can do this:

# rgbaArr is a N*4 array of float numbers you know what I mean
# X is a N*2 array of coordinates
# axx is the axes object that current draw, you get it from
# axx = fig.gca()

# also import these, to recreate the within env of scatter command 
import matplotlib.markers as mmarkers
import matplotlib.transforms as mtransforms
from matplotlib.collections import PatchCollection
import matplotlib.markers as mmarkers
import matplotlib.patches as mpatches


# define this function
# m is a string of scatter marker, it could be 'o', 's' etc..
# s is the size of the point, use 1.0
# dpi, get it from axx.figure.dpi
def addPatch_point(m, s, dpi):
    marker_obj = mmarkers.MarkerStyle(m)
    path = marker_obj.get_path()
    trans = mtransforms.Affine2D().scale(np.sqrt(s*5)*dpi/72.0)
    ptch = mpatches.PathPatch(path, fill = True, transform = trans)
    return ptch

patches = []
# markerArr is an array of maker string, ['o', 's'. 'o'...]
# sizeArr is an array of size float, [1.0, 1.0. 0.5...]

for m, s in zip(markerArr, sizeArr):
    patches.append(addPatch_point(m, s, axx.figure.dpi))

pclt = PatchCollection(
                patches,
                offsets = zip(X[:,0], X[:,1]),
                transOffset = axx.transData)

pclt.set_transform(mtransforms.IdentityTransform())
pclt.set_edgecolors('none') # it's up to you
pclt._facecolors = rgbaArr

# in the end, when you decide to draw
axx.add_collection(pclt)
# and call axx's parent to draw_idle()

How to show particular image as thumbnail while implementing share on Facebook?

Sharing on Facebook: How to Improve Your Results by Customizing the Image, Title, and Text

From the link above. For the best possible share, you'll want to suggest 3 pieces of data in your HTML:

  • Title
  • Short description
  • Image

This accomplished by the following, placed inside the 'head' tag of your HTML:

  • Title: <title>INSERT POST TITLE</title>
  • Image: <meta property=og:image content="http://site.com/YOUR_IMAGE.jpg"/>
  • Description: <meta name=description content="INSERT YOUR SUMMARY TEXT"/>

If you website is static HTML, you'll have to do this for every page using your HTML editor.

If you're using a CMS like Drupal, you can automate a lot of it (see above link). If you use wordpress, you can probably implement something similar using the Drupal example as a guideline. I hope you found these useful.

Finally, you can always manually edit your share posts. See this example with illustrations.

How to declare array of zeros in python (or an array of a certain size)

Use this:

bucket = [None] * 100
for i in range(100):
    bucket[i] = [None] * 100

OR

w, h = 100, 100
bucket = [[None] * w for i in range(h)]

Both of them will output proper empty multidimensional bucket list 100x100

Where is jarsigner?

%JAVA_HOME%\bin\jarsigner

You can find jarsigner there. Install jdk first.

Difference between Divide and Conquer Algo and Dynamic Programming

The other difference between divide and conquer and dynamic programming could be:

Divide and conquer:

  1. Does more work on the sub-problems and hence has more time consumption.
  2. In divide and conquer the sub-problems are independent of each other.

Dynamic programming:

  1. Solves the sub-problems only once and then stores it in the table.
  2. In dynamic programming the sub-problem are not independent.

SQL 'like' vs '=' performance

You should also keep in mind that when using like, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.

You should really look at the execution plan for the query and see what it's doing, guess as little as possible.

This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like for StartsWith for this very reason.

Autoplay audio files on an iPad with HTML5

I handled this by attaching an event handler for all the events for which you are allowed to trigger audio to the body element which triggers any html audio elements with autoplay to play once.

var mobile = /iPad|iPhone|iPod|android/.test(navigator.userAgent) && !window.MSStream;
if (mobile) {
    $('body').on('touchstart click doubleclick keydown', function() {
        $("audio[autoplay='autoplay']").each(
            function(){
                this.play();
                this.removeAttribute('autoplay');
            });
    });
}

Display open transactions in MySQL

Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.

SELECT * FROM information_schema.innodb_trx\G

From the document:

The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.

How can I remove an SSH key?

I can confirm that this bug is still present in Ubuntu 19.04 (Disco Dingo). The workaround suggested by VonC worked perfectly, summarizing for my version:

  • Click on Activities tab on top left corner
  • On the search box that comes up, begin typing "startup applications"
  • Click on the "Startup Applications" icon
  • On the box that pops up, select the gnome key ring manager application (can't remember the exact name on the GUI but it is distinctive enough) and remove it.

Next, I tried ssh-add -D again, and after reboot ssh-add -l told me The agent has no identities. I confirmed that I still had the ssh-agent daemon running with ps aux | grep agent. So I added the key I most frequently used with GitHub (ssh-add ~/.ssh/id_ecdsa) and all was good!

Now I can do the normal operations with my most frequently used repository, and if I occasionally require access to the other repository which uses the RSA key, I just dedicate one terminal for it with export GIT_SSH_COMMAND="ssh -i /home/me/.ssh/id_rsa.pub". Solved! Credit goes to VonC for pointing out the bug and the solution.

ISO time (ISO 8601) in Python

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748

UTC to ISO 8601:

import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43

UTC to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00

UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00

Local to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00

Notice there is a bug when using astimezone() on utc time. This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result

For Python 2, see and use pytz.

How to do multiple arguments to map function where one remains the same in python?

def func(a, b, c, d):
 return a + b * c % d
map(lambda x: func(*x), [[1,2,3,4], [5,6,7,8]])

By wrapping the function call with a lambda and using the star unpack, you can do map with arbitrary number of arguments.

What's the equivalent of Java's Thread.sleep() in JavaScript?

There's no direct equivalent, as it'd pause a webpage. However there is a setTimeout(), e.g.:

function doSomething() {
  thing = thing + 1;
  setTimeout(doSomething, 500);
}

Closure example (thanks Daniel):

function doSomething(val) {
  thing = thing + 1;
  setTimeout(function() { doSomething(val) }, 500);
}

The second argument is milliseconds before firing, you can use this for time events or waiting before performing an operation.

Edit: Updated based on comments for a cleaner result.

Why does configure say no C compiler found when GCC is installed?

Try specifying CC while configuring:

CC=/usr/bin/gcc ./configure --prefix=/usr/local/sphinx

Also check if your compiler produces executables. The following should produce an a.out:

echo "int main(){0;}" | gcc -x c -

How do I make a dotted/dashed line in Android?

Similar to tier777 here is a solution for a horizontal line:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-1dp">
        <shape android:shape="line">
            <stroke
                android:width="1dp"
                android:color="#111"
                android:dashWidth="8dp"
                android:dashGap="2dp"
                />
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</layer-list>

The clue is <item android:top="-1dp">.

In order to show dashed line on old devices (<= API 21) you should create a view with android:layerType="software" (see Android dashed line drawable potential ICS bug):

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@drawable/dashed_line"
    android:layerType="software"
    />

Also you can add the same view without android:layerType="software" to layout-v23 for better performance, but I am not sure it will work on all devices with API 23.

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

How to determine total number of open/active connections in ms sql server 2005

This shows the number of connections per each DB:

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame

And this gives the total:

SELECT 
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE 
    dbid > 0

If you need more detail, run:

sp_who2 'Active'

Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)

How to get main div container to align to centre?

I would omit the * { text-align:center } declaration, as it sets center alignment for all elements.

Usually with a fixed width container margin: 0 auto should be enough

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Guys I found the issue

I just tried by adding the qualifier name in employee service finally it solved my issue.

@Service("employeeService")

public class EmployeeServiceImpl implements EmployeeService{

}

How to apply style classes to td classes?

A more definite way to target a td is table tr td { }

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

This error can come not only because of the Date conversions

This error can come when we try to pass date whereas varchar is expected
or
when we try to pass varchar whereas date is expected.

Use to_char(sysdate,'YYYY-MM-DD') when varchar is expected

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

Split a string into array in Perl

Splitting a string by whitespace is very simple:

print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';

This is a special form of split actually (as this function usually takes patterns instead of strings):

As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a literal string composed of a single space character (such as ' ' or "\x20"). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator.


Here's an answer for the original question (with a simple string without any whitespace):

Perhaps you want to split on .gz extension:

my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/, $line;
print $_, "\n" for @abc;

Here I used (?<=...) construct, which is look-behind assertion, basically making split at each point in the line preceded by .gz substring.

If you work with the fixed set of extensions, you can extend the pattern to include them all:

my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt', 'xls', 'gz');
my $patt = join '|', map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/, $line;
print $_, "\n" for @abc;

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

Use this:

import cv2
cap = cv2.VideoCapture('path to video file')
count = 0
while cap.isOpened():
    ret,frame = cap.read()
    cv2.imshow('window-name', frame)
    cv2.imwrite("frame%d.jpg" % count, frame)
    count = count + 1
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows() # destroy all opened windows

List attributes of an object

vars(obj) returns the attributes of an object.

How to change color and font on ListView

You need to create a CustomListAdapter.

public class CustomListAdapter extends ArrayAdapter <String> {

    private Context mContext;
    private int id;
    private List <String>items ;

    public CustomListAdapter(Context context, int textViewResourceId , List<String> list ) 
    {
        super(context, textViewResourceId, list);           
        mContext = context;
        id = textViewResourceId;
        items = list ;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent)
    {
        View mView = v ;
        if(mView == null){
            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(id, null);
        }

        TextView text = (TextView) mView.findViewById(R.id.textView);

        if(items.get(position) != null )
        {
            text.setTextColor(Color.WHITE);
            text.setText(items.get(position));
            text.setBackgroundColor(Color.RED); 
            int color = Color.argb( 200, 255, 64, 64 );
                text.setBackgroundColor( color );

        }

        return mView;
    }

}

The list item looks like this (custom_list.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView"
    android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>

Use the TextView api's to decorate your text to your liking

and you will be using it like this

listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);

How can I "reset" an Arduino board?

I had the same problem on two Arduinos (one Uno, and one Modern Device Freeduino/USB Host board) and the window between reset and the beginning of serial port usage was so small that it was impossible to upload.

I finally fixed the problem by purchasing another Arduino Uno and building an ISP cable per these instructions, and using it to flash the Bare Bones app from the examples into each inaccessible board, using Arduino IDE version 0023, following these instructions to change preferences.txt. (Be sure to save the original file before editing it so you can replace it after you've rescued your Arduino.)

It took one quick upload to fix each board. Such a fast fix after so much grief. You might not want to purchase another Arduino, but consider these benefits:

  • You can overwrite the bootloader on your Arduino to gain more space.
  • Once the bootloader is overwritten, the board will boot faster.
  • Supposedly you can program raw AVRs for special projects, but I have not tried this: Google for ArduinoISP
  • It will quickly fix Arduinos that you block in the future.
  • You can now safely experiment to find ways to prevent serial port usage from locking up the device in the future.

What is the regex for "Any positive integer, excluding 0"

You might try a negative lookahead assertion:

^(?!0+$)\d+$

how to make log4j to write to the console as well

Your root logger definition is a bit confused. See the log4j documentation.

This is a standard Java properties file, which means that lines are treated as key=value pairs. Your second log4j.rootLogger line is overwriting the first, which explains why you aren't seeing anything on the console appender.

You need to merge your two rootLogger definitions into one. It looks like you're trying to have DEBUG messages go to the console and INFO messages to the file. The root logger can only have one level, so you need to change your configuration so that the appenders have appropriate levels.

While I haven't verified that this is correct, I'd guess it'll look something like this:

log4j.rootLogger=DEBUG,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender

Note that you also have an error in casing - you have console lowercase in one place and in CAPS in another.

Check if a folder exist in a directory and create them using C#

using System;
using System.IO;
using System.Windows.Forms;

namespace DirCombination 
{
    public partial class DirCombination : Form
    {
        private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt";
        private string _finalPath = null;
        private string _error = null;

        public DirCombination()
        {
            InitializeComponent();

            if (!FSParse(_Path))
                Console.WriteLine(_error);
            else
                Console.WriteLine(_finalPath);
        }

        private bool FSParse(string path)
        {
            try
            {
                string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':');
                string NewPath = Splited[0] + ":";
                if (Directory.Exists(NewPath))
                {                    
                    string[] Paths = Splited[1].Substring(1).Split('/');

                    for (int i = 0; i < Paths.Length - 1; i++)
                    {
                        NewPath += "/";
                        if (!string.IsNullOrEmpty(Paths[i]))
                        {
                            NewPath += Paths[i];
                            if (!Directory.Exists(NewPath))
                                Directory.CreateDirectory(NewPath);
                        }
                    }

                    if (!string.IsNullOrEmpty(Paths[Paths.Length - 1]))
                    {
                        NewPath += "/" + Paths[Paths.Length - 1];
                        if (!File.Exists(NewPath))
                            File.Create(NewPath);
                    }
                    _finalPath = NewPath;
                    return true;
                }
                else
                {
                    _error = "Drive is not exists!";
                    return false;
                }
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return false;
            }
        }
    }
}

Checking for a null object in C++

  • What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
  • Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)

No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.

  • Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?

If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:

int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
  /* Take up to three ints and return the sum of any supplied values.

  Pass null pointers for "not supplied".

  This is NOT an example of good code.
  */
  if (!pa && (pb || pc)) return silly_sum(pb, pc);
  if (!pb && pc) return silly_sum(pa, pc);
  if (pc) return silly_sum(pa, pb) + *pc;
  if (pa && pb) return *pa + *pb;
  if (pa) return *pa;
  if (pb) return *pb;
  return 0;
}

int main() {
  int a = 1, b = 2, c = 3;
  cout << silly_sum(&a, &b, &c) << '\n';
  cout << silly_sum(&a, &b) << '\n';
  cout << silly_sum(&a) << '\n';
  cout << silly_sum(0, &b, &c) << '\n';
  cout << silly_sum(&a, 0, &c) << '\n';
  cout << silly_sum(0, 0, &c) << '\n';
  return 0;
}

If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.

You can use something like boost::optional.

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

How to get JQuery.trigger('click'); to initiate a mouse click

I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements. Then I reverted back to .trigger() it also worked at safari for windows.

So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

How do I determine if a port is open on a Windows server?

Here is what worked for me:

  • Open a command prompt
  • Type telnet
  • Microsoft Telnet>open <host name or IP address><space><port>

It will confirm whether the port is opened.

Why does the arrow (->) operator in C exist?

C also does a good job at not making anything ambiguous.

Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.

How to get first N elements of a list in C#?

        dataGridView1.DataSource = (from S in EE.Stagaire
                                    join F in EE.Filiere on
                                    S.IdFiliere equals F.IdFiliere
                                    where S.Nom.StartsWith("A")
                                    select new
                                    {
                                        ID=S.Id,
                                        Name = S.Nom,
                                        Prénon= S.Prenon,
                                        Email=S.Email,
                                        MoteDePass=S.MoteDePass,
                                        Filiere = F.Filiere1
                                    }).Take(1).ToList();

Simple check for SELECT query empty result

In my sql use information function

select FOUND_ROWS();

it will return the no. of rows returned by select query.

Visually managing MongoDB documents and collections

Here are some popular MongoDB GUI administration tools:

Open source

  • dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.

    dbKoda screenshot

  • Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.

  • adminMongo - web-based or Electron app. Supports server monitoring and document editing.

Closed source

  • NoSQLBoosterfull-featured shell-centric cross-platform GUI tool for MongoDB v2.2-4. Free, Personal, and Commercial editions (feature comparison matrix).
  • MongoDB Compass – provides a graphical user interface that allows you to visualize your schema and perform ad-hoc find queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update queries or access to the shell.
  • Studio 3T, formerly MongoChef – a multi-platform in-place data browser and editor desktop GUI for MongoDB (Core version is free for personal and non-commercial use). Last commit: 2017-Jul-24
  • Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04

  • HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.

  • Database Master – a Windows based MongoDB Management Studio, supports also RDBMS. (not free)
  • SlamData - an open source web-based user-interface that allows you to upload and download data, run queries, build charts, explore data.

Abandoned projects

  • RockMongo – a MongoDB administration tool, written in PHP5. Allegedly the best in the PHP world. Similar to PHPMyAdmin. Last version: 2015-Sept-19
  • Fang of Mongo – a web-based UI built with Django and jQuery. Last commit: 2012-Jan-26, in a forked project.
  • Opricot – a browser-based MongoDB shell written in PHP. Latest version: 2010-Sep-21
  • Futon4Mongo – a clone of the CouchDB Futon web interface for MongoDB. Last commit: 2010-Oct-09
  • MongoVUE – an elegant GUI desktop application for Windows. Free and non-free versions. Latest version: 2014-Jan-20
  • UMongo – a full-featured open-source MongoDB server administration tool for Linux, Windows, Mac; written in Java. Last commit 2014-June
  • Mongo3 – a Ruby/Sinatra-based interface for cluster management. Last commit: Apr 16, 2013

Resetting remote to a certain commit

I solved problem like yours by this commands:

git reset --hard <commit-hash> 
git push -f <remote> <local branch>:<remote branch> 

TypeError: not all arguments converted during string formatting python

In addition to the other two answers, I think the indentations are also incorrect in the last two conditions. The conditions are that one name is longer than the other and they need to start with 'elif' and with no indentations. If you put it within the first condition (by giving it four indentations from the margin), it ends up being contradictory because the lengths of the names cannot be equal and different at the same time.

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

Programmatically generate video or animated GIF in Python?

I understand you asked about converting images to a gif; however, if the original format is MP4, you could use FFmpeg:

ffmpeg -i input.mp4 output.gif

How to create a .NET DateTime from ISO 8601 format

DateTime.ParseExact(...) allows you to tell the parser what each character represents.

How to find the Windows version from the PowerShell command line

I took the scripts above and tweaked them a little to come up with this:

$name=(Get-WmiObject Win32_OperatingSystem).caption
$bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture

$vert = " Version:"
$ver=(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId

$buildt = " Build:"
$build= (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

$installd = Get-ComputerInfo -Property WindowsInstallDateFromRegistry

Write-host $installd
Write-Host $name, $bit, $vert, $ver, `enter code here`$buildt, $build, $installd

To get a result like this:

Microsoft Windows 10 Home 64-bit Version: 1709 Build: 16299.431 @{WindowsInstallDateFromRegistry=18-01-01 2:29:11 AM}

Hint: I'd appreciate a hand stripping the prefix text from the install date so I can replace it with a more readable header.

Easy way to password-protect php page

<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";

if (isset($_COOKIE['PrivatePageLogin'])) {
   if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>

    <!-- LOGGED IN CONTENT HERE -->

<?php
      exit;
   } else {
      echo "Bad Cookie.";
      exit;
   }
}

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['user'] != $username) {
      echo "Sorry, that username does not match.";
      exit;
   } else if ($_POST['keypass'] != $password) {
      echo "Sorry, that password does not match.";
      exit;
   } else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
      setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "Sorry, you could not be logged in at this time.";
   }
}
?>

And the login form on the page...
(On the same page, right below the above^ posted code)

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

Replace duplicate spaces with a single space in T-SQL

I use FOR XML PATH solution to replace multiple spaces into single space

The idea is to replace spaces with XML tags Then split XML string into string fragments without XML tags Finally concatenating those string values by adding single space characters between two

Here is how final UDF function can be called

select dbo.ReplaceMultipleSpaces('   Sample   text  with  multiple  space     ')

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

How to check for the type of a template parameter?

You can specialize your templates based on what's passed into their parameters like this:

template <> void foo<animal> {

}

Note that this creates an entirely new function based on the type that's passed as T. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I have this error as well after upgrading MySQL from 5.6 to 5.7

I figured out that the best solution for me was to combine some of the solutions here and make something of it that worked with the minimum of input.

I use MyPHPAdmin for the simplicity of sending the queries through the interface because then I can check the structure and all that easily. You might use ssh directly or some other interface. The method should be similar or same anyway.

...

1.

First check out the actual error when trying to repair the db:

joomla.jos_menu Note : TIME/TIMESTAMP/DATETIME columns of old format have been upgraded to the new format.

Warning : Incorrect datetime value: '0000-00-00 00:00:00' for column 'checked_out_time' at row 1

Error : Invalid default value for 'checked_out_time'

status : Operation failed

This tells me the column checked_out_time in the table jos_menu needs to have all bad dates fixed as well as the "default" changed.

...

2.

I run the SQL query based on the info in the error message:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE checked_out_time = 0

If you get an error you can use the below query instead that seems to always work:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE CAST(checked_out_time AS CHAR(20)) = '0000-00-00 00:00:00'

...

3.

Then once that is done I run the second SQL query:

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Or in the case it is a date that has to be NULL

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT NULL;

...

If I run repair database now I get:

joomla.jos_menu OK

...

Works just fine :)

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

In Python, when to use a Dictionary, List or Set?

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

How to add a browser tab icon (favicon) for a website?

I've successfully done this for my website.

Only exception is, the SeaMonkey browser requires HTML code inserted in your <head>; whereas, the other browsers will still display the favicon.ico without any HTML insertion. Also, any browser other than IE may use other types of images, not just the .ico format. I hope this helps.

How do you test a public/private DSA keypair?

If it returns nothing, then they match:

cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost

Received fatal alert: handshake_failure through SSLHandshakeException

I meet the same problem today with OkHttp client to GET a https based url. It was caused by Https protocol version and Cipher method mismatch between server side and client side.

1) check your website https Protocol version and Cipher method.

openssl>s_client -connect your_website.com:443 -showcerts

You will get many detail info, the key info is listed as follows:

SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
2) config your http client, for example, in OkHttp client case:
@Test()
public void testHttpsByOkHttp() {
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_0) //protocol version
            .cipherSuites(
                    CipherSuite.TLS_RSA_WITH_RC4_128_SHA, //cipher method
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
            .build();

    OkHttpClient client = new OkHttpClient();
    client.setConnectionSpecs(Collections.singletonList(spec));
    Request request = new Request.Builder().url("https://your_website.com/").build();
    try {
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            logger.debug("result= {}", response.body().string());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This will get what we want.

Calling the base class constructor from the derived class constructor

but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???

Don't panic.

Farm constructor will be called in the constructor of PetStore, automatically.

See the base class inheritance calling rules: What are the rules for calling the superclass constructor?

Move cursor to end of file in vim

Try doing SHIFT + G and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G

How does collections.defaultdict work?

I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:

option = 1

switch(option) {
    case 1: print '1st option'
    case 2: print '2nd option'
    case 3: print '3rd option'
    default: return 'No such option'
}

There is no switch case statements available in python. We can achieve the same by using defaultdict.

from collections import defaultdict

def default_value(): return "Default Value"
dd = defaultdict(default_value)

dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'

print(dd[4])    
print(dd[5])    
print(dd[3])

It prints:

Default Value
Default Value
3rd option

In the above snippet dd has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError is thrown if key is not present. From this it is evident that defaultdict more like a switch case statement where we can avoid a complicated if-elif-elif-else blocks.

One more good example that impressed me a lot from this site is:

>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
...     food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, {'eggs': 1, 'spam': 7})
>>>

If we try to access any items other than eggs and spam we will get a count of 0.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

An update did the trick for me !

$ vagrant box update
$ vagrant plugin install vagrant-vbguest 

PDO Prepared Inserts multiple rows in single query

Here is my solution: https://github.com/sasha-ch/Aura.Sql based on auraphp/Aura.Sql library.

Usage example:

$q = "insert into t2(id,name) values (?,?), ... on duplicate key update name=name"; 
$bind_values = [ [[1,'str1'],[2,'str2']] ];
$pdo->perform($q, $bind_values);

Bugreports are welcome.

Difference between Visual Basic 6.0 and VBA

Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.

This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.

Finding the max/min value in an array of primitives using Java

Using Commons Lang (to convert) + Collections (to min/max)

import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));
        System.out.println(Collections.max(b));
   }
}

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

jQuery if statement, syntax

You can wrap jQuery calls inside normal JavaScript code. So, for example:

$(document).ready(function() {
    if (someCondition && someOtherCondition) {
        // Make some jQuery call.
    }
});

Change project name on Android Studio

To just rename the project:

  1. Refractor and rename the top level directory
  2. Close Android Studio
  3. IMPORT the whole project again

To change the package name:

The easiest and fastest solution is here: https://stackoverflow.com/a/35057550/4908798

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

you are confusing the concept of appending and prepending. the following code is prepending:

sys.path.insert(1,'/thePathToYourFolder/')

it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append() puts things at the very end of the search sequence.

it is advisable that you use something like virtualenv instead of manually coding your package directories into the PYTHONPATH everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:

  1. python ecosystems introduction

  2. bootstrapping python virtual environments

if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

If we need to move from one component to another service then we have to define that service into app.module providers array.

Form inline inside a form horizontal in twitter bootstrap?

Don't nest <form> tags, that will not work. Just use Bootstrap classes.

Bootstrap 3

<form class="form-horizontal" role="form">
    <div class="form-group">
      <label for="inputType" class="col-md-2 control-label">Type</label>
      <div class="col-md-3">
          <input type="text" class="form-control" id="inputType" placeholder="Type">
      </div>
    </div>
    <div class="form-group">
        <span class="col-md-2 control-label">Metadata</span>
        <div class="col-md-6">
            <div class="form-group row">
                <label for="inputKey" class="col-md-1 control-label">Key</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputKey" placeholder="Key">
                </div>
                <label for="inputValue" class="col-md-1 control-label">Value</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputValue" placeholder="Value">
                </div>
            </div>
        </div>
    </div>
</form>

You can achieve that behaviour in many ways, that's just an example. Test it on this bootply

Bootstrap 2

<form class="form-horizontal">
    <div class="control-group">
        <label class="control-label" for="inputType">Type</label>
        <div class="controls">
            <input type="text" id="inputType" placeholder="Type">
        </div>
    </div>
    <div class="control-group">
        <span class="control-label">Metadata</span>
        <div class="controls form-inline">
            <label for="inputKey">Key</label>
            <input type="text" class="input-small" placeholder="Key" id="inputKey">
            <label for="inputValue">Value</label>
            <input type="password" class="input-small" placeholder="Value" id="inputValue">
        </div>
    </div>
</form>

Note that I'm using .form-inline to get the propper styling inside a .controls.
You can test it on this jsfiddle

How to check if a Unix .tar.gz file is a valid file without uncompressing?

A nice option is to use tar -tvvf <filePath> which adds a line that reports the kind of file.

Example in a valid .tar file:

> tar -tvvf filename.tar 
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:46 ./testfolder2/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r--  0 diegoreymendez staff  325377 Jul  5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format,  Compression: none

Corrupted .tar file:

> tar -tvvf corrupted.tar 
tar: Unrecognized archive format
Archive Format: (null),  Compression: none
tar: Error exit delayed from previous errors.

javascript: detect scroll end

Take a look at this example: MDN Element.scrollHeight

I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.

You may use the following snippet:

//attaches the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        scrollTop = target.scrollTop || window.pageYOffset,
        scrollHeight = target.scrollHeight || document.body.scrollHeight;
    if (scrollHeight - scrollTop === $(target).innerHeight()) {
      console.log("? End of scroll");
    }
});

Java: convert seconds to minutes, hours and days

You should try this

import java.util.Scanner;

public class Time_converter {

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int seconds;
        int minutes ;
        int hours;
        System.out.print("Enter the number of seconds : ");
        seconds = input.nextInt();
        hours = seconds / 3600;
        minutes = (seconds%3600)/60;
        int seconds_output = (seconds% 3600)%60;


        System.out.println("The time entered in hours,minutes and seconds is:");
        System.out.println(hours  + " hours :" + minutes + " minutes:" + seconds_output +" seconds"); 
    }

}

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
    this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

How to start automatic download of a file in Internet Explorer?

For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.

I had trouble in IE10+ downloading a PDF and used @dandavis' download function (https://github.com/rndme/download).

IE10+ needs msSaveBlob.

How to include jQuery in ASP.Net project?

if you build an MVC project, its included by default. otherwise, what Nick said.

jQuery "on create" event for dynamically-created elements

For me binding to the body does not work. Binding to the document using jQuery.bind() does.

$(document).bind('DOMNodeInserted',function(e){
             var target = e.target;
         });

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Command failed due to signal: Segmentation fault: 11

For me it's because I have two bundles with the same name.

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

What's HTML character code 8203?

If you want to search for these invisible characters in your editor and make them visible, you can use a Regular Expression searching for non-ascii characters. Try searching for [^\x00-\x7F]. Tested in IntelliJ IDEA.

docker run <IMAGE> <MULTIPLE COMMANDS>

You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    

how to open a url in python

You could also try:

import os
os.system("start \"\" http://example.com")

This, other than @aaronasterling ´s answer has the advantage that it opens the default web browser. Be sure not to forget the "http://".

Find string between two substrings

Further from Nikolaus Gradwohl answer, I needed to get version number (i.e., 0.0.2) between('ui:' and '-') from below file content (filename: docker-compose.yml):

    version: '3.1'
services:
  ui:
    image: repo-pkg.dev.io:21/website/ui:0.0.2-QA1
    #network_mode: host
    ports:
      - 443:9999
    ulimits:
      nofile:test

and this is how it worked for me (python script):

import re, sys

f = open('docker-compose.yml', 'r')
lines = f.read()
result = re.search('ui:(.*)-', lines)
print result.group(1)


Result:
0.0.2

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Restoring Nuget References?

You need to Enable NuGet package restore at the VS solution level for the restore missing package to work.

enter image description here

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.

Why do you use sudo? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user").

What do you get if you run this?

$ head -n1 /usr/local/bin/pip

This will show you which python binary pip is trying to use. If it's pointing /usr/local/opt/python/bin/python2.7, then try running this:

$ ls -al /usr/local/opt/python/bin/python2.7

If this says "No such file or directory", then pip is trying to use a python binary that has been removed.

Next, try this:

$ which python
$ which python2.7

To see the path of the python binary that's actually working.

Since it looks like pip was successfully installed somewhere, it could be that /usr/local/bin/pip is part of an older installation of pip that's higher up on the PATH. To test that, you may try moving the non-functioning pip binary out of the way like this (might require sudo):

$ mv /usr/local/bin/pip /usr/local/bin/pip.old

Then try running your pip --version command again. Hopefully it picks up the correct version and runs successfully.

How to install VS2015 Community Edition offline

I was unable to find the direct download detailed in davidnr's post. You can download the ISO directly from the Microsoft Download Center here: https://download.microsoft.com/download/b/e/d/bedddfc4-55f4-4748-90a8-ffe38a40e89f/vs2015.3.com_enu.iso.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How can I check if a string is null or empty in PowerShell?

Note that the "if ($str)" and "IsNullOrEmpty" tests don't work comparably in all instances: an assignment of $str=0 produces false for both, and depending on intended program semantics, this could yield a surprise.

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Selenium WebDriver.get(url) does not open the URL

I had the same problem but with Chrome.

Solved it using the following steps

  1. Install Firefox/Chrome webdriver from Google
  2. Put the webdriver in Chrome's directory.

Here's the code and it worked fine

from selenium import webdriver

class InstaBot(object):
    def __init__(self):
        self.driver=webdriver.Chrome("C:\Program 
        Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure 
                                                      #it is chrome driver 
        self.driver.get("https://www.wikipedia.com")
        
        
InstaBot()

how to display employee names starting with a and then b in sql

select name_last, name_first
from employees
where name_last like 'A%' or name_last like 'B%'
order by name_last, name_first asc

AngularJS does not send hidden field value

Found a strange behaviour about this hidden value () and we can't make it to work.

After playing around we found the best way is just defined the value in controller itself after the form scope.

.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {

    $scope.routineForm = {};
    $scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";

    $scope.sendData = function {

// JSON http post action to API 
}

}])

Excel to CSV with UTF8 encoding

A simple workaround is to use Google Spreadsheet. Paste (values only if you have complex formulas) or import the sheet then download CSV. I just tried a few characters and it works rather well.

NOTE: Google Sheets does have limitations when importing. See here.

NOTE: Be careful of sensitive data with Google Sheets.

EDIT: Another alternative - basically they use VB macro or addins to force the save as UTF8. I have not tried any of these solutions but they sound reasonable.

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

Use virtualenv with Python with Visual Studio Code in Ubuntu

Another way is to open Visual Studio Code from a terminal with the virtualenv set and need to perform F1 Python: Select Interpreter and select the required virtualenv.

virtualenv

Creating a Jenkins environment variable using Groovy

For me, the following also worked in Jenkins 2 (2.73.3)

Replace

def pa = new ParametersAction([new StringParameterValue("FOO", foo)])
build.addAction(pa)

with

def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"])
build.addAction(pa)

ParametersAction seems to have a second constructor which allows to pass in "additionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java

find all subsets that sum to a particular value

This my dynamical programming implementation in JS. It will return an array of arrays, each holding the subsequences summing to the provided target value.

_x000D_
_x000D_
function getSummingItems(a,t){_x000D_
  return a.reduce((h,n) => Object.keys(h)_x000D_
                                 .reduceRight((m,k) => +k+n <= t ? (m[+k+n] = m[+k+n] ? m[+k+n].concat(m[k].map(sa => sa.concat(n)))_x000D_
                                                                                      : m[k].map(sa => sa.concat(n)),m)_x000D_
                                                                 :  m, h), {0:[[]]})[t];_x000D_
}_x000D_
var arr = Array(20).fill().map((_,i) => i+1), // [1,2,..,20]_x000D_
    tgt = 42,_x000D_
    res = [];_x000D_
_x000D_
console.time("test");_x000D_
res = getSummingItems(arr,tgt);_x000D_
console.timeEnd("test");_x000D_
console.log("found",res.length,"subsequences summing to",tgt);_x000D_
console.log(JSON.stringify(res));
_x000D_
_x000D_
_x000D_

"Debug certificate expired" error in Eclipse Android plugins

On a Mac, open the Terminal (current user's directory should open), cd ".android" ("ls" to validate debug.keystore is there). Finally "rm debug.keystore" to remove the file.

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

Can an interface extend multiple interfaces in Java?

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

for example, take a look here: http://www.tutorialspoint.com/java/java_interfaces.htm

Eclipse won't compile/run java file

  • Make a project to put the files in.
    • File -> New -> Java Project
    • Make note of where that project was created (where your "workspace" is)
  • Move your java files into the src folder which is immediately inside the project's folder.
    • Find the project INSIDE Eclipse's Package Explorer (Window -> Show View -> Package Explorer)
    • Double-click on the project, then double-click on the 'src' folder, and finally double-click on one of the java files inside the 'src' folder (they should look familiar!)
  • Now you can run the files as expected.

Note the hollow 'J' in the image. That indicates that the file is not part of a project.

Hollow J means it is not part of a project

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

How to get the index with the key in Python dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

How to make a simple collection view with Swift

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.

Install tkinter for Python

For Fedora >= 25 and python >= 3, we might need to include the dependencies for Tkinter

sudo dnf install python3-tkinter

How to set the title of UIButton as left alignment?

In Swift 5.0 and Xcode 10.2

You have two ways to approaches

1) Direct approach

btn.contentHorizontalAlignment = .left

2) SharedClass example (write once and use every ware)

This is your shared class(like this you access all components properties)

import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    private override init() {

    }
}

//UIButton extension
extension UIButton {
    func btnProperties() {
        contentHorizontalAlignment = .left
    }
}

In your ViewController call like this

button.btnProperties()//This is your button

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to render an array of objects in React?

You can do it in two ways:

First:

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

    return (
      <div>
      {listItems }
      </div>
    );
  }

Second: Directly write the map function in the return

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    return (
      <div>
      {data.map(function(d, idx){
         return (<li key={idx}>{d.name}</li>)
       })}
      </div>
    );
  }

How to describe table in SQL Server 2008?

As a variation of Bridge's answer (I don't yet have enough rep to comment, and didn't feel right about editing that answer), here is a version that works better for me.

SELECT column_name AS [Name],
   IS_NULLABLE AS [Null?],
   DATA_TYPE + CASE
                 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN ''
                 WHEN CHARACTER_MAXIMUM_LENGTH > 99999 THEN ''
                 ELSE '(' + Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) + ')' 
               END AS [Type]
FROM   INFORMATION_SCHEMA.Columns
WHERE  table_name = 'table_name'

Notable changes:

  • Works for types without length. For an int column, I was seeing NULL for the type because the length was null and it wiped out the whole Type column. So don't print any length component (or parens).
  • Change the check for CAST length of -1 to check actual length. I was getting a syntax error because the case resulted in '*' rather than -1. Seems to make more sense to perform an arithmetic check rather than an overflow from the CAST.
  • Don't print length when very long (arbitrarily > 5 digits).

What are the lesser known but useful data structures?

Rope: It's a string that allows for cheap prepends, substrings, middle insertions and appends. I've really only had use for it once, but no other structure would have sufficed. Regular strings and arrays prepends were just far too expensive for what we needed to do, and reversing everthing was out of the question.

Location Services not working in iOS 8

I was pulling my hair out with the same problem. Xcode gives you the error:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

But even if you implement one of the above methods, it won't prompt the user unless there is an entry in the info.plist for NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription.

Add the following lines to your info.plist where the string values represent the reason you you need to access the users location

<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>

I think these entries may have been missing since I started this project in Xcode 5. I'm guessing Xcode 6 might add default entries for these keys but have not confirmed.

You can find more information on these two Settings here

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

Use child_process.execSync but keep output in console

Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.

To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:

var spawn = require('child_process').spawn;

//kick off process of listing files
var child = spawn('ls', ['-l', '/']);

//spit stdout to screen
child.stdout.on('data', function (data) {   process.stdout.write(data.toString());  });

//spit stderr to screen
child.stderr.on('data', function (data) {   process.stdout.write(data.toString());  });

child.on('close', function (code) { 
    console.log("Finished with code " + code);
});

I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.

However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:

var execSync = require('child_process').execSync;

execSync("xterm -title RecursiveFileListing -e ls -latkR /");

This will allow you to see what your command is doing in the new terminal but still have the synchronous call.

Showing all session data at once?

echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";

Display yet formatting then you can view properly.

Read data from a text file using Java

In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

ssh-copy-id no identities found error

Run following command

# ssh-add

If it gives following error: Could not open a connection to your authentication agent

To remove this error, Run following command:

# eval `ssh-agent`

Class method differences in Python: bound, unbound and static

Please read this docs from the Guido First Class everything Clearly explained how Unbound, Bound methods are born.

Rails: select unique values from a column

If I am going right to way then :

Current query

Model.select(:rating)

is returning array of object and you have written query

Model.select(:rating).uniq

uniq is applied on array of object and each object have unique id. uniq is performing its job correctly because each object in array is uniq.

There are many way to select distinct rating :

Model.select('distinct rating').map(&:rating)

or

Model.select('distinct rating').collect(&:rating)

or

Model.select(:rating).map(&:rating).uniq

or

Model.select(:name).collect(&:rating).uniq

One more thing, first and second query : find distinct data by SQL query.

These queries will considered "london" and "london   " same means it will neglect to space, that's why it will select 'london' one time in your query result.

Third and forth query:

find data by SQL query and for distinct data applied ruby uniq mehtod. these queries will considered "london" and "london " different, that's why it will select 'london' and 'london ' both in your query result.

please prefer to attached image for more understanding and have a look on "Toured / Awaiting RFP".

enter image description here

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

Is it possible to use JavaScript to change the meta-tags of the page?

Yes, it is.

E.g. to set the meta-description:

document.querySelector('meta[name="description"]').setAttribute("content", _desc);

PHP: How to send HTTP response code?

If you are here because of Wordpress giving 404's when loading the environment, this should fix the problem:

define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
status_header( 200 );
//$wp_query->is_404=false; // if necessary

The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:

define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
header("HTTP/1.1 200 OK");
header("Status: 200 All rosy");

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

How to center a checkbox in a table cell?

Define the float property of the check element to none:

float: none;

And center the parent element:

text-align: center;

It was the only that works for me.

CSS background image alt attribute

The classical way to achieve this is to put the text into the div and use an image replacement technique.

<div class"ir background-image">Your alt text</div>

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

Get connection string from App.config

Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.

Line Break in HTML Select Option?

If you just want a line break in the dropdown list use this:

<option label="" value="" disabled=""> </option>

window.open target _self v window.location.href?

As others have said, the second approach is usually preferred.

The two code snippets are not exactly equivalent however: the first one actually sets window.opener to the window object itself, whereas the second will leave it as it is, at least under Firefox.

How to break out of nested loops?

A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

for (int i = 0; i < 1000; i++)
{
    int j = 0;

MANUAL_LOOP:;

    if (j < 1000)
    {
       if (condition)
       {
           break;
       }

       j++;
       goto MANUAL_LOOP;
    }
}

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Error in <my code> : object of type 'closure' is not subsettable

I think you meant to do url[i] <- paste(...

instead of url[i] = paste(.... If so replace = with <-.

Excel: VLOOKUP that returns true or false?

ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.

=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))

Android: Internet connectivity change listener

implementation 'com.treebo:internetavailabilitychecker:1.0.1'

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        InternetAvailabilityChecker.init(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
    }
}

Take nth column in a text file

If your file contains n lines, then your script has to read the file n times; so if you double the length of the file, you quadruple the amount of work your script does — and almost all of that work is simply thrown away, since all you want to do is loop over the lines in order.

Instead, the best way to loop over the lines of a file is to use a while loop, with the condition-command being the read builtin:

while IFS= read -r line ; do
    # $line is a single line of the file, as a single string
    : ... commands that use $line ...
done < input_file.txt

In your case, since you want to split the line into an array, and the read builtin actually has special support for populating an array variable, which is what you want, you can write:

while read -r -a line ; do
    echo ""${line[1]}" "${line[3]}"" >> out.txt
done < /path/of/my/text

or better yet:

while read -r -a line ; do
    echo "${line[1]} ${line[3]}"
done < /path/of/my/text > out.txt

However, for what you're doing you can just use the cut utility:

cut -d' ' -f2,4 < /path/of/my/text > out.txt

(or awk, as Tom van der Woerdt suggests, or perl, or even sed).

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

How do I revert my changes to a git submodule?

This worked for me, including recursively into submodules (perhaps that's why your -f didn't work, cause you changed a submodule inside the submodule):

git submodule update -f --recursive

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden, so when setting my pictures to width: 100% the pictures would look vertically cut, and so I forced them to be visible with !important and to avoid showing the slide animation out of the box I set overflow: hidden to the container div of the slide. Hope it works for you.

UPDATE - New Solution:

Original problem -> http://jsfiddle.net/xMddf/1/ (Even if I use overflow-y: visible it becomes "auto" and actually "scroll".)

#content {
    height: 100px;
    width: 200px;
    overflow-x: hidden;
    overflow-y: visible;
}

The new solution -> http://jsfiddle.net/xMddf/2/ (I found a workaround using a wrapper div to apply overflow-x and overflow-y to different DOM elements as James Khoury advised on the problem of combining visible and hidden to a single DOM element.)

#wrapper {
    height: 100px;
    overflow-y: visible;
}
#content {
    width: 200px;
    overflow-x: hidden;
}

How is "mvn clean install" different from "mvn install"?

To stick with the Maven terms:

  • "clean" is a phase of the clean lifecycle
  • "install" is a phase of the default lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

Javascript Confirm popup Yes, No button instead of OK and Cancel

Have a look at http://bootboxjs.com/

Very easy to use:

 bootbox.confirm("Are you sure?", function(result) {
  Example.show("Confirm result: "+result);
});

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

When should I use a List vs a LinkedList

In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.

LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine.

List<T> also offers a lot of support methods - Find, ToArray, etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.

What is a software framework?

Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.

And if you want to make a modern webapp, you don't actually need to use a framework for that, either.

You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]

Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.

You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.

And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.

How can I get the session object if I have the entity-manager?

I was working in Wildfly but I was using

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();

and the correct was

org.hibernate.Session session = (Session) manager.getDelegate();

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

Open https://www.google-analytics.com/analytics.js file in a new tab, copy all the code.

Now create a folder in your web directory, rename it to google-analytics.

Create a text file in the same folder and paste all the code you copied above.

Rename the file ga-local.js

Now change the URL to call your locally hosted Analytics Script file in your Google Analytics Code. It will look something like this i.e. https://domain.xyz/google-analytics/ga.js

Finally, place your NEW google analytics code into the footer of your webpage.

You are good to go. Now check your website of Google PageSpeed Insights. It will not show the warning for Leverage Browser Caching Google Analytics. And the only problem with this solution is, to regularly update the Analytics Script manually.

Docker official registry (Docker Hub) URL

For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be

docker.io/<dockerimagename>:version

The suggestion above of registry.hub.docker.com/library/<dockerimagename> did not work for me.

I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)

How to sort in-place using the merge sort algorithm?

There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.

There are also links to more detailed theoretical analysis by the same author associated with this link.

How to append output to the end of a text file

Using tee with option -a (--append) allows you to append to multiple files at once and also to use sudo (very useful when appending to protected files). Besides that, it is interesting if you need to use other shells besides bash, as not all shells support the > and >> operators

echo "hello world" | sudo tee -a output.txt

This thread has good answers about tee

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

Efficiently getting all divisors of a given number

//DIVISORS IN TIME COMPLEXITY sqrt(n)

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll int n;
    cin >> n;

    for(ll i = 2;  i <= sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i!=i)
                cout << i << endl << n/i<< endl;
            else
                cout << i << endl;
        }
    }
}

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

Regular expressions inside SQL Server

You can write queries like this in SQL Server:

--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'

SQL Server PRINT SELECT (Print a select query result)?

Add

PRINT 'Hardcoded table name -' + CAST(@@RowCount as varchar(10))

immediately after the query.

java.lang.UnsupportedClassVersionError

The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Android LinearLayout : Add border with shadow around a LinearLayout

You create a file .xml in drawable with name drop_shadow.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<item android:state_pressed="true">
        <layer-list>
            <item android:left="4dp" android:top="4dp">
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp"/>
                </shape>
            </item>
            ...
        </layer-list>
    </item>-->
    <item>
        <layer-list>
            <!-- SHADOW LAYER -->
            <!--<item android:top="4dp" android:left="4dp">
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp" />
                </shape>
            </item>-->
            <!-- SHADOW LAYER -->
            <item>
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp" />
                </shape>
            </item>
            <!-- CONTENT LAYER -->
            <item android:bottom="3dp" android:left="1dp" android:right="3dp" android:top="1dp">
                <shape>
                    <solid android:color="#ffffff" />
                    <corners android:radius="1dp" />
                </shape>
            </item>
        </layer-list>
    </item>
</selector>

Then:

<LinearLayout
...
android:background="@drawable/drop_shadow"/>

How can I convert a comma-separated string to an array?

Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

I am seeing the same thing. The error does not happen on insert of a row but on an update. the table I am referencing has two DateTime columns neither of which are nullable.

I have gotten the scenario down to getting the row and immediately saving it (no data changes). The get works fine but the update fails.

We are using NHibernate 3.3.1.4000

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

How to Use TempTable in Stored Procedure?

Here are the steps:

CREATE TEMP TABLE

-- CREATE TEMP TABLE 
Create Table #MyTempTable (
    EmployeeID int
);

INSERT TEMP SELECT DATA INTO TEMP TABLE

-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100

SELECT TEMP TABLE (You can now use this select query)

Select EmployeeID from #MyTempTable

FINAL STEP DROP THE TABLE

Drop Table #MyTempTable

I hope this will help. Simple and Clear :)

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

How do I solve the INSTALL_FAILED_DEXOPT error?

It seems like this error message can have many different causes. The case I came across was on a real device (so the emulator bases solutions did not apply).

Basically, when this happens, set your Logcat filter to Verbose or Warn, which will help you get more information about the cause.

In my case, multiple or conflicting versions of JUnit were being included in the project I was working on (a large existing codebase). The Android app I was trying to deploy had several library projects as dependencies, and I had mistakenly set things up to include multiple JUnit jar files.

I discovered this based on a series of Logcat messages. Note that the WARN line gives the cause:

DEBUG/dalvikvm(4808): DexOpt: 'Ljunit/framework/TestSuite$1;' has an earlier definition; blocking out
11-06 14:30:10.973: WARN/dalvikvm(4808): Invalid file flags in class Ljunit/runner/Sorter$Swapper;: 0209
11-06 14:30:10.973: null/libc(4808): Fatal signal 11 (SIGSEGV) at 0x00000004 (code=1), thread 4808 (dexopt)

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

ImportError: No module named matplotlib.pyplot

This worked for me, inspired by Sheetal Kaul

pip uninstall matplotlib
python3 -m pip install matplotlib

I knew it installed in the wrong place when this worked:

python2.7
import matplotlib

jQuery .load() call doesn't execute JavaScript in loaded HTML file

Test with this in trackingCode.html:

<script type="text/javascript">

    $(function() {

       show_alert();

       function show_alert() {
           alert("Inside the jQuery ready");
       }

    });
 </script>

How do I use raw_input in Python 3

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

In Python, how do I split a string and keep the separators?

Another no-regex solution that works well on Python 3

# Split strings and keep separator
test_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']

def split_and_keep(s, sep):
   if not s: return [''] # consistent with string.split()

   # Find replacement character that is not used in string
   # i.e. just use the highest available character plus one
   # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
   p=chr(ord(max(s))+1) 

   return s.replace(sep, sep+p).split(p)

for s in test_strings:
   print(split_and_keep(s, '<'))


# If the unicode limit is reached it will fail explicitly
unicode_max_char = chr(1114111)
ridiculous_string = '<Hello>'+unicode_max_char+'<World>'
print(split_and_keep(ridiculous_string, '<'))

Python read in string from file and split it into values

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

Convert between UIImage and Base64 string

Swift 5

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image!
}

Note: Tested in xcode 10.2

Swift 4

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image
}

Note: Tested in xcode 9.4.1

Detecting an "invalid date" Date instance in JavaScript

Nice solution! Included in my library of auxiliary functions, now it looks like this:

Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.prototype.toString.call(obj) === '[object Date]';
}

Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.isDate(obj) && !isNaN(obj.getTime());
}

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

How does numpy.newaxis work and when to use it?

What is np.newaxis?

The np.newaxis is just an alias for the Python constant None, which means that wherever you use np.newaxis you could also use None:

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)

Are there alternatives to np.newaxis?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shape you could also reshape the array to add these dimensions:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxis is the easiest way to add dimensions, but it's good to know the alternatives.

When to use np.newaxis?

In several contexts is adding dimensions useful:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow to display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])

How can I control the width of a label tag?

You can either give class name to all label so that all can have same width :

 .class-name {  width:200px;}

Example

.labelname{  width:200px;}

or you can simple give rest of label

label {  width:200px;  display: inline-block;}

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.