Programs & Examples On #Common code

How can I get the last day of the month in C#?

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

How to simulate a real mouse click using java?

it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.

jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
 public static void main(String args[]) {
  Robot bot = null;
  try {
   bot = new Robot();
  } catch (Exception failed) {
   System.err.println("Failed instantiating Robot: " + failed);
  }
  int mask = InputEvent.BUTTON1_DOWN_MASK;
  bot.mouseMove(100, 100);
  bot.mousePress(mask);
  bot.mouseRelease(mask);
 }
}

I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.

otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).

[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?

Write lines of text to a file in R

fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');

Function vs. Stored Procedure in SQL Server

Write a user-defined function when you want to compute and return a value for use in other SQL statements; write a stored procedure when you want instead is to group a possibly-complex set of SQL statements. These are two pretty different use cases, after all!

Count indexes using "for" in Python

Just use

for i in range(0, 5):
    print i

to iterate through your data set and print each value.

For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange

How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

addClass - can add multiple classes on same div?

$('.page-address-edit').addClass('test1 test2 test3');

Ref- jQuery

IIS 7, HttpHandler and HTTP Error 500.21

This situation happens because you haven't installed/start service of ASP.net.

Use below command in windows 7,8,10.

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

What .NET collection provides the fastest search

Have you considered List.BinarySearch(item)?

You said that your large collection is already sorted so this seems like the perfect opportunity? A hash would definitely be the fastest, but this brings about its own problems and requires a lot more overhead for storage.

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

How to find the mysql data directory from command line in windows

Use bellow command from CLI interface

[root@localhost~]# mysqladmin variables -p<password> | grep datadir

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

Bash script plugin for Eclipse?

ShellEd looks promising, does syntax highlighting, and has positive reviews, although I've not tried it myself. It was approved for distro inclusion by Redhat. There's a little more info on the ShellEd plugin page on the Eclipse site, and installation instructions on their wiki.

Note that if you're not running an up-to-date version of Eclipse (as of this writing, Juno) you'll need to use an older version, for instance 2.0.1 is compatible with Indigo.

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

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

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

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

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

MySql server startup error 'The server quit without updating PID file '

Check if you have space left in your drive. I got this problem when no space left in my drive.

Check object empty

let suppose ,

data = {};

if( if(!$.isEmptyObject(data)))
{
     document.write("Object is empty);
}

else{
    document.write("Object is not empty);
}

It worked for me and its an easy way to check if object is empty or not

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

Blade if(isset) is not working Laravel

@isset($usersType)
  // $usersType is defined and is not null...
@endisset

For a detailed explanation refer documentation:

In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions

Bash: Strip trailing linebreak from output

If you want to remove only the last newline, pipe through:

sed -z '$ s/\n$//'

sed won't add a \0 to then end of the stream if the delimiter is set to NUL via -z, whereas to create a POSIX text file (defined to end in a \n), it will always output a final \n without -z.

Eg:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender

And to prove no NUL added:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72                        foo.bar

To remove multiple trailing newlines, pipe through:

sed -Ez '$ s/\n+$//'

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

String.equals() with multiple conditions (and one action on result)

Possibilities:

  • Use String.equals():

    if (some_string.equals("john") ||
        some_string.equals("mary") ||
        some_string.equals("peter"))
    {
    }
    
  • Use a regular expression:

    if (some_string.matches("john|mary|peter"))
    {
    }
    
  • Store a list of strings to be matched against in a Collection and search the collection:

    Set<String> names = new HashSet<String>();
    names.add("john");
    names.add("mary");
    names.add("peter");
    
    if (names.contains(some_string))
    {
    }
    

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

How to post pictures to instagram using API

If it has a UI, it has an "API". Let's use the following example: I want to publish the pic I use in any new blog post I create. Let's assume is Wordpress.

  1. Create a service that is constantly monitoring your blog via RSS.
  2. When a new blog post is posted, download the picture.
  3. (Optional) Use a third party API to apply some overlays and whatnot to your pic.
  4. Place the photo in a well-known location on your PC or server.
  5. Configure Chrome (read above) so that you can use the browser as a mobile.
  6. Using Selenium (or any other of those libraries), simulate the entire process of posting on Instagram.
  7. Done. You should have it.

Editing an item in a list<T>

After adding an item to a list, you can replace it by writing

list[someIndex] = new MyClass();

You can modify an existing item in the list by writing

list[someIndex].SomeProperty = someValue;

EDIT: You can write

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);

Copy Data from a table in one Database to another separate database

Hard to say without any idea what you mean by "it didn't work." There are a whole lot of things that can go wrong and any advice we give in troubleshooting one of those paths may lead you further and further from finding a solution, which may be really simple.

Here's a something I would look for though,

Identity Insert must be on on the table you are importing into if that table contains an identity field and you are manually supplying it. Identity Insert can also only be enabled for 1 table at a time in a database, so you must remember to enable it for the table, then disable it immediately after you are done importing.

Also, try listing out all your fields

INSERT INTO db1.user.MyTable (Col1, Col2, Col3)
SELECT Col1, COl2, Col3 FROM db2.user.MyTable

How do you implement a circular buffer in C?

// Note power of two buffer size
#define kNumPointsInMyBuffer 1024 

typedef struct _ringBuffer {
    UInt32 currentIndex;
    UInt32 sizeOfBuffer;
    double data[kNumPointsInMyBuffer];
} ringBuffer;

// Initialize the ring buffer
ringBuffer *myRingBuffer = (ringBuffer *)calloc(1, sizeof(ringBuffer));
myRingBuffer->sizeOfBuffer = kNumPointsInMyBuffer;
myRingBuffer->currentIndex = 0;

// A little function to write into the buffer
// N.B. First argument of writeIntoBuffer() just happens to have the
// same as the one calloc'ed above. It will only point to the same
// space in memory if the calloc'ed pointer is passed to
// writeIntoBuffer() as an arg when the function is called. Consider
// using another name for clarity
void writeIntoBuffer(ringBuffer *myRingBuffer, double *myData, int numsamples) {
    // -1 for our binary modulo in a moment
    int buffLen = myRingBuffer->sizeOfBuffer - 1;
    int lastWrittenSample = myRingBuffer->currentIndex;

    int idx;
    for (int i=0; i < numsamples; ++i) {
        // modulo will automagically wrap around our index
        idx = (i + lastWrittenSample) & buffLen; 
        myRingBuffer->data[idx] = myData[i];
    }

    // Update the current index of our ring buffer.
    myRingBuffer->currentIndex += numsamples;
    myRingBuffer->currentIndex &= myRingBuffer->sizeOfBuffer - 1;
}

As long as your ring buffer's length is a power of two, the incredibly fast binary "&" operation will wrap around your index for you. For my application, I'm displaying a segment of audio to the user from a ring buffer of audio acquired from a microphone.

I always make sure that the maximum amount of audio that can be displayed on screen is much less than the size of the ring buffer. Otherwise you might be reading and writing from the same chunk. This would likely give you weird display artifacts.

How do I make flex box work in safari?

display: flex;
display: -webkit-box;

did it for me. Also there were two display: flex; on the same element from different classes. So I removed the other one.

Make function wait until element exists

You can check if the dom already exists by setting a timeout until it is already rendered in the dom.

var panelMainWrapper = document.getElementById('panelMainWrapper');
setTimeout(function waitPanelMainWrapper() {
    if (document.body.contains(panelMainWrapper)) {
        $("#panelMainWrapper").html(data).fadeIn("fast");
    } else {
        setTimeout(waitPanelMainWrapper, 10);
    }
}, 10);

std::wstring VS std::string

  1. When you want to store 'wide' (Unicode) characters.
  2. Yes: 255 of them (excluding 0).
  3. Yes.
  4. Here's an introductory article: http://www.joelonsoftware.com/articles/Unicode.html

To find first N prime numbers in python

The line k = k-1 does not do what you think. It has no effect. Changing k does not affect the loop. At each iteration, k is assigned to the next element of the range, so any changes you have made to k inside the loop will be overwritten.

Export DataBase with MySQL Workbench with INSERT statements

I had some problems to find this option in newer versions, so for Mysql Workbench 6.3, go to schemas and enter in your connection:

enter image description here


Go to Tools -> Data Export

enter image description here


Click on Advanced Options

enter image description here


Scroll down and uncheck extended-inserts

enter image description here


Then export the data you want and you will see the result file as this:

enter image description here

Rolling back local and remote git repository by 1 commit

For Windows Machines, use:

git reset HEAD~1  #Remove Commit Locally

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

Comparing object properties in c#

I ended up doing this:

    public static string ToStringNullSafe(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
    public static bool Compare<T>(T a, T b)
    {
        int count = a.GetType().GetProperties().Count();
        string aa, bb;
        for (int i = 0; i < count; i++)
        {
            aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
            bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
            if (aa != bb)
            {
                return false;
            }
        }
        return true;
    }

Usage:

    if (Compare<ObjectType>(a, b))

Update

If you want to ignore some properties by name:

    public static string ToStringNullSafe(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
    public static bool Compare<T>(T a, T b, params string[] ignore)
    {
        int count = a.GetType().GetProperties().Count();
        string aa, bb;
        for (int i = 0; i < count; i++)
        {
            aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
            bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
            if (aa != bb && ignore.Where(x => x == a.GetType().GetProperties()[i].Name).Count() == 0)
            {
                return false;
            }
        }
        return true;
    }

Usage:

    if (MyFunction.Compare<ObjType>(a, b, "Id","AnotherProp"))

Add Header and Footer for PDF using iTextsharp

pdfDoc.Open();
Paragraph para = new Paragraph("Hello World", new Font(Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(para);
pdfDoc.Add(new Paragraph("\r\n"));
htmlparser.Parse(sr);
pdfDoc.Close();

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.

How to exclude 0 from MIN formula Excel

Enter the following into the result cell and then press Ctrl & Shift while pushing ENTER:

=MIN(If(A1:E1>0,A1:E1))

How to store printStackTrace into a string

Something along the lines of

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

Ought to be what you need.

Relevant documentation:

Why does corrcoef return a matrix?

You can use the following function to return only the correlation coefficient:

def pearson_r(x, y):
"""Compute Pearson correlation coefficient between two arrays."""

   # Compute correlation matrix
   corr_mat = np.corrcoef(x, y)

   # Return entry [0,1]
   return corr_mat[0,1]

Converting List<Integer> to List<String>

As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):

List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<>(oldList.size());
for (Integer myInt : oldList) { 
  newList.add(String.valueOf(myInt)); 
}

php is null or empty?

If you use ==, php treats an empty string or array as null. To make the distinction between null and empty, either use === or is_null. So:

if($a === NULL) or if(is_null($a))

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

Setting selected option in laravel form

Another ordinary simple way this is good if there are few options in select box

<select name="job_status">
   <option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}}  value="unemployed">Unemployed</option>
   <option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>
</select>

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

ReportViewer Client Print Control "Unable to load client print control"?

Unable to load Client Print Control!
Everytime, clients wanted to print report by clicking the button print on their report viewer, they always got this error message.

I had spent nearly two weeks to fix this problem.
My environment is:
- Window Server 2003 Standard Edition R2
- Report Server Version 10.X.X.X
- Clients with windowXP SP3
My Solution is:
- Replacing the CAP file (RSClientPrint-x86.cab) in C\Program Files\Microsoft SQL
Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin\
- Extract the RSClientPrint-x86.cab and destribute it to clients.


Hear is the CAB file: https://sites.google.com/site/narithsite/Home/RSClientPrint-x86.cab?attredirects=0&d=1

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

How to stop a looping thread in Python?

Depends on what you run in that thread. If that's your code, then you can implement a stop condition (see other answers).

However, if what you want is to run someone else's code, then you should fork and start a process. Like this:

import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()

now, whenever you want to stop that process, send it a SIGTERM like this:

proc.terminate()
proc.join()

And it's not slow: fractions of a second. Enjoy :)

Find element in List<> that contains a value

Either use LINQ:

var value = MyList.First(item => item.name == "foo").value;

(This will just find the first match, of course. There are lots of options around this.)

Or use Find instead of FindIndex:

var value = MyList.Find(item => item.name == "foo").value;

I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.

(I'd also suggest following the .NET naming conventions.)

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Removing spaces from string

I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:

String field = field.replaceAll("\\s+", "");

how to pass list as parameter in function

public void SomeMethod(List<DateTime> dates)
{
    // do something
}

How to detect if URL has changed after hash in JavaScript

While doing a little chrome extension, I faced the same problem with an additionnal problem : Sometimes, the page change but not the URL.

For instance, just go to the Facebook Homepage, and click on the 'Home' button. You will reload the page but the URL won't change (one-page app style).

99% of the time, we are developping websites so we can get those events from Frameworks like Angular, React, Vue etc..

BUT, in my case of a Chrome extension (in Vanilla JS), I had to listen to an event that will trigger for each "page change", which can generally be caught by URL changed, but sometimes it doesn't.

My homemade solution was the following :

listen(window.history.length);
var oldLength = -1;
function listen(currentLength) {
  if (currentLength != oldLength) {
    // Do your stuff here
  }

  oldLength = window.history.length;
  setTimeout(function () {
    listen(window.history.length);
  }, 1000);
}

So basically the leoneckert solution, applied to window history, which will change when a page changes in a single page app.

Not rocket science, but cleanest solution I found, considering we are only checking an integer equality here, and not bigger objects or the whole DOM.

Jquery to get the id of selected value from dropdown

Try this

on change event

$("#jodSel").on('change',function(){
    var getValue=$(this).val();
    alert(getValue);
  });

Note: In dropdownlist if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id attribute inside option its not standard paractise though i did both in my answer but i prefer example 1

HTML Markup

Example 1:
    <select id="example1">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
        <option value="4">four</option>
    </select>
Example 2 :
    <select id="example2">
        <option id="1">one</option>
        <option id="2">two</option>
        <option id="3">three</option>
        <option id="4">four</option>
    </select>

Jquery:

$("#example1").on('change', function () {
    alert($(this).val());
});

$("#example2").on('change', function () {
    alert($(this).find('option:selected').attr('id'));
});

View Demo : For example 1 & 2

Blog Article : Get and Set dropdown list selected value with Jquery

My Blog : jQuery tutorials

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

CSS for the "down arrow" on a <select> element?

The drop-down is platform-level element, you can't apply CSS to it.

You can overlay an image on top of it using CSS, and call the click event in the element beneath.

What is a callback in java

Strictly speaking, the concept of a callback function does not exist in Java, because in Java there are no functions, only methods, and you cannot pass a method around, you can only pass objects and interfaces. So, whoever has a reference to that object or interface may invoke any of its methods, not just one method that you might wish them to.

However, this is all fine and well, and we often speak of callback objects and callback interfaces, and when there is only one method in that object or interface, we may even speak of a callback method or even a callback function; we humans tend to thrive in inaccurate communication.

(Actually, perhaps the best approach is to just speak of "a callback" without adding any qualifications: this way, you cannot possibly go wrong. See next sentence.)

One of the most famous examples of using a callback in Java is when you call an ArrayList object to sort itself, and you supply a comparator which knows how to compare the objects contained within the list.

Your code is the high-level layer, which calls the lower-level layer (the standard java runtime list object) supplying it with an interface to an object which is in your (high level) layer. The list will then be "calling back" your object to do the part of the job that it does not know how to do, namely to compare elements of the list. So, in this scenario the comparator can be thought of as a callback object.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

I had the perf counter reg issue and here's what I did.

  1. My exe file was SQLManagementStudio_x86_ENU.exe
  2. In command line typed in the below line and hit enter

C:\Projects\Installer\SQL Server 2008 Management Studio\SQLManagementStudio_x86_ENU.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

(Note : i had the exe in this location of my machine C:\Projects\Installer\SQL Server 2008 Management Studio)

  1. SQL Server installation started and this time it skipped the rule for Perf counter registry values. The installation was successful.

PHP Get all subdirectories of a given directory

Find all PHP files recursively. The logic should be simple enough to tweak and it aims to be fast(er) by avoiding function calls.

function get_all_php_files($directory) {
    $directory_stack = array($directory);
    $ignored_filename = array(
        '.git' => true,
        '.svn' => true,
        '.hg' => true,
        'index.php' => true,
    );
    $file_list = array();
    while ($directory_stack) {
        $current_directory = array_shift($directory_stack);
        $files = scandir($current_directory);
        foreach ($files as $filename) {
            //  Skip all files/directories with:
            //      - A starting '.'
            //      - A starting '_'
            //      - Ignore 'index.php' files
            $pathname = $current_directory . DIRECTORY_SEPARATOR . $filename;
            if (isset($filename[0]) && (
                $filename[0] === '.' ||
                $filename[0] === '_' ||
                isset($ignored_filename[$filename])
            )) 
            {
                continue;
            }
            else if (is_dir($pathname) === TRUE) {
                $directory_stack[] = $pathname;
            } else if (pathinfo($pathname, PATHINFO_EXTENSION) === 'php') {
                $file_list[] = $pathname;
            }
        }
    }
    return $file_list;
}

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

How to set default font family for entire Android app

The answer is yes.

Global Roboto light for TextView and Button classes:

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
    <item name="android:buttonStyle">@style/RobotoButtonStyle</item>
</style>

<style name="RobotoTextViewStyle" parent="android:Widget.TextView">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="RobotoButtonStyle" parent="android:Widget.Holo.Button">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

Just select the style you want from list themes.xml, then create your custom style based on the original one. At the end, apply the style as the theme of the application.

<application
    android:theme="@style/AppTheme" >
</application>

It will work only with built-in fonts like Roboto, but that was the question. For custom fonts (loaded from assets for example) this method will not work.

EDIT 08/13/15

If you're using AppCompat themes, remember to remove android: prefix. For example:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
    <item name="buttonStyle">@style/RobotoButtonStyle</item>
</style>

Note the buttonStyle doesn't contain android: prefix, but textViewStyle must contain it.

What jsf component can render a div tag?

I think we can you use verbatim tag, as in this tag we use any of the HTML tags

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

How to run a makefile in Windows?

If you install Cygwin. Make sure to select make in the installer. You can then run the following command provided you have a Makefile.

make -f Makefile

https://cygwin.com/install.html

Uncaught SyntaxError: Unexpected token with JSON.parse

I found the same issue with JSON.parse(inputString).

In my case the input string is coming from my server page [return of a page method].

I printed the typeof(inputString) - it was string, still the error occurs.

I also tried JSON.stringify(inputString), but it did not help.

Later I found this to be an issue with the new line operator [\n], inside a field value.

I did a replace [with some other character, put the new line back after parse] and everything is working fine.

When do you use the "this" keyword?

Any time you need a reference to the current object.

One particularly handy scenario is when your object is calling a function and wants to pass itself into it.

Example:

void onChange()
{
    screen.draw(this);
}

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can use this command,

jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl

But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.

nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &

Disable output buffering

(I've posted a comment, but it got lost somehow. So, again:)

  1. As I noticed, CPython (at least on Linux) behaves differently depending on where the output goes. If it goes to a tty, then the output is flushed after each '\n'
    If it goes to a pipe/process, then it is buffered and you can use the flush() based solutions or the -u option recommended above.

  2. Slightly related to output buffering:
    If you iterate over the lines in the input with

    for line in sys.stdin:
    ...

then the for implementation in CPython will collect the input for a while and then execute the loop body for a bunch of input lines. If your script is about to write output for each input line, this might look like output buffering but it's actually batching, and therefore, none of the flush(), etc. techniques will help that. Interestingly, you don't have this behaviour in pypy. To avoid this, you can use

while True: line=sys.stdin.readline()
...

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

How do I sort a VARCHAR column in SQL server that contains numbers?

This may help you, I have tried this when i got the same issue.

SELECT * FROM tab ORDER BY IIF(TRY_CAST(val AS INT) IS NULL, 1, 0),TRY_CAST(val AS INT);

Parse string to date with moment.js

Maybe try the Intl polyfill for IE8 or the olyfill service ?

or

https://github.com/andyearnshaw/Intl.js/

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

How to print full stack trace in exception?

Use a function like this:

    public static string FlattenException(Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

Then you can call it like this:

try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(FlattenException(we));
}

Tools to get a pictorial function call graph of code

Astrée is the most robust and sophisticated tool out there, IMHO.

How to have a drop down <select> field in a rails form?

<%= f.select :email_provider, ["gmail","yahoo","msn"]%>

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

C++ - Decimal to binary converting

Your solution needs a modification. The final string should be reversed before returning:

std::reverse(r.begin(), r.end());
return r;

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

How to Get Element By Class in JavaScript?

When some elements lack ID, I use jQuery like this:

$(document).ready(function()
{
    $('.myclass').attr('id', 'myid');
});

This might be a strange solution, but maybe someone find it useful.

How to get the previous URL in JavaScript?

Those of you using Node.js and Express can set a session cookie that will remember the current page URL, thus allowing you to check the referrer on the next page load. Here's an example that uses the express-session middleware:

//Add me after the express-session middleware    
app.use((req, res, next) => {
    req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});

You can then check for the existance of a referrer cookie like so:

if ( req.session.referrer ) console.log(req.session.referrer);

Do not assume that a referrer cookie always exists with this method as it will not be available on instances where the previous URL was another website, the session was cleaned or was just created (first-time website load).

How to install PIP on Python 3.6?

I just successfully installed a package for excel. After installing the python 3.6, you have to download the desired package, then install. For eg,

  1. python.exe -m pip download openpyxl==2.1.4

  2. python.exe -m pip install openpyxl==2.1.4

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");

C# version of java's synchronized keyword?

You can use the lock statement instead. I think this can only replace the second version. Also, remember that both synchronized and lock need to operate on an object.

How do I make a transparent canvas in html5?

Iif you want a particular <canvas id="canvasID"> to be always transparent you just have to set

#canvasID{
    opacity:0.5;
}

Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.

context.fillStyle = "rgba(0, 0, 200, 0.5)";

Xpath for href element

This will get you the generic link:

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();

If you want to have it specify a parameter then you will have to test for each one:

...
int i = 1;

selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...

The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.

Please excuse if the code is not perfect, I have not tested myself.

Filtering lists using LINQ

This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.

List<Person> filteredResults =from p in people
        join e in exclusions on p.compositeKey equals e.compositeKey into temp
        from t in temp.DefaultIfEmpty()
        where t.compositeKey == null
        select p

let me know if it works!

How to see local history changes in Visual Studio Code?

I think there is no out-of-the-box support for that in VS Code.

You can install a plugin to give you similar functionality. Eg.:

https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints

Or the more famous:

https://marketplace.visualstudio.com/items?itemName=xyz.local-history

Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore file also solves this problem).

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

How to parse XML and count instances of a particular node attribute?

xml.etree.ElementTree vs. lxml

These are some pros of the two most used libraries I would have benefit to know before choosing between them.

xml.etree.ElementTree:

  1. From the standard library: no needs of installing any module

lxml

  1. Easily write XML declaration: for instance do you need to add standalone="no"?
  2. Pretty printing: you can have a nice indented XML without extra code.
  3. Objectify functionality: It allows you to use XML as if you were dealing with a normal Python object hierarchy.node.
  4. sourceline allows to easily get the line of the XML element you are using.
  5. you can use also a built-in XSD schema checker.

How to find encoding of a file via script on Linux?

here is an example script using file -I and iconv which works on MacOsX For your question you need to use mv instead of iconv

#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
  encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
  case $encoding in
    iso-8859-1)
    iconv -f iso8859-1 -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

Stop mouse event propagation

The simplest is to call stop propagation on an event handler. $event works the same in Angular 2, and contains the ongoing event (by it a mouse click, mouse event, etc.):

(click)="onEvent($event)"

on the event handler, we can there stop the propagation:

onEvent(event) {
   event.stopPropagation();
}

how do I use an enum value on a switch statement in C++

You can use a std::map to map the input to your enum:

#include <iostream>
#include <string>
#include <map>
using namespace std;

enum level {easy, medium, hard};
map<string, level> levels;

void register_levels()
{
    levels["easy"]   = easy;
    levels["medium"] = medium;
    levels["hard"]   = hard;
}

int main()
{
    register_levels();
    string input;
    cin >> input;
    switch( levels[input] )
    {
    case easy:
        cout << "easy!"; break;
    case medium:
        cout << "medium!"; break;
    case hard:
        cout << "hard!"; break;
    }
}

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv

How to get EditText value and display it on screen through TextView?

Try this->

EditText text = (EditText) findViewById(R.id.text_input);

Editable name = text.getText();

Editable is the return data type of getText() method it will handle both string and integer values

Automatically pass $event with ng-click?

Add a $event to the ng-click, for example:

<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>

Then the jQuery.Event was passed to the callback:

enter image description here

ReCaptcha API v2 Styling

I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform, filter is also applied to iframe elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:

.g-recaptcha {
    filter: invert(1) hue-rotate(180deg);
}

The hue-rotate(180deg) makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()'ed to black and vice versa.

Didn't see this in any answer or comment so decided to share even if this is an old thread.

Difference Between Cohesion and Coupling

simply, Cohesion represents the degree to which a part of a code base forms a logically single, atomic unit. Coupling, on the other hand, represents the degree to which a single unit is independent from others. In other words, it is the number of connections between two or more units. The fewer the number, the lower the coupling.

In essence, high cohesion means keeping parts of a code base that are related to each other in a single place. Low coupling, at the same time, is about separating unrelated parts of the code base as much as possible.

Types of code from a cohesion and coupling perspective:

Ideal is the code that follows the guideline. It is loosely coupled and highly cohesive. We can illustrate such code with this picture: enter image description here

God Object is a result of introducing high cohesion and high coupling. It is an anti-pattern and basically stands for a single piece of code that does all the work at once: enter image description here poorly selected takes place when the boundaries between different classes or modules are selected poorlyenter image description here

Destructive decoupling is the most interesting one. It sometimes occurs when a programmer tries to decouple a code base so much that the code completely loses its focus:enter image description here

read more here

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug

or

cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main

or

strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main

or

gdb
(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file

Ref:
https://sourceware.org/gdb/onlinedocs/gdb/Files.html#Files https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html

How to fix "Headers already sent" error in PHP

You do

printf ("Hi %s,</br />", $name);

before setting the cookies, which isn't allowed. You can't send any output before the headers, not even a blank line.

Overwriting my local branch with remote branch

first, create a new branch in the current position (in case you need your old 'screwed up' history):

git branch fubar-pin

update your list of remote branches and sync new commits:

git fetch --all

then, reset your branch to the point where origin/branch points to:

git reset --hard origin/branch

be careful, this will remove any changes from your working tree!

Matplotlib (pyplot) savefig outputs blank image

change the order of the functions fixed the problem for me:

  • first Save the plot
  • then Show the plot

as following:

plt.savefig('heatmap.png')

plt.show()

remove kernel on jupyter notebook

Run jupyter kernelspec list to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel

jupyter kernelspec uninstall unwanted-kernel

Old answer
Delete the folder corresponding to the kernel you want to remove.

The docs has a list of the common paths for kernels to be stored in: http://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs

How to only find files in a given directory, and ignore subdirectories using bash

If you just want to limit the find to the first level you can do:

 find /dev -maxdepth 1 -name 'abc-*'

... or if you particularly want to exclude the .udev directory, you can do:

 find /dev -name '.udev' -prune -o -name 'abc-*' -print

Cannot open local file - Chrome: Not allowed to load local resource

If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.

If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).

See also:

How to view DLL functions?

Use the free DLL Export Viewer, it is very easy to use.

Python pandas Filtering out nan from a data selection of a column of strings

Just drop them:

nms.dropna(thresh=2)

this will drop all rows where there are at least two non-NaN.

Then you could then drop where name is NaN:

In [87]:

nms
Out[87]:
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

[5 rows x 3 columns]
In [89]:

nms = nms.dropna(thresh=2)
In [90]:

nms[nms.name.notnull()]
Out[90]:
  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

[2 rows x 3 columns]

EDIT

Actually looking at what you originally want you can do just this without the dropna call:

nms[nms.name.notnull()]

UPDATE

Looking at this question 3 years later, there is a mistake, firstly thresh arg looks for at least n non-NaN values so in fact the output should be:

In [4]:
nms.dropna(thresh=2)

Out[4]:
  movie    name  rating
0   thg    John     3.0
1   thg     NaN     4.0
3   mol  Graham     NaN

It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.

Calculate the date yesterday in JavaScript

[edit sept 2020]: a snippet containing previous answer and added an arrow function

_x000D_
_x000D_
// a (not very efficient) oneliner
let yesterday = new Date(new Date().setDate(new Date().getDate()-1));
console.log(yesterday);

// a function call
yesterday = ( function(){this.setDate(this.getDate()-1); return this} )
            .call(new Date);
console.log(yesterday);

// an iife (immediately invoked function expression)
yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date);
console.log(yesterday);

// oneliner using es6 arrow function
yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
console.log(yesterday);

// use a method
const getYesterday = (dateOnly = false) => {
  let d = new Date();
  d.setDate(d.getDate() - 1);
  return dateOnly ? new Date(d.toDateString()) : d;
};
console.log(getYesterday());
console.log(getYesterday(true));
_x000D_
_x000D_
_x000D_

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

Graphviz: How to go from .dot to a graph?

dot -Tps input.dot > output.eps
dot -Tpng input.dot > output.png

PostScript output seems always there. I am not sure if dot has PNG output by default. This may depend on how you have built it.

What is the use of the square brackets [] in sql statements?

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

Getting the PublicKeyToken of .Net assemblies

Another options is to use the open source tool NuGet Package Explorer for this.

From a Nuget package (.nupkg) you could check the PublicKeyToken, or drag the binary (.dll) in the tool. For the latter select first "File -> new"

enter image description here

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

You can also add

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
/> 

under META-INF/context.xml file (This will be only at application level).

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

ssh: check if a tunnel is alive

#!/bin/bash

# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null

# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
  echo ' > You missing ssh tunnel. Creating one..'
  ssh -L 6000:localhost:5432 example.com
fi

echo ' > DO YOUR STUFF < '

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

I got the same error when upgraded angular from 6 to 8.

Simple update angular cli to latest version & node version to 10+.

1) Visit this link to get the latest node version. Angular 8 requires 10+.
2) Execute npm i @angular/cli@latest to update cli.


