Programs & Examples On #Login attempts

Converting a vector<int> to string

Maybe std::ostream_iterator and std::ostringstream:

#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

  std::ostringstream oss;

  if (!vec.empty())
  {
    // Convert all but the last element to avoid a trailing ","
    std::copy(vec.begin(), vec.end()-1,
        std::ostream_iterator<int>(oss, ","));

    // Now add the last element with no delimiter
    oss << vec.back();
  }

  std::cout << oss.str() << std::endl;
}

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

adding x and y axis labels in ggplot2

since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

In my answer,I have stored the plot in mygraph variable and then I have used

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

And the work is done. Below is the complete answer.

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

Also, you can change the labels title from the same formula used above -

mygraph$labels$size= "N2" #size contains the nitrogen level 

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

Regex Last occurrence?

One that worked for me was:

.+(\\.+)$

Try it online!

Explanation:

.+     - any character except newline
(      - create a group
 \\.+   - match a backslash, and any characters after it
)      - end group
$      - this all has to happen at the end of the string

implement time delay in c

What operating system are you using?
I know that on windows, you can do something like this:

//include crap
#include <windows.h>

int main () {
  //do things
  Sleep(/* ur wait time in ms */);// wait for param1 ms
  //continue to do things
}

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

linux find regex

Note that -regex depends on whole path.

 -regex pattern
              File name matches regular expression pattern.  
              This is a match on the whole path, not a search.

You don't actually have to use -regex for what you are doing.

find . -iname "*[0-9]"

How to find length of dictionary values

Sure. In this case, you'd just do:

length_key = len(d['key'])  # length of the list stored at `'key'` ...

It's hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:

length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key']  # length of the list stored at `'key'` ...

How to change cursor from pointer to finger using jQuery?

$('selector').css('cursor', 'pointer'); // 'default' to revert

I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".

The normal arrow cursor is just "default".

all possible default pointer looks DEMO

Compiler warning - suggest parentheses around assignment used as truth value

It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have == in there. You can make the warning go away by adding another set of parentheses:

while ((list = list->next))

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Combining (concatenating) date and time into a datetime

The simple solution

SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Delete files older than 3 months old in a directory using .NET

i have try this code and it works very well, hope this answered

namespace EraseJunkFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\yourdirectory\");
            foreach (FileInfo file in yourRootDir.GetFiles())
                if (file.LastWriteTime < DateTime.Now.AddDays(-90))
                    file.Delete();
        }
    }
}

Difference between one-to-many and many-to-one relationship

Yes, it a vice versa. It depends on which side of the relationship the entity is present on.

For example, if one department can employ for several employees then, department to employee is a one to many relationship (1 department employs many employees), while employee to department relationship is many to one (many employees work in one department).

More info on the relationship types:

Database Relationships - IBM DB2 documentation

Open Redis port for remote connections

Another possibly helpful note.

Redis can be bound to multiple IPs - that's very helpful when you don't want to open it to entire world (0.0.0.0) but only make it accessible in local networks.

  1. sudo nano /etc/redis/redis.conf
  2. add your local network IP to the end of bind setting:

bind 127.0.0.1 10.0.0.1

  1. restart the service: sudo service redis-server restart

Now you can easily access redis from other computers in same network, e.g. redis-cli -h 10.0.0.1

MongoDb shuts down with Code 100

To run Mongo DB demon with mongod command, you should have a database directory, probably you need to run:

mkdir C:\data\db

Also, MongoDB need to have a write permissions for that directory or it should be run with superuser permissions, like sudo mongod.

check if variable empty

Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following

if (!empty($var) && is_null($var))

Note the PHP manual

variable is considered empty if it does not exist or if its value equals FALSE

As opposed to being null which is handy here!

Eliminate space before \begin{itemize}

\renewcommand{\@listI}{%
\leftmargin=25pt
\rightmargin=0pt
\labelsep=5pt
\labelwidth=20pt
\itemindent=0pt
\listparindent=0pt
\topsep=0pt plus 2pt minus 4pt
\partopsep=0pt plus 1pt minus 1pt
\parsep=0pt plus 1pt
\itemsep=\parsep}

How to Get JSON Array Within JSON Object?

I guess this will help you.

JSONObject jsonObj = new JSONObject(jsonStr);

JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
  JSONObject jsonObj = ja_data.getJSONObject(i);
  Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();

  // getting inner array Ingredients
  JSONArray ja = jsonObj.getJSONArray("Ingredients");
  int len = ja.length();

  ArrayList<String> Ingredients_names = new ArrayList<>();
  for(int j=0; j<len; j++) {
    JSONObject json = ja.getJSONObject(j);
    Ingredients_names.add(json.getString("name"));
  }
}

How to include !important in jquery

For those times when you need to use jquery to set !important properties, here is a plugin I build that will allow you to do so.

$.fn.important = function(key, value) {
    var q = Object.assign({}, this.style)
    q[key] = `${value} !important`;
    $(this).css("cssText", Object.entries(q).filter(x => x[1]).map(([k, v]) => (`${k}: ${v}`)).join(';'));
};

$('div').important('color', 'red');

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

How do I get total physical memory size using PowerShell without WMI?

Id like to say that instead of going with the systeminfo this would help over to get the total physical memory in GB's the machine

Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}

you can pass this value to the variable and get the gross output for the total physical memory in the machine

   $totalmemory = Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}
   $totalmemory

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

Bootstrap - Removing padding or margin when screen size is smaller

The easy solution is to write something like that,

px-lg-1

mb-lg-5

By adding lg, the class will be applied only on large screens

Trim last character from a string

Slightly modified version of @Damian Leszczynski - Vash that will make sure that only a specific character will be removed.

public static class StringExtensions
{
    public static string TrimLastCharacter(this string str, char character)
    {
        if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
        {
            return str;
        }
        return str.Substring(0, str.Length - 1);
    }
}

Virtual network interface in Mac OS X

if you are on a dev environment and want access some service already running on localhost/host machine. in docker for mac you have another option.use docker.for.mac.localhost instead of localhost in docker container. docker.for.mac.host.internal should be used instead of docker.for.mac.localhost from Docker Community Edition 17.12.0-ce-mac46 2018-01-09. this allows you to connect to service running on your on mac from within a docker container.please refer below links

understanding the docker.for.mac.localhost behavior

release notes

Altering a column to be nullable

This depends on what SQL Engine you are using, in Sybase your command works fine:

ALTER TABLE Merchant_Pending_Functions 
Modify NumberOfLocations NULL;

Asynchronously load images with jQuery

If you just want to set the source of the image you can use this.

$("img").attr('src','http://somedomain.com/image.jpg');

Convert Swift string to array

Updated for Swift 4

Here are 3 ways.

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

//array of String
var strArr = myString.map { String($0)}

Swift 3

Here are 3 ways.

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:

let charArr = "Cat".letterize()

How do I implement JQuery.noConflict() ?

Today i have this issue because i have implemented "bootstrap menu" that uses a jQuery version along with "fancybox image gallery". Of course one plugin works and the other not due to jQuery conflict but i have overcome it as follow:

First i have added the "bootstrap menu" Js in the script footer as the menu is presented allover the website pages:

<!-- Top Menu Javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var jq171 = jQuery.noConflict(true);
</script>

And in the "fancybox" image gallery page as follow:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="fancybox/js/libs/jquery-1.7.1.min.js"><\/script>')</script>

And the good thing is both working like a charm :)

Give it a try :)

How to Logout of an Application Where I Used OAuth2 To Login With Google?

Overview of OAuth: Is the User Who He/She Says He/She is?:

I'm not sure if you used OAuth to login to Stack Overflow, like the "Login with Google" option, but when you use this feature, Stack Overflow is simply asking Google if it knows who you are:

"Yo Google, this Vinesh fella claims that [email protected] is him, is that true?"

If you're logged in already, Google will say YES. If not, Google will say:

"Hang on a sec Stack Overflow, I'll authenticate this fella and if he can enter the right password for his Google account, then it's him".

When you enter your Google password, Google then tells Stack Overflow you are who you say you are, and Stack Overflow logs you in.

When you logout of your app, you're logging out of your app:

Here's where developers new to OAuth sometimes get a little confused... Google and Stack Overflow, Assembla, Vinesh's-very-cool-slick-webapp, are all different entities, and Google knows nothing about your account on Vinesh's cool webapp, and vice versa, aside from what's exposed via the API you're using to access profile information.