This is what I have currently

enter image description here

How to create Select List for Country and States/province in MVC

Thank You All! I am able to to load Select List as per MVC now My Working Code is below:

HTML+MVC Code in View:-

    <tr>
        <th>@Html.Label("Country")</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
    </tr>
    <tr>
        <th>@Html.LabelFor(x=>x.Province)</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
    </tr>

Created a Controller under "UTIL" folder: Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedAvail.Applications.MedProvision.Web.Util
{
    public class SelectListItemHelper
    {
        public static IEnumerable<SelectListItem> GetProvincesList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "California", Value = "B"},
                new SelectListItem{Text = "Alaska", Value = "B"},
                new SelectListItem{Text = "Illinois", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


        public static IEnumerable<SelectListItem> GetCountryList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "United States", Value = "B"},
                new SelectListItem{Text = "Canada", Value = "B"},
                new SelectListItem{Text = "United Kingdom", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


    }
}

And its working COOL now :-)

Thank you!!

PHP: Calling another class' method

You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA

class ClassA {
    public function getName() {
      echo $this->name;
    }
}

class ClassB extends ClassA {
    public function getName() {
      parent::getName();
    }
}

Without inheritance or an instance method, you'd need ClassA to have a static method

class ClassA {
  public static function getName() {
    echo "Rawkode";
  }
}

--- other file ---

echo ClassA::getName();

If you're just looking to call the method from an instance of the class:

class ClassA {
  public function getName() {
    echo "Rawkode";
  }
}

--- other file ---

$a = new ClassA();
echo $a->getName();

Regardless of the solution you choose, require 'ClassA.php is needed.

Change CSS class properties with jQuery

You can't change CSS properties directly with jQuery. But you can achieve the same effect in at least two ways.

Dynamically Load CSS from a File

function updateStyleSheet(filename) {
    newstylesheet = "style_" + filename + ".css";

    if ($("#dynamic_css").length == 0) {
        $("head").append("<link>")
        css = $("head").children(":last");

        css.attr({
          id: "dynamic_css",
          rel:  "stylesheet",
          type: "text/css",
          href: newstylesheet
        });
    } else {
        $("#dynamic_css").attr("href",newstylesheet);
    }
}

The example above is copied from:

Dynamically Add a Style Element

$("head").append('<style type="text/css"></style>');
var newStyleElement = $("head").children(':last');
newStyleElement.html('.red{background:green;}');

The example code is copied from this JSFiddle fiddle originally referenced by Alvaro in their comment.

Hiding button using jQuery

You can use the .hide() function bound to a click handler:

$('#Comanda').click(function() {
    $(this).hide();
});