When your user logs out, he or she isn't logging out of Google, he/she is logging out of your app, or Stack Overflow, or Assembla, or whatever web application used Google OAuth to authenticate the user.

In fact, I can log out of all of my Google accounts and still be logged into Stack Overflow. Once your app knows who the user is, that person can log out of Google. Google is no longer needed.

With that said, what you're asking to do is log the user out of a service that really doesn't belong to you. Think about it like this: As a user, how annoyed do you think I would be if I logged into 5 different services with my Google account, then the first time I logged out of one of them, I have to login to my Gmail account again because that app developer decided that, when I log out of his application, I should also be logged out of Google? That's going to get old really fast. In short, you really don't want to do this...

Yeh yeh, whatever, I still want to log the user out Of Google, just tell me how do I do this?

With that said, if you still do want to log a user out of Google, and realize that you may very well be disrupting their workflow, you could dynamically build the logout url from one of their Google services logout button, and then invoke that using an img element or a script tag:

<script type="text/javascript" 
    src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

<img src="https://mail.google.com/mail/u/0/?logout&hl=en" />

OR

window.location = "https://mail.google.com/mail/u/0/?logout&hl=en";

If you redirect your user to the logout page, or invoke it from an element that isn't cross-domain restricted, the user will be logged out of Google.

Note that this does not necessarily mean the user will be logged out of your application, only Google. :)

Summary:

What's important for you to keep in mind is that, when you logout of your app, you don't need to make the user re-enter a password. That's the whole point! It authenticates against Google so the user doesn't have to enter his or her password over and over and over again in each web application he or she uses. It takes some getting used to, but know that, as long as the user is logged into Google, your app doesn't need to worry about whether or not the user is who he/she says he/she is.

I have the same implementation in a project as you do, using the Google Profile information with OAuth. I tried the very same thing you're looking to try, and it really started making people angry when they had to login to Google over and over again, so we stopped logging them out of Google. :)

Android: Align button to bottom-right of screen using FrameLayout?

Two ways to do this:

1) Using a Frame Layout

android:layout_gravity="bottom|right"

2) Using a Relative Layout

android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" 

How to delete columns in numpy.array

Another way is to use masked arrays:

import numpy as np
a = np.array([[ np.nan,   2.,   3., np.nan], [  1.,   2.,   3., 9]])
print(a)
# [[ NaN   2.   3.  NaN]
#  [  1.   2.   3.   9.]]

The np.ma.masked_invalid method returns a masked array with nans and infs masked out:

print(np.ma.masked_invalid(a))
[[-- 2.0 3.0 --]
 [1.0 2.0 3.0 9.0]]

The np.ma.compress_cols method returns a 2-D array with any column containing a masked value suppressed:

a=np.ma.compress_cols(np.ma.masked_invalid(a))
print(a)
# [[ 2.  3.]
#  [ 2.  3.]]

See manipulating-a-maskedarray

How should we manage jdk8 stream for null values

An example how to avoid null e.g. use filter before groupingBy

Filter out the null instances before groupingBy.

Here is an example

MyObjectlist.stream()
            .filter(p -> p.getSomeInstance() != null)
            .collect(Collectors.groupingBy(MyObject::getSomeInstance));

How to apply bold text style for an entire row using Apache POI?

This work for me

I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0); 
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);

What are the best JVM settings for Eclipse?

It is that time of year again: "eclipse.ini take 3" the settings strike back!

Eclipse Helios 3.6 and 3.6.x settings

alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png

After settings for Eclipse Ganymede 3.4.x and Eclipse Galileo 3.5.x, here is an in-depth look at an "optimized" eclipse.ini settings file for Eclipse Helios 3.6.x:

(by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7)

Eclipse.ini

alt text

WARNING: for non-windows platform, use the Sun proprietary option -XX:MaxPermSize instead of the Eclipse proprietary option --launcher.XXMaxPermSize.
That is: Unless you are using the latest jdk6u21 build 7. See the Oracle section below.

-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
-vm
C:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Declipse.p2.unsignedPolicy=allow
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+CMSIncrementalPacing
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons

Note:
Adapt the p2.reconciler.dropins.directory to an external directory of your choice.
See this SO answer. The idea is to be able to drop new plugins in a directory independently from any Eclipse installation.

The following sections detail what are in this eclipse.ini file.


The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes

Andrew Niefer did alert me to this situation, and wrote a blog post, about a non-standard vm argument (-XX:MaxPermSize) and can cause vms from other vendors to not start at all.
But the eclipse version of that option (--launcher.XXMaxPermSize) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below).

The final solution is on the Eclipse Wiki, and for Helios on Windows with 6u21 pre build 7 only:

(eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503

That's it. No setting to tweak here (again, only for Helios on Windows with a 6u21 pre build 7).
For non-Windows platform, you need to revert to the Sun proprietary option -XX:MaxPermSize.

The issue is based one a regression: JVM identification fails due to Oracle rebranding in java.exe, and triggered bug 319514 on Eclipse.
Andrew took care of Bug 320005 - [launcher] --launcher.XXMaxPermSize: isSunVM should return true for Oracle, but that will be only for Helios 3.6.1.
Francis Upton, another Eclipse committer, reflects on the all situation.

Update u21b7, July, 27th:
Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7.
If you use jdk6u21 build 7, you can revert to the --launcher.XXMaxPermSize (eclipse option) instead of -XX:MaxPermSize (the non-standard option).
The auto-detection happening in the C launcher shim eclipse.exe will still look for the "Sun Microsystems" string, but with 6u21b7, it will now work - again.

For now, I still keep the -XX:MaxPermSize version (because I have no idea when everybody will launch eclipse the right JDK).


Implicit `-startup` and `--launcher.library`

Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases:

  • startup: If not specified, the executable will look in the plugins directory for the org.eclipse.equinox.launcher bundle with the highest version.
  • launcher.library: If not specified, the executable looks in the plugins directory for the appropriate org.eclipse.equinox.launcher.[platform] fragment with the highest version and uses the shared library named eclipse_* inside.

Use JDK6

The JDK6 is now explicitly required to launch Eclipse:

-Dosgi.requiredJavaVersion = 1.6

This SO question reports a positive incidence for development on Mac OS.


+UnlockExperimentalVMOptions

The following options are part of some of the experimental options of the Sun JVM.

-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods

They have been reported in this blog post to potentially speed up Eclipse.
See all the JVM options here and also in the official Java Hotspot options page.
Note: the detailed list of those options reports that UseFastAccessorMethods might be active by default.

See also "Update your JVM":

As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17.


Opening files in Eclipse from the command line

See the blog post from Andrew Niefer reporting this new option:

--launcher.defaultAction
openFile

This tells the launcher that if it is called with a command line that only contains arguments that don't start with "-", then those arguments should be treated as if they followed "--launcher.openFile".

eclipse myFile.txt

This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose "Open With" or "Send To" Eclipse.

Relative paths will be resolved first against the current working directory, and second against the eclipse program directory.

See bug 301033 for reference. Originally bug 4922 (October 2001, fixed 9 years later).


p2 and the Unsigned Dialog Prompt

If you are tired of this dialog box during the installation of your many plugins:

alt text

, add in your eclipse.ini:

-Declipse.p2.unsignedPolicy=allow

See this blog post from Chris Aniszczy, and the bug report 235526.

I do want to say that security research supports the fact that less prompts are better.
People ignore things that pop up in the flow of something they want to get done.

For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them.
Instead, we should collect all the problems, do not install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called 'safe staging'.

---------- http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif

Additional options

Those options are not directly in the eclipse.ini above, but can come in handy if needed.


The `user.home` issue on Windows7

When eclipse starts, it will read its keystore file (where passwords are kept), a file located in user.home.
If for some reason that user.home doesn't resolve itself properly to a full-fledge path, Eclipse won't start.
Initially raised in this SO question, if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start)

Add in your eclipse.ini:

-eclipse.keyring 
C:\eclipse\keyring.txt

This has been tracked by bug 300577, it has been solve in this other SO question.


Debug mode

Wait, there's more than one setting file in Eclipse.
if you add to your eclipse.ini the option:

-debug

, you enable the debug mode and Eclipse will look for another setting file: a .options file where you can specify some OSGI options.
And that is great when you are adding new plugins through the dropins folder.
Add in your .options file the following settings, as described in this blog post "Dropins diagnosis":

org.eclipse.equinox.p2.core/debug=true
org.eclipse.equinox.p2.core/reconciler=true