MySQL IF ELSEIF in select query

I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:

case 
  when qty_1<='23' then price
  when '23'>qty_1 && qty_2<='23' then price_2
  when '23'>qty_2 && qty_3<='23' then price_3
  when '23'>qty_3 then price_4
  else 1
end

Android: How to use webcam in emulator?

I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :

http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html

His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

rotate image with css

Give the parent a style of overflow: hidden. If it is overlapping sibling elements, you will have to put it inside of a container with a fixed height/width and give that a style of overflow: hidden.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

select certain columns of a data table

DataView dv = new DataView(Your DataTable);

DataTable dt = dv.ToTable(true, "Your Specific Column Name");

The dt contains only selected column values.

Django: Redirect to previous page after login

Django's built-in authentication works the way you want.

Their login pages include a next query string which is the page to return to after login.

Look at http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

Should I use "camel case" or underscores in python?

for everything related to Python's style guide: i'd recommend you read PEP8.

To answer your question:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

When should I use GC.SuppressFinalize()?

If a class, or anything derived from it, might hold the last live reference to an object with a finalizer, then either GC.SuppressFinalize(this) or GC.KeepAlive(this) should be called on the object after any operation that might be adversely affected by that finalizer, thus ensuring that the finalizer won't run until after that operation is complete.

The cost of GC.KeepAlive() and GC.SuppressFinalize(this) are essentially the same in any class that doesn't have a finalizer, and classes that do have finalizers should generally call GC.SuppressFinalize(this), so using the latter function as the last step of Dispose() may not always be necessary, but it won't be wrong.

How to update PATH variable permanently from Windows command line?

This script http://www.autohotkey.com/board/topic/63210-modify-system-path-gui/

includes all the necessary Windows API calls which can be refactored for your needs. It is actually an AutoHotkey GUI to change the System PATH easily. Needs to be run as an Administrator.

Meaning of delta or epsilon argument of assertEquals for double values

Epsilon is a difference between expected and actual values which you can accept thinking they are equal. You can set .1 for example.

How to test for $null array in PowerShell

You can reorder the operands:

$null -eq $foo

Note that -eq in PowerShell is not an equivalence relation.

When do you use Git rebase instead of Git merge?

TL;DR

If you have any doubt, use merge.

Short Answer

The only differences between a rebase and a merge are:

  • The resulting tree structure of the history (generally only noticeable when looking at a commit graph) is different (one will have branches, the other won't).
  • Merge will generally create an extra commit (e.g. node in the tree).
  • Merge and rebase will handle conflicts differently. Rebase will present conflicts one commit at a time where merge will present them all at once.

So the short answer is to pick rebase or merge based on what you want your history to look like.

Long Answer

There are a few factors you should consider when choosing which operation to use.

Is the branch you are getting changes from shared with other developers outside your team (e.g. open source, public)?

If so, don't rebase. Rebase destroys the branch and those developers will have broken/inconsistent repositories unless they use git pull --rebase. This is a good way to upset other developers quickly.

How skilled is your development team?

Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

I've worked on teams where the developers all came from a time when companies could afford dedicated staff to deal with branching and merging. Those developers don't know much about Git and don't want to know much. In these teams I wouldn't risk recommending rebasing for any reason.

Does the branch itself represent useful information

Some teams use the branch-per-feature model where each branch represents a feature (or bugfix, or sub-feature, etc.) In this model the branch helps identify sets of related commits. For example, one can quickly revert a feature by reverting the merge of that branch (to be fair, this is a rare operation). Or diff a feature by comparing two branches (more common). Rebase would destroy the branch and this would not be straightforward.

I've also worked on teams that used the branch-per-developer model (we've all been there). In this case the branch itself doesn't convey any additional information (the commit already has the author). There would be no harm in rebasing.