P2 will inform you what bundles were found in dropins/ folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start:

  • was your bundle in the plan?
  • Was it installation problem (P2 fault)
  • or maybe it is just not optimal to include your feature?

That comes from Bug 264924 - [reconciler] No diagnosis of dropins problems, which finally solves the following issue like:

Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse
Unzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5

This is a problematic configuration since OCL depends on EMF which is missing.
3.5M5 provides no diagnosis of this problem.

Start eclipse.
No obvious problems. Nothing in Error Log.

  • Help / About / Plugin details shows org.eclipse.ocl.doc, but not org.eclipse.ocl.
  • Help / About / Configuration details has no (diagnostic) mention of org.eclipse.ocl.
  • Help / Installation / Information Installed Software has no mention of org.eclipse.ocl.

Where are the nice error markers?


Manifest Classpath

See this blog post:

  • In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party.
  • In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution.

That means some of your projects might no longer compile in Helios.
If you want to revert to Galileo behavior, add:

-DresolveReferencedLibrariesForContainers=true

See bug 305037, bug 313965 and bug 313890 for references.


IPV4 stack

This SO question mentions a potential fix when not accessing to plugin update sites:

-Djava.net.preferIPv4Stack=true

Mentioned here just in case it could help in your configuration.


JVM1.7x64 potential optimizations

This article reports:

For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are:

-Xincgc 
-XX:-DontCompileHugeMethods 
-XX:MaxInlineSize=1024  
-XX:FreqInlineSize=1024 

But I am still working on it...

error TS2339: Property 'x' does not exist on type 'Y'

I was getting this error on Vue 3. It was because defineComponent must be imported like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "HelloWorld",
    props: {
        msg: String,
    },
    created() {
        this.testF();
    },
    methods: {
        testF() {
            console.log("testF");
        },
    },
});
</script>

javascript popup alert on link click

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML

HTML:

<a id="theLink">Click Me</a>

I could use the following jQuery to hookup an event to that specific link.

// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {

  // The '#theLink' portion is a selector which matches a DOM element
  // with the id 'theLink' and .click registers a call back for the 
  // element being clicked on 
  $('#theLink').click(function (event) {

    // This stops the link from actually being followed which is the 
    // default action 
    event.preventDefault();

    var answer confirm("Please click OK to continue");
    if (!answer) {
      window.location="http://www.continue.com"
    }
  });

});

Using ConfigurationManager to load config from an arbitrary location

I provided the configuration values to word hosted .nET Compoent as follows.

A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.

string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

Android Studio Gradle Already disposed Module

I was having this issue because gradle and Android Studio were using a different path for the jvm. In the Event Log there was an option for AS and gradle to use the same path. Selecting this and then doing an invalidate cache & restart resolved the issue for me.

How to simulate a button click using code?

you can do it this way

private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

JavaScript for detecting browser language preference

If you don't want to rely on an external server and you have one of your own you can use a simple PHP script to achieve the same behavior as @DanSingerman answer.

languageDetector.php:

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
echo json_encode($lang);
?>

And just change this lines from the jQuery script:

url: "languageDetector.php",
dataType: 'json',
success: function(language) {
    nowDoSomethingWithIt(language);
}

What is the difference between map and flatMap and a good use case for each?

Use test.md as a example:

?  spark-1.6.1 cat test.md
This is the first line;
This is the second line;
This is the last line.

scala> val textFile = sc.textFile("test.md")
scala> textFile.map(line => line.split(" ")).count()
res2: Long = 3

scala> textFile.flatMap(line => line.split(" ")).count()
res3: Long = 15

scala> textFile.map(line => line.split(" ")).collect()
res0: Array[Array[String]] = Array(Array(This, is, the, first, line;), Array(This, is, the, second, line;), Array(This, is, the, last, line.))

scala> textFile.flatMap(line => line.split(" ")).collect()
res1: Array[String] = Array(This, is, the, first, line;, This, is, the, second, line;, This, is, the, last, line.)

If you use map method, you will get the lines of test.md, for flatMap method, you will get the number of words.

The map method is similar to flatMap, they are all return a new RDD. map method often to use return a new RDD, flatMap method often to use split words.

How do I resize a Google Map with JavaScript after it has loaded?

for Google Maps v3, you need to trigger the resize event differently:

google.maps.event.trigger(map, "resize");

See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event


Update

This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.

_x000D_
_x000D_
$(function() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  var map = new google.maps.Map($("#map-canvas")[0], mapOptions);

  // listen for the window resize event & trigger Google Maps to update too
  $(window).resize(function() {
    // (the 'map' here is the result of the created 'var map = ...' above)
    google.maps.event.trigger(map, "resize");
  });
});
_x000D_
html,
body {
  height: 100%;
}
#map-canvas {
  min-width: 200px;
  width: 50%;
  min-height: 200px;
  height: 80%;
  border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

UPDATE 2018-05-22

With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map class.

The documentation states

When the map is resized, the map center is fixed

  • The full-screen control now preserves center.

  • There is no longer any need to trigger the resize event manually.

source: https://developers.google.com/maps/documentation/javascript/new-renderer

google.maps.event.trigger(map, "resize"); doesn't have any effect starting from version 3.32

How can I switch my git repository to a particular commit

If you want to throw the latest four commits away, use:

git reset --hard HEAD^^^^

Alternatively, you can specify the hash of a commit you want to reset to:

git reset --hard 6e559cb

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

How do you stop MySQL on a Mac OS install?

If you installed the MySQL 5 package with MacPorts:

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql.plist 

Or

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist 

if you installed the mysql5-devel package.

How to reset the state of a Redux store?

One way to do that would be to write a root reducer in your application.

The root reducer would normally delegate handling the action to the reducer generated by combineReducers(). However, whenever it receives USER_LOGOUT action, it returns the initial state all over again.

For example, if your root reducer looked like this:

const rootReducer = combineReducers({
  /* your app’s top-level reducers */
})

You can rename it to appReducer and write a new rootReducer delegating to it:

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

const rootReducer = (state, action) => {
  return appReducer(state, action)
}

Now we just need to teach the new rootReducer to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state as we pass it to appReducer:

 const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    state = undefined
  }

  return appReducer(state, action)
}

Now, whenever USER_LOGOUT fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type as well.

To reiterate, the full new code looks like this:

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    state = undefined
  }

  return appReducer(state, action)
}

Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state before passing it to another function. Mutating a state object would be a violation of Redux principles.

In case you are using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and the state copy will be loaded from there on refresh.

First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.

const rootReducer = (state, action) => {
    if (action.type === SIGNOUT_REQUEST) {
        // for all keys defined in your persistConfig(s)
        storage.removeItem('persist:root')
        // storage.removeItem('persist:otherKey')

        state = undefined;
    }
    return appReducer(state, action);
};

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Bootstrap 3 Glyphicons are not working

I was having the same problem where the browser was unable to find the font files, and my issue was due to exclusions in my .htaccess file that was whitelisting files that shouldn't be sent to index.php for processing. As the font file couldn't be loaded the characters were replaced with BLOB.

RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|svg|css|js|ico|rss|xml|json)$
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^ index.php [L,QSA]

As you can see, files like images, rss, and xml are excluded from the rewrite, but the font files are .woff and .woff2 files, so these also needed adding to the whitelist.

RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|svg|css|js|ico|rss|xml|json|woff|woff2)$
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^ index.php [L,QSA]

Adding woff and woff2 to the whitelist allows the font files to be loaded, and the glyphicons should then display properly.

How do I make a list of data frames?

This may be a little late but going back to your example I thought I would extend the answer just a tad.

 D1 <- data.frame(Y1=c(1,2,3), Y2=c(4,5,6))
 D2 <- data.frame(Y1=c(3,2,1), Y2=c(6,5,4))
 D3 <- data.frame(Y1=c(6,5,4), Y2=c(3,2,1))
 D4 <- data.frame(Y1=c(9,9,9), Y2=c(8,8,8))

Then you make your list easily:

mylist <- list(D1,D2,D3,D4)

Now you have a list but instead of accessing the list the old way such as

mylist[[1]] # to access 'd1'

you can use this function to obtain & assign the dataframe of your choice.

GETDF_FROMLIST <- function(DF_LIST, ITEM_LOC){
   DF_SELECTED <- DF_LIST[[ITEM_LOC]]
   return(DF_SELECTED)
}

Now get the one you want.

D1 <- GETDF_FROMLIST(mylist, 1)
D2 <- GETDF_FROMLIST(mylist, 2)
D3 <- GETDF_FROMLIST(mylist, 3)
D4 <- GETDF_FROMLIST(mylist, 4)