Might you want to revert the merge for any reason?

Reverting (as in undoing) a rebase is considerably difficult and/or impossible (if the rebase had conflicts) compared to reverting a merge. If you think there is a chance you will want to revert then use merge.

Do you work on a team? If so, are you willing to take an all or nothing approach on this branch?

Rebase operations need to be pulled with a corresponding git pull --rebase. If you are working by yourself you may be able to remember which you should use at the appropriate time. If you are working on a team this will be very difficult to coordinate. This is why most rebase workflows recommend using rebase for all merges (and git pull --rebase for all pulls).

Common Myths

Merge destroys history (squashes commits)

Assuming you have the following merge:

    B -- C
   /      \
  A--------D

Some people will state that the merge "destroys" the commit history because if you were to look at the log of only the master branch (A -- D) you would miss the important commit messages contained in B and C.

If this were true we wouldn't have questions like this. Basically, you will see B and C unless you explicitly ask not to see them (using --first-parent). This is very easy to try for yourself.

Rebase allows for safer/simpler merges

The two approaches merge differently, but it is not clear that one is always better than the other and it may depend on the developer workflow. For example, if a developer tends to commit regularly (e.g. maybe they commit twice a day as they transition from work to home) then there could be a lot of commits for a given branch. Many of those commits might not look anything like the final product (I tend to refactor my approach once or twice per feature). If someone else was working on a related area of code and they tried to rebase my changes it could be a fairly tedious operation.

Rebase is cooler / sexier / more professional

If you like to alias rm to rm -rf to "save time" then maybe rebase is for you.

My Two Cents

I always think that someday I will come across a scenario where Git rebase is the awesome tool that solves the problem. Much like I think I will come across a scenario where Git reflog is an awesome tool that solves my problem. I have worked with Git for over five years now. It hasn't happened.

Messy histories have never really been a problem for me. I don't ever just read my commit history like an exciting novel. A majority of the time I need a history I am going to use Git blame or Git bisect anyway. In that case, having the merge commit is actually useful to me, because if the merge introduced the issue, that is meaningful information to me.

Update (4/2017)

I feel obligated to mention that I have personally softened on using rebase although my general advice still stands. I have recently been interacting a lot with the Angular 2 Material project. They have used rebase to keep a very clean commit history. This has allowed me to very easily see what commit fixed a given defect and whether or not that commit was included in a release. It serves as a great example of using rebase correctly.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

Python how to plot graph sine wave

The window of usefulness has likely come and gone, but I was working at a similar problem. Here is my attempt at plotting sine using the turtle module.

from turtle import *
from math import *

#init turtle
T=Turtle()

#sample size
T.screen.setworldcoordinates(-1,-1,1,1) 

#speed up the turtle
T.speed(-1)

#range of hundredths from -1 to 1
xcoords=map(lambda x: x/100.0,xrange(-100,101))

#setup the origin
T.pu();T.goto(-1,0);T.pd()

#move turtle
for x in xcoords:
    T.goto(x,sin(xcoords.index(x)))

Split function in oracle to comma separated values with automatic sequence

There are multiple options. See Split single comma delimited string into rows in Oracle

You just need to add LEVEL in the select list as a column, to get the sequence number to each row returned. Or, ROWNUM would also suffice.

Using any of the below SQLs, you could include them into a FUNCTION.

INSTR in CONNECT BY clause:

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5  FROM DATA
  6  CONNECT BY instr(str, ',', 1, LEVEL - 1) > 0
  7  /

STR
----------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

REGEXP_SUBSTR in CONNECT BY clause:

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5  FROM DATA
  6  CONNECT BY regexp_substr(str , '[^,]+', 1, LEVEL) IS NOT NULL
  7  /

STR
----------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

REGEXP_COUNT in CONNECT BY clause:

SQL> WITH DATA AS
  2        ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3        )
  4      SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5      FROM DATA
  6      CONNECT BY LEVEL 

Using XMLTABLE

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(COLUMN_VALUE) str
  5    FROM DATA, xmltable(('"' || REPLACE(str, ',', '","') || '"'))
  6  /
STR
------------------------------------------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

Using MODEL clause:

SQL> WITH t AS
  2  (
  3         SELECT 'word1, word2, word3, word4, word5, word6' str
  4         FROM   dual ) ,
  5  model_param AS
  6  (
  7         SELECT str AS orig_str ,
  8                ','
  9                       || str
 10                       || ','                                 AS mod_str ,
 11                1                                             AS start_pos ,
 12                Length(str)                                   AS end_pos ,
 13                (Length(str) - Length(Replace(str, ','))) + 1 AS element_count ,
 14                0                                             AS element_no ,
 15                ROWNUM                                        AS rn
 16         FROM   t )
 17  SELECT   trim(Substr(mod_str, start_pos, end_pos-start_pos)) str
 18  FROM     (
 19                  SELECT *
 20                  FROM   model_param MODEL PARTITION BY (rn, orig_str, mod_str)
 21                  DIMENSION BY (element_no)
 22                  MEASURES (start_pos, end_pos, element_count)
 23                  RULES ITERATE (2000)
 24                  UNTIL (ITERATION_NUMBER+1 = element_count[0])
 25                  ( start_pos[ITERATION_NUMBER+1] = instr(cv(mod_str), ',', 1, cv(element_no)) + 1,
 26                  end_pos[iteration_number+1] = instr(cv(mod_str), ',', 1, cv(element_no) + 1) ) )
 27  WHERE    element_no != 0
 28  ORDER BY mod_str ,
 29           element_no
 30  /

STR
------------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

You could also use DBMS_UTILITY package provided by Oracle. It provides various utility subprograms. One such useful utility is COMMA_TO_TABLE procedure, which converts a comma-delimited list of names into a PL/SQL table of names.

Read DBMS_UTILITY.COMMA_TO_TABLE

Convert any object to a byte[]

What you're looking for is serialization. There are several forms of serialization available for the .Net platform

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

How can I present a file for download from an MVC controller?

mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

Replacing H1 text with a logo image: best method for SEO and accessibility?

A new (Keller) method is supposed to improve speed over the -9999px method:

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

To analyze a query you already have entered into the Query editor, you need to choose "Include Actual Execution Plan" (7th toggle button to the right of the "! Execute" button). After executing the query, you need to click on the "Execution Plan" tab in the results pane at the bottom (above the results of the query).

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Page redirect with successful Ajax request

You can just redirect in your success handler, like this:

window.location.href = "thankyou.php";

Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Here is another good explanation from the book:

As for the difference between SCOPE_IDENTITY and @@IDENTITY, suppose that you have a stored procedure P1 with three statements:
- An INSERT that generates a new identity value
- A call to a stored procedure P2 that also has an INSERT statement that generates a new identity value
- A statement that queries the functions SCOPE_IDENTITY and @@IDENTITY The SCOPE_IDENTITY function will return the value generated by P1 (same session and scope). The @@IDENTITY function will return the value generated by P2 (same session irrespective of scope).

Get the records of last month in SQL server

You can get the last month records with this query

SELECT * FROM dbo.member d 
WHERE  CONVERT(DATE, date_created,101)>=CONVERT(DATE,DATEADD(m, datediff(m, 0, current_timestamp)-1, 0)) 
and CONVERT(DATE, date_created,101) < CONVERT(DATE, DATEADD(m, datediff(m, 0, current_timestamp)-1, 0),101) 

IIS7 Permissions Overview - ApplicationPoolIdentity

Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

SSH library for Java

I just discovered sshj, which seems to have a much more concise API than JSCH (but it requires Java 6). The documentation is mostly by examples-in-the-repo at this point, and usually that's enough for me to look elsewhere, but it seems good enough for me to give it a shot on a project I just started.

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

expected assignment or function call: no-unused-expressions ReactJS

In case someone having a problem like i had. I was using the parenthesis with the return statement on the same line at which i had written the rest of the code. Also, i used map function and props so i got so many brackets. In this case, if you're new to React you can avoid the brackets around the props, because now everyone prefers to use the arrow functions. And in the map function you can also avoid the brackets around your function callback.

props.sample.map(function callback => (
   ));

like so. In above code sample you can see there is only opening parenthesis at the left of the function callback.

How to make background of table cell transparent

You are giving colour to the background and then expecting it to be transparent? Remove background-color: #D8F0DA,

If you want #D8F0DA to be the colour of text, use color: #D8F0DA

Writing a dictionary to a text file?

I do it like this in python 3:

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)

hasNext in Python iterators?

No, there is no such method. The end of iteration is indicated by an exception. See the documentation.

What's the use of ob_start() in php?

The accepted answer here describes what ob_start() does - not why it is used (which was the question asked).

As stated elsewhere ob_start() creates a buffer which output is written to.

But nobody has mentioned that it is possible to stack multiple buffers within PHP. See ob_get_level().