Hope that extra bit helps.

Cheers!

Laravel 5 - How to access image uploaded in storage within View?

If you are on windows you can run this command on cmd:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

from: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

div hover background-color change?

div hover background color change

Try like this:

.class_name:hover{
    background-color:#FF0000;
}

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

How to create a stopwatch using JavaScript?

function StopWatch() {
    let startTime, endTime, running, duration = 0
    
    this.start = () => {
        if (running) console.log('its already running')
        else {
            running = true
            startTime = Date.now()
        }
    }

    this.stop = () => {
        if (!running) console.log('its not running!')
        else {
            running = false
            endTime = Date.now()

            const seconds = (endTime - startTime) / 1000
            duration += seconds
        }
    }

    this.restart = () => {
        startTime = endTime = null
        running = false
        duration = 0
    }
    
    Object.defineProperty(this, 'duration', {
        get: () => duration.toFixed(2)
    })

}

const sw =  new StopWatch()

sw.start()
sw.stop()

sw.duration

filename and line number of Python script

In Python 3 you can use a variation on:

def Deb(msg = None):
  print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")

In code, you can then use:

Deb("Some useful information")
Deb()

To produce:

123: Some useful information
124:

Where the 123 and 124 are the lines that the calls are made from.

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

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

Thank you for this

Here's what I did:

1.Created an Extensions.cs file in a Utils folder.

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

namespace Web.ProjectName.Utils
{
    public class Extensions
    {
        public static IEnumerable<SelectListItem> GetStatesList()
        {
            IList<SelectListItem> states = new List<SelectListItem>
            {
                new SelectListItem() {Text="Alabama", Value="AL"},
                new SelectListItem() { Text="Alaska", Value="AK"},
                new SelectListItem() { Text="Arizona", Value="AZ"},
                new SelectListItem() { Text="Arkansas", Value="AR"},
                new SelectListItem() { Text="California", Value="CA"},
                new SelectListItem() { Text="Colorado", Value="CO"},
                new SelectListItem() { Text="Connecticut", Value="CT"},
                new SelectListItem() { Text="District of Columbia", Value="DC"},
                new SelectListItem() { Text="Delaware", Value="DE"},
                new SelectListItem() { Text="Florida", Value="FL"},
                new SelectListItem() { Text="Georgia", Value="GA"},
                new SelectListItem() { Text="Hawaii", Value="HI"},
                new SelectListItem() { Text="Idaho", Value="ID"},
                new SelectListItem() { Text="Illinois", Value="IL"},
                new SelectListItem() { Text="Indiana", Value="IN"},
                new SelectListItem() { Text="Iowa", Value="IA"},
                new SelectListItem() { Text="Kansas", Value="KS"},
                new SelectListItem() { Text="Kentucky", Value="KY"},
                new SelectListItem() { Text="Louisiana", Value="LA"},
                new SelectListItem() { Text="Maine", Value="ME"},
                new SelectListItem() { Text="Maryland", Value="MD"},
                new SelectListItem() { Text="Massachusetts", Value="MA"},
                new SelectListItem() { Text="Michigan", Value="MI"},
                new SelectListItem() { Text="Minnesota", Value="MN"},
                new SelectListItem() { Text="Mississippi", Value="MS"},
                new SelectListItem() { Text="Missouri", Value="MO"},
                new SelectListItem() { Text="Montana", Value="MT"},
                new SelectListItem() { Text="Nebraska", Value="NE"},
                new SelectListItem() { Text="Nevada", Value="NV"},
                new SelectListItem() { Text="New Hampshire", Value="NH"},
                new SelectListItem() { Text="New Jersey", Value="NJ"},
                new SelectListItem() { Text="New Mexico", Value="NM"},
                new SelectListItem() { Text="New York", Value="NY"},
                new SelectListItem() { Text="North Carolina", Value="NC"},
                new SelectListItem() { Text="North Dakota", Value="ND"},
                new SelectListItem() { Text="Ohio", Value="OH"},
                new SelectListItem() { Text="Oklahoma", Value="OK"},
                new SelectListItem() { Text="Oregon", Value="OR"},
                new SelectListItem() { Text="Pennsylvania", Value="PA"},
                new SelectListItem() { Text="Rhode Island", Value="RI"},
                new SelectListItem() { Text="South Carolina", Value="SC"},
                new SelectListItem() { Text="South Dakota", Value="SD"},
                new SelectListItem() { Text="Tennessee", Value="TN"},
                new SelectListItem() { Text="Texas", Value="TX"},
                new SelectListItem() { Text="Utah", Value="UT"},
                new SelectListItem() { Text="Vermont", Value="VT"},
                new SelectListItem() { Text="Virginia", Value="VA"},
                new SelectListItem() { Text="Washington", Value="WA"},
                new SelectListItem() { Text="West Virginia", Value="WV"},
                new SelectListItem() { Text="Wisconsin", Value="WI"},
                new SelectListItem() { Text="Wyoming", Value="WY"}
            };
            return states;
        }
    }
}

2.In my model, where state will be abbreviated (e.g. "AL", "NY", etc.):

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Web.ProjectName.Models
{
    public class ContactForm
    {

        ...

        [Required]
        [Display(Name = "State")]
        [RegularExpression("[A-Z]{2}")]
        public string State { get; set; }

        ...

    }
}

2.In my view I referenced it:

  @model Web.ProjectName.Models.ContactForm

  ...

  @Html.LabelFor(x => x.State, new { @class = "form-label" })
  @Html.DropDownListFor(x => x.State, Web.ProjectName.Utils.Extensions.GetStatesList(), new { @class = "form-control" })

  ...

Shell script to delete directories older than n days

This will do it recursively for you:

find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \;

Explanation:

  • find: the unix command for finding files / directories / links etc.
  • /path/to/base/dir: the directory to start your search in.
  • -type d: only find directories
  • -ctime +10: only consider the ones with modification time older than 10 days
  • -exec ... \;: for each such result found, do the following command in ...
  • rm -rf {}: recursively force remove the directory; the {} part is where the find result gets substituted into from the previous part.

Alternatively, use:

find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf

Which is a bit more efficient, because it amounts to:

rm -rf dir1 dir2 dir3 ...

as opposed to:

rm -rf dir1; rm -rf dir2; rm -rf dir3; ...

as in the -exec method.


With modern versions of find, you can replace the ; with + and it will do the equivalent of the xargs call for you, passing as many files as will fit on each exec system call:

find . -type d -ctime +10 -exec rm -rf {} +

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

Automatically enter SSH password with script

First you need to install sshpass.

  • Ubuntu/Debian: apt-get install sshpass
  • Fedora/CentOS: yum install sshpass
  • Arch: pacman -S sshpass

Example:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM

Custom port example:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400

Notes:

  • sshpass can also read a password from a file when the -f flag is passed.
    • Using -f prevents the password from being visible if the ps command is executed.
    • The file that the password is stored in should have secure permissions.

Java - Including variables within strings?

Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);

results in string containing the following:

A string of ponies.

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.

Difference between hamiltonian path and euler path

Euler Path - An Euler path is a path in which each edge is traversed exactly once.

Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.

If you have ever confusion remember E - Euler E - Edge.

Convert number to varchar in SQL with formatting

RIGHT('00' + CONVERT(VARCHAR, MyNumber), 2)

Be warned that this will cripple numbers > 99. You might want to factor in that possibility.

C# getting its own class name

I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.

typeof(MyProgram).Name

How to center a window on the screen in Tkinter?

The simplest (but possibly inaccurate) method is to use tk::PlaceWindow, which takes the pathname of a toplevel window as an argument. The main window's pathname is .

import tkinter

root = tkinter.Tk()
root.eval('tk::PlaceWindow . center')

second_win = tkinter.Toplevel(root)
root.eval(f'tk::PlaceWindow {str(second_win)} center')

root.mainloop()

The problem

Simple solutions ignore the outermost frame with the title bar and the menu bar, which leads to a slight offset from being truly centered.

The solution

import tkinter  # Python 3

def center(win):
    """
    centers a tkinter window
    :param win: the main window or Toplevel window to center
    """
    win.update_idletasks()
    width = win.winfo_width()
    frm_width = win.winfo_rootx() - win.winfo_x()
    win_width = width + 2 * frm_width
    height = win.winfo_height()
    titlebar_height = win.winfo_rooty() - win.winfo_y()
    win_height = height + titlebar_height + frm_width
    x = win.winfo_screenwidth() // 2 - win_width // 2
    y = win.winfo_screenheight() // 2 - win_height // 2
    win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    win.deiconify()

if __name__ == '__main__':
    root = tkinter.Tk()
    root.attributes('-alpha', 0.0)
    menubar = tkinter.Menu(root)
    filemenu = tkinter.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Exit", command=root.destroy)
    menubar.add_cascade(label="File", menu=filemenu)
    root.config(menu=menubar)
    frm = tkinter.Frame(root, bd=4, relief='raised')
    frm.pack(fill='x')
    lab = tkinter.Label(frm, text='Hello World!', bd=4, relief='sunken')
    lab.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
    center(root)
    root.attributes('-alpha', 1.0)
    root.mainloop()

With tkinter you always want to call the update_idletasks() method
directly before retrieving any geometry, to ensure that the values returned are accurate.

There are four methods that allow us to determine the outer-frame's dimensions.
winfo_rootx() will give us the window's top left x coordinate, excluding the outer-frame.
winfo_x() will give us the outer-frame's top left x coordinate.
Their difference is the outer-frame's width.

frm_width = win.winfo_rootx() - win.winfo_x()
win_width = win.winfo_width() + (2*frm_width)

The difference between winfo_rooty() and winfo_y() will be our title-bar / menu-bar's height.

titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = win.winfo_height() + (titlebar_height + frm_width)

You set the window's dimensions and the location with the geometry method. The first half of the geometry string is the window's width and height excluding the outer-frame,
and the second half is the outer-frame's top left x and y coordinates.

win.geometry(f'{width}x{height}+{x}+{y}')

You see the window move

One way to prevent seeing the window move across the screen is to use .attributes('-alpha', 0.0) to make the window fully transparent and then set it to 1.0 after the window has been centered. Using withdraw() or iconify() later followed by deiconify() doesn't seem to work well, for this purpose, on Windows 7. I use deiconify() as a trick to activate the window.


Making it optional

You might want to consider providing the user with an option to center the window, and not center by default; otherwise, your code can interfere with the window manager's functions. For example, xfwm4 has smart placement, which places windows side by side until the screen is full. It can also be set to center all windows, in which case you won't have the problem of seeing the window move (as addressed above).


Multiple monitors

If the multi-monitor scenario concerns you, then you can either look into the screeninfo project, or look into what you can accomplish with Qt (PySide2) or GTK (PyGObject), and then use one of those toolkits instead of tkinter. Combining GUI toolkits results in an unreasonably large dependency.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

When you define concatenation you need to use an ALIAS for the new column if you want to order on it combined with DISTINCT Some Ex with sql 2008

--this works 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by FullName

--this works too

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
    from SalesLT.Customer c 
    order by 1

-- this doesn't 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by c.FirstName, c.LastName

-- the problem the DISTINCT needs an order on the new concatenated column, here I order on the singular column
-- this works

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
        as FullName, CustomerID 
        from SalesLT.Customer c 

order by 1, CustomerID

-- this doesn't

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
     from SalesLT.Customer c 
      order by 1, CustomerID

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

It is written here that "By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing."

As it seems that these new checkboxes appeared with Android 2.3, I understand that my previous versions of Android Studio (at least the 2.2) did sign with both signatures. So, to continue as I did before, I think that it is better to check both checkboxes.

EDIT March 31st, 2017 : submitted several apps with both signatures => no problem :)

How do I use a custom deleter with a std::unique_ptr member?

You can simply use std::bind with a your destroy function.

std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
    std::placeholders::_1));

But of course you can also use a lambda.

std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});

Python Infinity - Any caveats?

I found a caveat that no one so far has mentioned. I don't know if it will come up often in practical situations, but here it is for the sake of completeness.

Usually, calculating a number modulo infinity returns itself as a float, but a fraction modulo infinity returns nan (not a number). Here is an example:

>>> from fractions import Fraction
>>> from math import inf
>>> 3 % inf
3.0
>>> 3.5 % inf
3.5
>>> Fraction('1/3') % inf
nan

I filed an issue on the Python bug tracker. It can be seen at https://bugs.python.org/issue32968.

Update: this will be fixed in Python 3.8.

Strings as Primary Keys in SQL Database

Indices imply lots of comparisons.

Typically, strings are longer than integers and collation rules may be applied for comparison, so comparing strings is usually more computationally intensive task than comparing integers.

Sometimes, though, it's faster to use a string as a primary key than to make an extra join with a string to numerical id table.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

Configuring Git over SSH to login once

If you're using github, they have a very nice tutorial that explains it more clearly (at least to me).

http://help.github.com/set-up-git-redirect/

How to insert an item into an array at a specific index (JavaScript)?

You can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

Tooltip with HTML content without JavaScript

Using the title attribute:

_x000D_
_x000D_
<a href="#" title="Tooltip here">Link</a>
_x000D_
_x000D_
_x000D_

How can I run multiple npm scripts in parallel?

In a package.json in the parent folder:

"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"

this work in windows

How to create a circle icon button in Flutter?

You can easily do the following:

FlatButton(
      onPressed: () {

       },
      child: new Icon(
        Icons.arrow_forward,
        color: Colors.white,
        size: 20.0,
      ),
      shape: new CircleBorder(),
      color: Colors.black12,
    )

The result isenter image description here

MVC Redirect to View from jQuery with parameters

i used to do like this

inside view

<script type="text/javascript">

//will replace the '_transactionIds_' and '_payeeId_' 
var _addInvoiceUrl = '@(Html.Raw( Url.Action("PayableInvoiceMainEditor", "Payables", new { warehouseTransactionIds ="_transactionIds_",payeeId = "_payeeId_", payeeType="Vendor" })))';

on javascript file

var url = _addInvoiceUrl.replace('_transactionIds_', warehouseTransactionIds).replace('_payeeId_', payeeId);
        window.location.href = url;

in this way i can able to pass the parameter values on demand..

by using @Html.Raw, url will not get amp; for parameters

How do I convert a decimal to an int in C#?

No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.

int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));

This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.

IDEA: javac: source release 1.7 requires target release 1.7

Most likely you have incorrect compiler options imported from Maven here:

compiler options

Also check project and module bytecode (target) version settings outlined on the screenshot.

Other places where the source language level is configured:

  • Project Structure | Project

project

  • Project Structure | Modules (check every module) | Sources

sources

Maven default language level is 1.5 (5.0), you will see this version as the Module language level on the screenshot above.

This can be changed using maven-compiler-plugin configuration inside pom.xml:

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

or

<project>
  [...]
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  [...]
</project>

IntelliJ IDEA will respect this setting after you Reimport the Maven project in the Maven Projects tool window:

reimport

Check if string contains only digits

string.match(/^[0-9]+$/) != null;

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

How can I create download link in HTML?

There's one more subtlety that can help here.

I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn't work all the time because the browser's compulsion to play the or display the file is still very strong.

BUT.. this is based on examining the extension on the URL's filename!You don't want to fiddle with the server's extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download's rename feature to fix the name.

_x000D_
_x000D_
<a target="_blank" download="realname.mp3" href="realname.UNKNOWN">Download it</a>_x000D_
<a target="_blank" href="realname.mp3">Play it</a>
_x000D_
_x000D_
_x000D_

I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn't.

Regular expression for validating names and surnames?

It's a very difficult problem to validate something like a name due to all the corner cases possible.

Corner Cases

Sanitize the inputs and let them enter whatever they want for a name, because deciding what is a valid name and what is not is probably way outside the scope of whatever you're doing; given the range of potential strange - and legal names is nearly infinite.

If they want to call themselves Tricyclopltz^2-Glockenschpiel, that's their problem, not yours.

Select DISTINCT individual columns in django?

User order by with that field, and then do distinct.

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

How to insert element into arrays at specific position?

This is better method how insert item to array on some position.

function arrayInsert($array, $item, $position)
{
    $begin = array_slice($array, 0, $position);
    array_push($begin, $item);
    $end = array_slice($array, $position);
    $resultArray = array_merge($begin, $end);
    return $resultArray;
}

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

Determine the number of rows in a range

I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows that will give you the number of rows.

So, if you have a named data range called Data that has 7 rows, then =ROWS(Data) will show 7 in that cell.

Some dates recognized as dates, some dates not recognized. Why?

A workaround for this problem consists in temporarily changing your regional settings, so the date format of the CSV imported file "matches" the regional settings one.