As to the why....

  1. Sending HTML to the browser in larger chunks gives a performance benefit from a reduced network overhead.

  2. Passing the data out of PHP in larger chunks gives a performance and capacity benefit by reducing the number of context switches required

  3. Passing larger chunks of data to mod_gzip/mod_deflate gives a performance benefit in that the compression can be more efficient.

  4. buffering the output means that you can still manipulate the HTTP headers later in the code

  5. explicitly flushing the buffer after outputting the [head]....[/head] can allow the browser to begin marshaling other resources for the page before HTML stream completes.

  6. Capturing the output in a buffer means that it can redirected to other functions such as email, or copied to a file as a cached representation of the content

HTML embedded PDF iframe

If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:

<object data="your_url_to_pdf" type="application/pdf">
    <iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

What is the difference between user and kernel modes in operating systems?

Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.

Spring can you autowire inside an abstract class?

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:

public abstract class EO {
    @Autowired
    protected SmsNotificationService smsNotificationService;
    @Autowired
    protected SendEmailService sendEmailService;
    ...
    protected abstract void executeOperation(GenericMessage gMessage);
}

public final class OperationsExecutor {
    public enum OperationsType {
        ENROLL, CAMPAIGN
    }

    private OperationsExecutor() {
    }

    public static Object delegateOperation(OperationsType type, Object obj) 
    {
        switch(type) {
            case ENROLL:
                if (obj == null) {
                    return new EnrollOperation();
                }
                return EnrollOperation.validateRequestParams(obj);
            case CAMPAIGN:
                if (obj == null) {
                    return new CampaignOperation();
                }
                return CampaignOperation.validateRequestParams(obj);
            default:
                throw new IllegalArgumentException("OperationsType not supported.");
        }
    }
}

@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
    @Override
    public void executeOperation(GenericMessage genericMessage) {
        LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring autowire dependency defined in an abstract class

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

How to reset the use/password of jenkins on windows?

I got the initial password in the path C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

Then I login successfully with "administrator" as an user name.

Display a tooltip over a button using Windows Forms

For default tooltip this can be used -

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip(this.textBox1, "Hello world");

A customized tooltip can also be used in case if formatting is required for tooltip message. This can be created by custom formatting the form and use it as tooltip dialog on mouse hover event of the control. Please check following link for more details -

http://newapputil.blogspot.in/2015/08/create-custom-tooltip-dialog-from-form.html

How to split large text file in windows?

Below code split file every 500

@echo off
setlocal ENABLEDELAYEDEXPANSION
REM Edit this value to change the name of the file that needs splitting. Include the extension.
SET BFN=upload.txt
REM Edit this value to change the number of lines per file.
SET LPF=15000
REM Edit this value to change the name of each short file. It will be followed by a number indicating where it is in the list.
SET SFN=SplitFile

REM Do not change beyond this line.

SET SFX=%BFN:~-3%

SET /A LineNum=0
SET /A FileNum=1

For /F "delims==" %%l in (%BFN%) Do (
SET /A LineNum+=1

echo %%l >> %SFN%!FileNum!.%SFX%

if !LineNum! EQU !LPF! (
SET /A LineNum=0
SET /A FileNum+=1
)

)
endlocal
Pause

See below: https://forums.techguy.org/threads/solved-split-a-100000-line-csv-into-5000-line-csv-files-with-dos-batch.1023949/

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

php stdClass to array

This function worked for me:

function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Reference: http://carlofontanos.com/convert-stdclass-object-to-array-in-php/

How to change a Git remote on Heroku

  1. View Remote URLs

    > git remote -v

    heroku  https://git.heroku.com/###########.git (fetch) < your Heroku Remote URL
    heroku  https://git.heroku.com/############.git (push)
    origin  https://github.com/#######/#####.git (fetch) < if you use GitHub then this is your GitHub remote URL
    origin  https://github.com/#######/#####.git (push)
  1. Remove Heroku remote URL

    > git remote rm heroku

  2. Set new Heroku URL

    > heroku git:remote -a ############

And you are done.

What is the best way to add a value to an array in state

the best away now.

this.setState({ myArr: [...this.state.myArr, new_value] })

Creating a JSON Array in node js

You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

How can I style even and odd elements?

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).

this is what you want:

<html>
    <head>
        <style>
            li { color: blue }<br>
            li:nth-child(even) { color:red }
            li:nth-child(odd) { color:green}
        </style>
    </head>
    <body>
        <ul>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
            <li>ho</li>
        </ul>
    </body>
</html>

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

How to set JFrame to appear centered, regardless of monitor resolution?

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.

in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.

Height of an HTML select box (dropdown)

The Chi Row answer is a good option for the problem, but I've found an error i the onclick arguments. Instead, would be:

<select size="1" position="absolute" onclick="size=(size!=1)?1:n;" ...>

(And mention you must replace the "n" with the number of lines you need)

Is there a splice method for strings?

Here's a nice little Curry which lends better readability (IMHO):

The second function's signature is identical to the Array.prototype.splice method.

function mutate(s) {
    return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
    };
}

mutate('101')(1, 1, '1');

I know there's already an accepted answer, but hope this is useful.

How to use sessions in an ASP.NET MVC 4 application?

You can store any kind of data in a session using:

Session["VariableName"]=value;

This variable will last 20 mins or so.

Css height in percent not working

You can achieve that by using positioning.

Try

position: absolute;

to get the 100% height.

How do I check out a remote Git branch?

to get all remote branches use this :

git fetch --all

then checkout to the branch :

git checkout test

How to have a transparent ImageButton: Android

This is programatically set background color as transparent

 ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
 btn.setBackgroundColor(Color.TRANSPARENT);

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

How to set null value to int in c#?

Additionally, you cannot use "null" as a value in a conditional assignment. e.g...

bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;

FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

So, you have to cast the null as well... This works:

int? myint = (testvalue == true) ? 1234 : (int?)null;

What's the best way to convert a number to a string in JavaScript?

If I had to take everything into consideration, I will suggest following

var myint = 1;
var mystring = myint + '';
/*or int to string*/
myint = myint + ''

IMHO, its the fastest way to convert to string. Correct me if I am wrong.

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

What causes the Broken Pipe Error?

The current state of a socket is determined by 'keep-alive' activity. In your case, this is possible that when you are issuing the send call, the keep-alive activity tells that the socket is active and so the send call will write the required data (40 bytes) in to the buffer and returns without giving any error.

When you are sending a bigger chunk, the send call goes in to blocking state.

The send man page also confirms this:

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it would return EAGAIN in this case

So, while blocking for the free available buffer, if the caller is notified (by keep-alive mechanism) that the other end is no more present, the send call will fail.

Predicting the exact scenario is difficult with the mentioned info, but I believe, this should be the reason for you problem.