Open Office seems to work in a similar way for that issue, see: http://www.oooforum.org/forum/viewtopic.phtml?t=85898

How can I get Docker Linux container information from within the container itself?

You can use this command line to identify the current container ID (tested with docker 1.9).

awk -F"-|/." '/1:/ {print $3}' /proc/self/cgroup

Then, a little request to Docker API (you can share /var/run/docker.sock) to retrieve all informations.

execute function after complete page load

I tend to use the following pattern to check for the document to complete loading. The function returns a Promise (if you need to support IE, include the polyfill) that resolves once the document completes loading. It uses setInterval underneath because a similar implementation with setTimeout could result in a very deep stack.

function getDocReadyPromise()
{
  function promiseDocReady(resolve)
  {
    function checkDocReady()
    {
      if (document.readyState === "complete")
      {
        clearInterval(intervalDocReady);
        resolve();
      }
    }
    var intervalDocReady = setInterval(checkDocReady, 10);
  }
  return new Promise(promiseDocReady);
}

Of course, if you don't have to support IE:

const getDocReadyPromise = () =>
{
  const promiseDocReady = (resolve) =>
  {
    const checkDocReady = () =>
      ((document.readyState === "complete") && (clearInterval(intervalDocReady) || resolve()));
    let intervalDocReady = setInterval(checkDocReady, 10);
  }
  return new Promise(promiseDocReady);
}

With that function, you can do the following:

getDocReadyPromise().then(whatIveBeenWaitingToDo);

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

Check if enum exists in Java

Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

I have come up with the following three alternatives on how to look up an enum:

private enum Test {
    TEST1, TEST2;

    public Test fromNameOrThrowException(String name) {
        return Arrays.stream(values())
                .filter(e -> e.name().equals(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
    }

    public Test fromNameOrNull(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
    }

    public Optional<Test> fromName(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
    }
}

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

jQuery how to bind onclick event to dynamically added HTML element

All of these methods are deprecated. You should use the on method to solve your problem.

If you want to target a dynamically added element you'll have to use

$(document).on('click', selector-to-your-element , function() {
     //code here ....
});

this replace the deprecated .live() method.

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

Python 3.8 with boto3 v1.16v - 2020 December

For configuring routes, you have to configure API Gateway to accept routes. otherwise other than the base route everything else will end up in a {missing auth token} or something other...

Once you configured API Gateway to accept routes, make sure that you enabled lambda proxy, so that things will work better,

to access routes,

new_route = event['path'] # /{some_url}

to access query parameter

query_param = event['queryStringParameters'][{query_key}]

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

How do I pause my shell script for a second before continuing?

use trap to pause and check command line (in color using tput) before running it

trap 'tput setaf 1;tput bold;echo $BASH_COMMAND;read;tput init' DEBUG

press any key to continue

use with set -x to debug command line

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

How to make a HTTP PUT request?


protected void UpdateButton_Click(object sender, EventArgs e)
        {
            var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
            var bytes = Encoding.ASCII.GetBytes(values);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
            request.Method = "PUT";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            var response =  (HttpWebResponse) request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
                UpdateResponseLabel.Text = "Update completed";
            else
                UpdateResponseLabel.Text = "Error in update";
        }

Check if a string is a date value

This is how I solved this problem in an app I'm working on right now:

updated based on feedback from krillgar:

var isDate = function(date) {
    return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}

What's the difference between ng-model and ng-bind

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

This example would help you to understand.

PHP passing $_GET in linux command prompt

-- Option 1: php-cgi --

Use 'php-cgi' in place of 'php' to run your script. This is the simplest way as you won't need to specially modify your php code to work with it:

php-cgi -f /my/script/file.php a=1 b=2 c=3

-- Option 2: if you have a web server --

If the php file is on a web server you can use 'wget' on the command line:

wget 'http://localhost/my/script/file.php?a=1&b=2&c=3'

OR:

wget -q -O - "http://localhost/my/script/file.php?a=1&b=2&c=3"

-- Accessing the variables in php --

In both option 1 & 2 you access these parameters like this:

$a = $_GET["a"];
$b = $_GET["b"];
$c = $_GET["c"];

Make docker use IPv4 for port binding

By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.

From RedHat https://access.redhat.com/solutions/3114021

Remove elements from collection while iterating

Only second approach will work. You can modify collection during iteration using iterator.remove() only. All other attempts will cause ConcurrentModificationException.

Globally catch exceptions in a WPF application?

Example code using NLog that will catch exceptions thrown from all threads in the AppDomain, from the UI dispatcher thread and from the async functions:

App.xaml.cs :

public partial class App : Application
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        SetupExceptionHandling();
    }

    private void SetupExceptionHandling()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");

        DispatcherUnhandledException += (s, e) =>
        {
            LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
            e.Handled = true;
        };

        TaskScheduler.UnobservedTaskException += (s, e) =>
        {
            LogUnhandledException(e.Exception, "TaskScheduler.UnobservedTaskException");
            e.SetObserved();
        };
    }

    private void LogUnhandledException(Exception exception, string source)
    {
        string message = $"Unhandled exception ({source})";
        try
        {
            System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception ex)
        {
            _logger.Error(ex, "Exception in LogUnhandledException");
        }
        finally
        {
            _logger.Error(exception, message);
        }
    }

How to "add existing frameworks" in Xcode 4?

Another easy way to do it so that it is referenced in the project folder you want, like "Frameworks", is to:

  1. Select "Show the Project navigator"
  2. Right-click on the project folder you wish to add the framework to.
  3. Select 'Add Files to "YourProjectName"'
  4. Browse to the framework - generally under /Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks
  5. Select the one you want.
  6. Select "Add"

It will appear in both the project navigator where you want it, as well as in the "Link Binary With Libraries" area of the "Build Phases" pane of your target.

Unable to ping vmware guest from another vmware guest

In Menu bar

select the Host-> Virtual Network Settings -> Host Virtual Network Mapping...

set your drop down list as your host Network Adapter...If You can not ping Check your Firewall Status Because the Firewall is blocked the 'ping' packets

Java using enum with switch statement

If whichView is an object of the GuideView Enum, following works well. Please note that there is no qualifier for the constant after case.

switch (whichView) {
    case SEVEN_DAY:
        ...
        break;
    case NOW_SHOWING:
        ...
        break;
}

Check if element exists in jQuery

your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists:

Vanilla JavaScript: in case you have more advanced selectors:

//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}

if(document.querySelector("#elemId")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}

jQuery:

if(jQuery("#elemId").length){}

AngularJS Directive Restrict A vs E

The restrict option is typically set to:

  • 'A' - only matches attribute name
  • 'E' - only matches element name
  • 'C' - only matches class name
  • 'M' - only matches comment

Here is the documentation link.

What is the definition of "interface" in object oriented programming

Personally I see an interface like a template. If a interface contains the definition for the methods foo() and bar(), then you know every class which uses this interface has the methods foo() and bar().

How to allow http content within an iframe on a https site

All you need to do is just use Google as a Proxy server.

https://www.google.ie/gwt/x?u=[YourHttpLink].

<iframe src="https://www.google.ie/gwt/x?u=[Your http link]"></frame>

It worked for me.

Credits:- https://www.wikihow.com/Use-Google-As-a-Proxy

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

How can I pad an int with leading zeros when using cout << operator?

Another way to achieve this is using old printf() function of C language

You can use this like

int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);

This will print 09 - 01 - 0001 on the console.

You can also use another function sprintf() to write formatted output to a string like below:

int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;

Don't forget to include stdio.h header file in your program for both of these functions

Thing to be noted:

You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d format specifier than this will not fill 2 in blank spaces. This will set pad to 24 and will fill blank spaces.

Validate phone number using angular js

An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.

https://angular-ui.github.io/

What is the difference between required and ng-required?

I would like to make a addon for tiago's answer:

Suppose you're hiding element using ng-show and adding a required attribute on the same:

<div ng-show="false">
    <input required name="something" ng-model="name"/>
</div>

will throw an error something like :

An invalid form control with name='' is not focusable

This is because you just cannot impose required validation on hidden elements. Using ng-required makes it easier to conditionally apply required validation which is just awesome!!

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Perhaps my nested for loops being used incorrectly?

Hint: nested loops won't work for this problem. A simple for loop won't work either.

You need to visualize the problem.

Write two ordered lists on a piece of paper, and using two fingers to point the elements of the respective lists, step through them as you do the merge in your head. Then translate your mental decision process into an algorithm and then code.

The optimal solution makes a single pass through the two lists.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Open images? Python

Instead of

Image.open(picture.jpg)
Img.show

You should have

from PIL import Image

#...

img = Image.open('picture.jpg')
img.show()

You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using %s or .format()).

Making TextView scrollable on Android

Try this:

android:scrollbars = "vertical"

What is the equivalent of the C# 'var' keyword in Java?

As of Java 10, the equivalent is ... var.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you are finding the following screen and facing the problem of code signing required, then one of the following solutions may help you.

Image_1

Solution 1. As said before, sign in with an Apple ID. Then you will get options like this, if you enter correct bundle identifier. Then select the appropriate profile from the list.

Image_2_after_adding_apple_id

Solution 2. If you don't want to sign in with your Apple ID, then change a small flag in project.pbxproj file. Find the following text in the project file.

/* Begin PBXProject section */

Change flag ProvisioningStyle = Automatic; to ProvisioningStyle = Manual; Refer to the following image. After changing the flag, you will see the options to select appropriate profile from the list.

Enter image description here

Using LINQ to concatenate strings

return string.Join(", ", strings.ToArray());

In .Net 4, there's a new overload for string.Join that accepts IEnumerable<string>. The code would then look like:

return string.Join(", ", strings);

How to remove gem from Ruby on Rails application?

If you're using Rails 3+, remove the gem from the Gemfile and run bundle install.

If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install should do the trick.

How can I share Jupyter notebooks with non-programmers?

A great way of doing this on WordPress consists of the following steps:

Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor

Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.

Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:

[gist gist_url]

I have actually implemented this on my blog. You can find the post here

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

How to increase an array's length

You can make use of ArrayList. Array has the fixed number of size.

This Example here can help you. The example is pretty easy with its output.

Output:
2 5 1 23 14 
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29

CodeIgniter: Create new helper?

Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.

E.g. place a file called user_helper.php in /application/helpers with this content:

<?php
  function pre($var)
  {
    echo '<pre>';
    if(is_array($var)) {
      print_r($var);
    } else {
      var_dump($var);
    }
    echo '</pre>';
  }
?> 

Now you can either load the helper via $this->load->helper(‘user’); or add it to application/config/autoload.php config.

When should I use UNSIGNED and SIGNED INT in MySQL?

For negative integer value, SIGNED is used and for non-negative integer value, UNSIGNED is used. It always suggested to use UNSIGNED for id as a PRIMARY KEY.

What's a good, free serial port monitor for reverse-engineering?

I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.

FirstOrDefault returns NullReferenceException if no match is found

FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.

So you just have to check for null first:

string displayName = null;
var keyValue = Dictionary
    .FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue  != null)
{
    displayName = keyValue.Value.DisplayName;
} 

But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.

Another option is to provide a default value with DefaultIfEmpty:

string displayName = Dictionary
    .Where(kv => kv.Value.ID == long.Parse(options.ID))
    .Select(kv => kv.Value.DisplayName)   // not a problem even if no item matches
    .DefaultIfEmpty("--Option unknown--") // or no argument -> null
    .First();                             // cannot cause an exception

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Executing multiple commands from a Windows cmd script

Not sure why the first command is stopping. If you can make it parallel, you can try something like

start cmd.exe /C 1.bat      
start cmd.exe /C 2.bat

How to find my php-fpm.sock?

When you look up your php-fpm.conf

example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf

you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all IPv4 addresses on a
;                            specific port;
;   '[::]:port'            - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

How to know if docker is already logged in to a docker registry server

The docker cli credential scheme is unsurprisingly uncomplicated, just take a look:

cat ~/.docker/config.json

{
  "auths": {
    "dockerregistry.myregistry.com": {},
    "https://index.docker.io/v1/": {}

This exists on Windows (use Get-Content ~\.docker\config.json) and you can also poke around the credential tool which also lists the username ... and I think you can even retrieve the password

. "C:\Program Files\Docker\Docker\resources\bin\docker-credential-wincred.exe" list

{"https://index.docker.io/v1/":"kcd"}

Difference between string and text in rails?

If you are using oracle... STRING will be created as VARCHAR(255) column and TEXT, as a CLOB.

NATIVE_DATABASE_TYPES = {
    primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
    string: { name: "VARCHAR2", limit: 255 },
    text: { name: "CLOB" },
    ntext: { name: "NCLOB" },
    integer: { name: "NUMBER", limit: 38 },
    float: { name: "BINARY_FLOAT" },
    decimal: { name: "DECIMAL" },
    datetime: { name: "TIMESTAMP" },
    timestamp: { name: "TIMESTAMP" },
    timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
    timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
    time: { name: "TIMESTAMP" },
    date: { name: "DATE" },
    binary: { name: "BLOB" },
    boolean: { name: "NUMBER", limit: 1 },
    raw: { name: "RAW", limit: 2000 },
    bigint: { name: "NUMBER", limit: 19 }
}

https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb

Global constants file in Swift

Like others have mentioned, anything declared outside a class is global.

You can also create singletons:

class TestClass {
    static let sharedInstance = TestClass()
    // Anything else goes here
    var number = 0
}

Whenever you want to use something from this class, you e.g. write:

TestClass.sharedInstance.number = 1

If you now write println(TestClass.sharedInstance.number) from anywhere in your project you will print 1 to the log. This works for all kinds of objects.

tl;dr: Any time you want to make everything in a class global, add static let sharedInstance = YourClassName() to the class, and address all values of the class with the prefix YourClassName.sharedInstance

wait() or sleep() function in jquery?

You can use the .delay() function.
This is what you're after:

.addClass("load").delay(2000).addClass("done");

Column count doesn't match value count at row 1

MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:

INSERT INTO `receiving_table`
  (id,
  first_name,
  last_name)
VALUES 
  (1002,'Charles','Babbage'),
  (1003,'George', 'Boole'),
  (1001,'Donald','Chamberlin'),
  (1004,'Alan','Turing'),
  (1005,'My','Widenius');

IF formula to compare a date with current date and return result

You can enter the following formula in the cell where you want to see the Overdue or Not due result:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))

This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue, otherwise it is set to Not due.

How to rename a class and its corresponding file in Eclipse?

Right click file -> Refactor -> Rename.

Difference between static memory allocation and dynamic memory allocation

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

Import SQL file into mysql

For localhost on XAMPP. Open a cmd window and type

cd C:\xampp\mysql\bin
mysql.exe -u root -p

Attention! No semi-colon after -p Enter your password and type

use database_name;

to select the database you need.

Check if your table is there

show tables;

Import from your sql file

source sqlfile.sql;

I have put my file on C:\xampp\mysql\bin location in order to don't mix up with locations of sql file.

Remove all whitespace in a string

"Whitespace" includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

Python 3

' hello  apple '.translate(str.maketrans('', '', ' \n\t\r'))

OR if you want to be thorough:

import string
' hello  apple'.translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

OR if you want to be thorough:

import string
' hello  apple'.translate(None, string.whitespace)

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

.NET Core vs Mono

In a nutshell:

Mono = Compiler for C#

Mono Develop = Compiler+IDE

.Net Core = ASP Compiler

Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.

Job for mysqld.service failed See "systemctl status mysqld.service"

Had the same problem. Solved as given below. Use command :

sudo tail -f /var/log/messages|grep -i mysql

to check if SELinux policy is causing the issue. If so, first check if SELinux policy is enabled using command #sestatus. If it shows enabled, then disable it. To disable:

  1. # vi /etc/sysconfig/selinux
  2. change 'SELINUX=enforcing' to 'SELINUX=disabled'
  3. restart linux
  4. check with sestatus and it should show "disabled"

Uninstall and reinstall mysql. It should be working.

Disable Copy or Paste action for text box?

EX:

<input type="textbox" ondrop="return false;" onpaste="return false;">

Use these attributes in the required textbox in HTML. Now the drag-and-drop and the paste functionality are disabled.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I have solved above problem Applying below steps

enter image description here

And after you made thses changes, do following changes in your web.config

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />

Disable-web-security in Chrome 48+

On OS X, to open a new Chrome window - without having to close the already open windows first - pass in the additional -n flag. Make sure to specify empty string for data-dir (necessary for newer versions of Chrome, like v50 something+).

open -na /Applications/Google\ Chrome.app/ --args --disable-web-security --user-data-dir=""

I found that using Chrome 60+ on Mac OS X Sierra, the above command no longer worked, but a slight modification does:

open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_sess_1" --disable-web-security

The data directory path is important. Even if you're standing in your home directory when issuing the command, you can't simply refer to a local directory. It needs to be an absolute path.

How to call javascript from a href?

<a onClick="yourFunction(); return false;" href="fallback.html">One Way</a>

** Edit **
From the flurry of comments, I'm sharing the resources given/found.

Previous SO Q and A's:

Interesting reads:

What is the syntax for Typescript arrow functions with generics?

while the popular answer with extends {} works and is better than extends any, it forces the T to be an object

const foo = <T extends {}>(x: T) => x;

to avoid this and preserve the type-safety, you can use extends unknown instead

const foo = <T extends unknown>(x: T) => x;

How do HashTables deal with collisions?

Update since Java 8: Java 8 uses a self-balanced tree for collision-handling, improving the worst case from O(n) to O(log n) for lookup. The use of a self-balanced tree was introduced in Java 8 as an improvement over chaining (used until java 7), which uses a linked-list, and has a worst case of O(n) for lookup (as it needs to traverse the list)

To answer the second part of your question, insertion is done by mapping a given element to a given index in the underlying array of the hashmap, however, when a collision occurs, all elements must still be preserved (stored in a secondary data-structure, and not just replaced in the underlying array). This is usually done by making each array-component (slot) be a secondary datastructure (aka bucket), and the element is added to the bucket residing on the given array-index (if the key does not already exist in the bucket, in which case it is replaced).

During lookup, the key is hashed to it's corresponding array-index, and search is performed for an element matching the (exact) key in the given bucket. Because the bucket does not need to handle collisions (compares keys directly), this solves the problem of collisions, but does so at the cost of having to perform insertion and lookup on the secondary datastructure. The key point is that in a hashmap, both the key and the value is stored, and so even if the hash collides, keys are compared directly for equality (in the bucket), and thus can be uniquely identified in the bucket.

Collission-handling brings the worst-case performance of insertion and lookup from O(1) in the case of no collission-handling to O(n) for chaining (a linked-list is used as secondary datastructure) and O(log n) for self-balanced tree.

References:

Java 8 has come with the following improvements/changes of HashMap objects in case of high collisions.

  • The alternative String hash function added in Java 7 has been removed.

  • Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after certain threshold is reached.

Above changes ensure performance of O(log(n)) in worst case scenarios (https://www.nagarro.com/en/blog/post/24/performance-improvement-for-hashmap-in-java-8)

Creating a comma separated list from IList<string> or IEnumerable<string>

You could also use something like the following after you have it converted to an array using one of the of methods listed by others:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Configuration;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
            string[] itemList = { "Test1", "Test2", "Test3" };
            commaStr.AddRange(itemList);
            Console.WriteLine(commaStr.ToString()); //Outputs Test1,Test2,Test3
            Console.ReadLine();
        }
    }
}

Edit: Here is another example

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

How to use pip with Python 3.x alongside Python 2.x

In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:

pip install python2-module-name

pip3 install python3-module-name

That's all

How do you get the path to the Laravel Storage folder?

In Laravel 3, call path('storage').

In Laravel 4, use the storage_path() helper function.

How to elegantly check if a number is within a range?

Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}

For further illustration:

public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}

Base64 encoding and decoding in client-side Javascript

Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa() and atob() functions.

For server-side JavaScript (Node), you can use Buffers to decode.

If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:

http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html

With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.

How do I use properly CASE..WHEN in MySQL

I think part of it is that you're stating the value you're selecting after CASE, and then using WHEN x = y syntax afterward, which is a combination of two different methods of using CASE. It should either be

CASE X
  WHEN a THEN ...
  WHEN b THEN ...

or

CASE
  WHEN x = a THEN ...
  WHEN x = b THEN ...

How to perform update operations on columns of type JSONB in Postgres 9.4

Matheus de Oliveira created handy functions for JSON CRUD operations in postgresql. They can be imported using the \i directive. Notice the jsonb fork of the functions if jsonb if your data type.

9.3 json https://gist.github.com/matheusoliveira/9488951

9.4 jsonb https://gist.github.com/inindev/2219dff96851928c2282

What is the difference between compileSdkVersion and targetSdkVersion?

The Application settings of an Android project's properties in Visual Studio 2017 (15.8.5) has them combined:

enter image description here

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

How to make an ImageView with rounded corners?

Starting with the version 1.2.0-alpha03 of the the Material Components Library there is the new ShapeableImageView.

You can use something like:

  <com.google.android.material.imageview.ShapeableImageView
      ...
      app:shapeAppearanceOverlay="@style/roundedImageView"
      app:srcCompat="@drawable/ic_image" />

with:

  <style name="roundedImageView" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
  </style>

Or programmatically:

float radius = getResources().getDimension(R.dimen.default_corner_radius);
imageView.setShapeAppearanceModel(imageView.getShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,radius)
    .build());

enter image description here

How to resolve a Java Rounding Double issue

Save the number of cents rather than dollars, and just do the format to dollars when you output it. That way you can use an integer which doesn't suffer from the precision issues.

Android Studio with Google Play Services

Google Play services Integration in Android studio.

Step 1:

SDK manager->Tools Update this

1.Google play services
2.Android Support Repository

Step 2:

chance in build.gradle 
defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.0.+'
}

Step 3:

 android.manifest.xml
<uses-sdk
        android:minSdkVersion="8" />

Step 4:

Sync project file with grandle.
wait for few minute.

Step 5:

File->Project Structure find error with red bulb images,click on go to add dependencies select your app module.
Save

Please put comment if you have require help. Happy coding.

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

How to get the selected index of a RadioGroup in Android

You could have a reference to the radio group and use getCheckedRadioButtonId () to get the checked radio button id. Take a look here

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

Then when you need to get the selected radio option.

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}

How to run a PowerShell script without displaying a window?

Here's a one-liner:

mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& 'C:\Example Path That Has Spaces\My Script.ps1'"""""", 0 : window.close")

Although it's possible for this to flash a window very briefly, that should be a rare occurrence.

How to restart a node.js server

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

Global Angular CLI version greater than local version

Two ways to solve this global and local angular CLI version issue.
1. Keep a specific angular-cli version for both environments.
2. Goto latest angular-cli version for both environments.

1. Specific angular-cli version

First, find out which angular version you want to keep on the global and local environment.

ng --version

for example: here we keeping local angular CLI version 8.3.27

So, we have to change the global version also on 8.3.27. use cmd>

npm install --save-dev @angular/[email protected] -g

here, '-g' flag for a set global angular-cli version.

2. Goto latest angular version for both CLI environment.

npm install --save-dev @angular/cli@latest -g  
npm install --save-dev @angular/cli@latest 

GIT: Checkout to a specific folder

I defined an git alias to achieve just this (before I found this question).

It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.

git checkto develop ~/my_project_git

This e.g. would checkout the develop branch into "~/my_project_git" directory.

This is the alias code inside ~/.gitconfig:

[alias]
    checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
               exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
               dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
               git checkout \"$1\"; cd \"$cDir\"; };f"

JavaScript closures vs. anonymous functions

You are both using closures.

I 'm going with the Wikipedia definition here:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

Your friend's attempt clearly uses the variable i, which is non-local, by taking its value and making a copy to store into the local i2.

Your own attempt passes i (which at the call site is in scope) to an anonymous function as an argument. This is not a closure so far, but then that function returns another function that references the same i2. Since inside the inner anonymous function i2 is not a local, this creates a closure.

Setting PayPal return URL and making it auto return?

I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"

where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

Comments please??

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

Extract the filename from a path

$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name

Works with both relative an absolute paths

Generate a random letter in Python

import random
def guess_letter():
    return random.choice('abcdefghijklmnopqrstuvwxyz')

JavaScript seconds to time string with format hh:mm:ss

Non-prototype version of toHHMMSS:

    function toHHMMSS(seconds) {
        var sec_num = parseInt(seconds);
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);        
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        return time;
    }   

How to make IPython notebook matplotlib plot inline

To make matplotlib inline by default in Jupyter (IPython 3):

  1. Edit file ~/.ipython/profile_default/ipython_config.py

  2. Add line c.InteractiveShellApp.matplotlib = 'inline'

Please note that adding this line to ipython_notebook_config.py would not work. Otherwise it works well with Jupyter and IPython 3.1.0

how to print json data in console.log

To output an object to the console, you have to stringify the object first:

success:function(data){
     console.log(JSON.stringify(data));
}