Programs & Examples On #System profiler

Tomcat is not deploying my web project from Eclipse

I have faced this issue and I just removed the server from eclipse and re-configured it... And everything started working fine... I have faced it two three times and the same thing worked.

Ruby Array find_first object?

Either I don't understand your question, or Enumerable#find is the thing you were looking for.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

Python - How to cut a string in Python?

You need to split the string:

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s.split('&')
['http://www.domain.com/?s=some', 'two=20']

That will return a list as you can see so you can do:

>>> s2 = s.split('&')[0]
>>> print s2
http://www.domain.com/?s=some

How to mount a single file in a volume

I have same issue on my Windows 8.1

It turned out that it was due to case-sensitivity of path. I called docker-compose up from directory cd /c/users/alex/ and inside container a file was turned into directory.

But when I did cd /c/Users/alex/ (not Users capitalized) and called docker-compose up from there, it worked.

In my system both Users dir and Alex dir are capitalized, though it seems like only Users dir matter.

How to track down access violation "at address 00000000"

An access violation at anywhere near adress '00000000' indicates a null pointer access. You're using something before it's ever been created, most likely, or after it's been FreeAndNil()'d.

A lot of times this is caused by accessing a component in the wrong place during form creation, or by having your main form try and access something in a datamodule that hasn't been created yet.

MadExcept makes it pretty easy to track these things down, and is free for non-commercial use. (Actually, a commercial use license is pretty inexpensive as well, and well worth the money.)

How to split one string into multiple strings separated by at least one space in bash shell?

Probably the easiest and most secure way in BASH 3 and above is:

var="string    to  split"
read -ra arr <<<"$var"

(where arr is the array which takes the split parts of the string) or, if there might be newlines in the input and you want more than just the first line:

var="string    to  split"
read -ra arr -d '' <<<"$var"

(please note the space in -d ''; it cannot be omitted), but this might give you an unexpected newline from <<<"$var" (as this implicitly adds an LF at the end).

Example:

touch NOPE
var="* a  *"
read -ra arr <<<"$var"
for a in "${arr[@]}"; do echo "[$a]"; done

Outputs the expected

[*]
[a]
[*]

as this solution (in contrast to all previous solutions here) is not prone to unexpected and often uncontrollable shell globbing.

Also this gives you the full power of IFS as you probably want:

Example:

IFS=: read -ra arr < <(grep "^$USER:" /etc/passwd)
for a in "${arr[@]}"; do echo "[$a]"; done

Outputs something like:

[tino]
[x]
[1000]
[1000]
[Valentin Hilbig]
[/home/tino]
[/bin/bash]

As you can see, spaces can be preserved this way, too:

IFS=: read -ra arr <<<' split  :   this    '
for a in "${arr[@]}"; do echo "[$a]"; done

outputs

[ split  ]
[   this    ]

Please note that the handling of IFS in BASH is a subject on its own, so do your tests; some interesting topics on this:

  • unset IFS: Ignores runs of SPC, TAB, NL and on line starts and ends
  • IFS='': No field separation, just reads everything
  • IFS=' ': Runs of SPC (and SPC only)

Some last examples:

var=$'\n\nthis is\n\n\na test\n\n'
IFS=$'\n' read -ra arr -d '' <<<"$var"
i=0; for a in "${arr[@]}"; do let i++; echo "$i [$a]"; done

outputs

1 [this is]
2 [a test]

while

unset IFS
var=$'\n\nthis is\n\n\na test\n\n'
read -ra arr -d '' <<<"$var"
i=0; for a in "${arr[@]}"; do let i++; echo "$i [$a]"; done

outputs

1 [this]
2 [is]
3 [a]
4 [test]

BTW:

  • If you are not used to $'ANSI-ESCAPED-STRING' get used to it; it's a timesaver.

  • If you do not include -r (like in read -a arr <<<"$var") then read does backslash escapes. This is left as exercise for the reader.


For the second question:

To test for something in a string I usually stick to case, as this can check for multiple cases at once (note: case only executes the first match, if you need fallthrough use multiple case statements), and this need is quite often the case (pun intended):

case "$var" in
'')                empty_var;;                # variable is empty
*' '*)             have_space "$var";;        # have SPC
*[[:space:]]*)     have_whitespace "$var";;   # have whitespaces like TAB
*[^-+.,A-Za-z0-9]*) have_nonalnum "$var";;    # non-alphanum-chars found
*[-+.,]*)          have_punctuation "$var";;  # some punctuation chars found
*)                 default_case "$var";;      # if all above does not match
esac

So you can set the return value to check for SPC like this:

case "$var" in (*' '*) true;; (*) false;; esac

Why case? Because it usually is a bit more readable than regex sequences, and thanks to Shell metacharacters it handles 99% of all needs very well.

Add a column to a table, if it does not already exist

IF NOT EXISTS (SELECT 1  FROM SYS.COLUMNS WHERE  
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Email address validation using ASP.NET MVC data type attributes

Try Html.EditorFor helper method instead of Html.TextBoxFor.

How do I tell if an object is a Promise?

Here's my original answer, which has since been ratified in the spec as the way to test for a promise:

Promise.resolve(obj) == obj

This works because the algorithm explicitly demands that Promise.resolve must return the exact object passed in if and only if it is a promise by the definition of the spec.

I have another answer here, which used to say this, but I changed it to something else when it didn't work with Safari at that time. That was a year ago, and this now works reliably even in Safari.

I would have edited my original answer, except that felt wrong, given that more people by now have voted for the altered solution in that answer than the original. I believe this is the better answer, and I hope you agree.

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

it is working in my google chrome browser version 11.0.696.60

I created a simple page with no other items just basic tags and no separate CSS file and got an image

this is what i setup:

<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>

I put an id just in case there was a hidden id tag and it works

xls to csv converter

We can use Pandas lib of Python to conevert xls file to csv file Below code will convert xls file to csv file . import pandas as pd

Read Excel File from Local Path :

df = pd.read_excel("C:/Users/IBM_ADMIN/BU GPA Scorecard.xlsx",sheetname=1)

Trim Spaces present on columns :

df.columns = df.columns.str.strip()

Send Data frame to CSV file which will be pipe symbol delimted and without Index :

df.to_csv("C:/Users/IBM_ADMIN/BU GPA Scorecard csv.csv",sep="|",index=False)

Turn off auto formatting in Visual Studio

VS2015 settings that helped me prevent auto formatting:

(and Tools > Options > Text Editor > Basic > Advanced, just like Tango91 suggested)

enter image description here

Checkout multiple git repos into same Jenkins workspace

Depending upon the relationships of the repositories, another approach is to add the other repository (repositories) as a git submodules to one of the repositories. A git submodule is creates a reference to the other repos. Those submodule repos are not cloned unless the you specify the --recursive flag when cloning the "superproject" (official term).

Here's the command to add a submodule into the current project:

git submodule add <repository URI path to clone>

We are using Jenkins v1.645 and the git SCM will out-of-the-box do a recursive clone for superprojects. Voila you get the superproject files and all the dependent (submodule) repo files in their own respective directories in the same Jenkins job workspace.

Not vouching that this is the correct approach rather it's an approach.

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

  //-----------------------------------------------------------------------------
  @Override
  public void onCreate (Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.main_activity);

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>

Finding the next available id in MySQL

I don't think you can ever be sure on the next id, because someone might insert a new row just after you asked for the next id. You would at least need a transaction, and if I'm not mistaken you can only get the actual id used after inserting it, at least that is the common way of handling it -- see http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Using unset vs. setting a variable to empty

So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).

I made my own test..

foo=(5 6 8)
echo ${#foo[*]}
unset foo
echo ${#foo[*]}

Which results in..

3
0

So just to clarify that unset'ting the entire array will in fact remove it entirely.

How to know which is running in Jupyter notebook?

import sys
sys.executable

will give you the interpreter. You can select the interpreter you want when you create a new notebook. Make sure the path to your anaconda interpreter is added to your path (somewhere in your bashrc/bash_profile most likely).

For example I used to have the following line in my .bash_profile, that I added manually :

export PATH="$HOME/anaconda3/bin:$PATH"

EDIT: As mentioned in a comment, this is not the proper way to add anaconda to the path. Quoting Anaconda's doc, this should be done instead after install, using conda init:

Should I add Anaconda to the macOS or Linux PATH?

We do not recommend adding Anaconda to the PATH manually. During installation, you will be asked “Do you wish the installer to initialize Anaconda3 by running conda init?” We recommend “yes”. If you enter “no”, then conda will not modify your shell scripts at all. In order to initialize after the installation process is done, first run source <path to conda>/bin/activate and then run conda init

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

Anaconda-Navigator - Ubuntu16.04

add anaconda installation path to .bashrc

export PATH="$PATH:/home/username/anaconda3/bin"

load in terminal

$ source ~/.bashrc

run from terminal

$ anaconda-navigator

How can I pass a username/password in the header to a SOAP WCF Service

Obviously it has been some years this post has been alive - but the fact is I did find it when looking for a similar issue. In our case, we had to add the username / password info to the Security header. This is different from adding header info outside of the Security headers.

The correct way to do this (for custom bindings / authenticationMode="CertificateOverTransport") (as on the .Net framework version 4.6.1), is to add the Client Credentials as usual :

    client.ClientCredentials.UserName.UserName = "[username]";
    client.ClientCredentials.UserName.Password = "[password]";

and then add a "token" in the security binding element - as the username / pwd credentials would not be included by default when the authentication mode is set to certificate.

You can set this token like so:

    //Get the current binding 
    System.ServiceModel.Channels.Binding binding = client.Endpoint.Binding;
    //Get the binding elements 
    BindingElementCollection elements = binding.CreateBindingElements();
    //Locate the Security binding element
    SecurityBindingElement security = elements.Find<SecurityBindingElement>();

    //This should not be null - as we are using Certificate authentication anyway
    if (security != null)
    {
    UserNameSecurityTokenParameters uTokenParams = new UserNameSecurityTokenParameters();
    uTokenParams.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
security.EndpointSupportingTokenParameters.SignedEncrypted.Add(uTokenParams);
    }

   client.Endpoint.Binding = new CustomBinding(elements.ToArray());

That should do it. Without the above code (to explicitly add the username token), even setting the username info in the client credentials may not result in those credentials passed to the Service.

What is the difference between 'E', 'T', and '?' for Java generics?

compiler will make a capture for each wildcard (e.g., question mark in List) when it makes up a function like:

foo(List<?> list) {
    list.put(list.get()) // ERROR: capture and Object are not identical type.
}

However a generic type like V would be ok and making it a generic method:

<V>void foo(List<V> list) {
    list.put(list.get())
}

MySQL: How to add one day to datetime field in query

How about this: 

select * from fab_scheduler where custid = 1334666058 and eventdate = eventdate + INTERVAL 1 DAY

Creating CSS Global Variables : Stylesheet theme management

It's not possible using CSS, but using a CSS preprocessor like less or SASS.

How to enable zoom controls and pinch zoom in a WebView?

Try this code, I get working fine.

 webSettings.setSupportZoom(true);
 webSettings.setBuiltInZoomControls(true);
 webSettings.setDisplayZoomControls(false);

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

How to initialize an array's length in JavaScript?

  • Array(5) gives you an array with length 5 but no values, hence you can't iterate over it.

  • Array.apply(null, Array(5)).map(function () {}) gives you an array with length 5 and undefined as values, now it can be iterated over.

  • Array.apply(null, Array(5)).map(function (x, i) { return i; }) gives you an array with length 5 and values 0,1,2,3,4.

  • Array(5).forEach(alert) does nothing, Array.apply(null, Array(5)).forEach(alert) gives you 5 alerts

  • ES6 gives us Array.from so now you can also use Array.from(Array(5)).forEach(alert)

  • If you want to initialize with a certain value, these are good to knows...
    Array.from('abcde'), Array.from('x'.repeat(5))
    or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]

How to terminate a python subprocess launched with shell=True

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()

p.kill() ends up killing the shell process and cmd is still running.

I found a convenient fix this by:

p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)

This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed. p.pid will be the id of your cmd process then.

p.kill() should work.

I don't know what effect this will have on your pipe though.

Android 'Unable to add window -- token null is not for an application' exception

Try getParent() at the argument place of context like new AlertDialog.Builder(getParent()); Hope it will work, it worked for me.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

open terminal and type command

sudo snap install postman

hit enter button if it asks for password enter and proceed it will install postman

If above solution doesn't work for you then you should install snap first to install it

sudo apt update
sudo apt install snapd

when snap is installed successfully then u can use its packages and follow my solution for postman

How to save data file into .RData?

Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier

date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")

This was you can always keep a check of when it was run

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

java.io.FileNotFoundException: the system cannot find the file specified

I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.

How to run an android app in background?

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

How to select option in drop down using Capybara

It is not a direct answer, but you can (if your server permit):

1) Create a model for your Organization; extra: It will be easier to populate your HTML.

2) Create a factory (FactoryGirl) for your model;

3) Create a list (create_list) with the factory;

4) 'pick' (sample) a Organization from the list with:

# Random select
option = Organization.all.sample 

# Select the FIRST(0) by id
option = Organization.all[0] 

# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on... 

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

C# DataTable.Select() - How do I format the filter criteria to include null?

Try out Following:

DataRow rows = DataTable.Select("[Name]<>'n/a'")

For Null check in This:

DataRow rows =  DataTable.Select("[Name] <> 'n/a' OR [Name] is NULL" )

Input mask for numeric and decimal

using jQuery input mask plugin (6 whole and 2 decimal places):

HTML:

<input class="mask" type="text" />

jQuery:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});

I hope this helps someone

Search a whole table in mySQL for a string

Try this code,

SELECT 
       * 
FROM 
       `customers` 
WHERE 
       (
          CONVERT 
               (`customer_code` USING utf8mb4) LIKE '%Mary%' 
          OR 
          CONVERT(`customer_name` USING utf8mb4) LIKE '%Mary%' 
          OR 
          CONVERT(`email_id` USING utf8mb4) LIKE '%Mary%' 
          OR 
          CONVERT(`address1` USING utf8mb4) LIKE '%Mary%' 
          OR
          CONVERT(`report_sorting` USING utf8mb4) LIKE '%Mary%'
       )

This is help to solve your problem mysql version 5.7.21

Launch Pycharm from command line (terminal)

You can launch Pycharm from Mac terminal using the open command. Just type open /path/to/App

Applications$ ls -lrt PyCharm\ CE.app/
total 8
drwxr-xr-x@ 71 amit  admin  2414 Sep 24 11:08 lib
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 help
drwxr-xr-x@ 12 amit  admin   408 Sep 24 11:08 plugins
drwxr-xr-x@ 29 amit  admin   986 Sep 24 11:08 license
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 skeletons
-rw-r--r--@  1 amit  admin    10 Sep 24 11:08 build.txt
drwxr-xr-x@  6 amit  admin   204 Sep 24 11:12 Contents
drwxr-xr-x@ 14 amit  admin   476 Sep 24 11:12 bin
drwxr-xr-x@ 31 amit  admin  1054 Sep 25 21:43 helpers
/Applications$
/Applications$ open PyCharm\ CE.app/

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I found there was another solution for this problem rather than creating a symbolic link.

You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD_LIBRARY_PATH environment variable. What I did is to put following line in my .bash_profile:

export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5.15-osx10.6-x86/lib/:$DYLD_LIBRARY_PATH

That's it.

How to parse XML using jQuery?

I assume you are loading the XML from an external file. With $.ajax(), it's quite simple actually:

$.ajax({
    url: 'xmlfile.xml',
    dataType: 'xml',
    success: function(data){
        // Extract relevant data from XML
        var xml_node = $('Pages',data);
        console.log( xml_node.find('Page[Name="test"] > controls > test').text() );
    },
    error: function(data){
        console.log('Error loading XML data');
    }
});

Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page> versus <page>) which can be confusing when you try to use XML tree selectors.

Rails ActiveRecord date between

I have been using the 3 dots, instead of 2. Three dots gives you a range that is open at the beginning and closed at the end, so if you do 2 queries for subsequent ranges, you can't get the same row back in both.

2.2.2 :003 > Comment.where(updated_at: 2.days.ago.beginning_of_day..1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" BETWEEN '2015-07-12 00:00:00.000000' AND '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 
2.2.2 :004 > Comment.where(updated_at: 2.days.ago.beginning_of_day...1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" >= '2015-07-12 00:00:00.000000' AND "comments"."updated_at" < '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 

And, yes, always nice to use a scope!

Can I run multiple programs in a Docker container?

There can be only one ENTRYPOINT, but that target is usually a script that launches as many programs that are needed. You can additionally use for example Supervisord or similar to take care of launching multiple services inside single container. This is an example of a docker container running mysql, apache and wordpress within a single container.

Say, You have one database that is used by a single web application. Then it is probably easier to run both in a single container.

If You have a shared database that is used by more than one application, then it would be better to run the database in its own container and the applications each in their own containers.

There are at least two possibilities how the applications can communicate with each other when they are running in different containers:

  1. Use exposed IP ports and connect via them.
  2. Recent docker versions support linking.

How to ignore a property in class if null, using json.net

This does not exactly answer the original question, but may prove useful depending on the use case. (And since I wound up here after my search, it may be useful for others.)

In my most recent experience, I'm working with a PATCH api. If a property is specified but with no value given (null/undefined because it's js), then the property and value are removed from the object being patched. So I was looking for a way to selectively build an object that could be serialized in such a way that this would work.

I remembered seeing the ExpandoObject, but never had a true use case for it until today. This allows you to build an object dynamically, so you won't have null properties unless you want them there.

Here is a working fiddle, with the code below.

Results:

Standard class serialization
    noName: {"Name":null,"Company":"Acme"}
    noCompany: {"Name":"Fred Foo","Company":null}
    defaultEmpty: {"Name":null,"Company":null}
ExpandoObject serialization
    noName: {"Company":"Acme"}
    noCompany: {"name":"Fred Foo"}
    defaultEmpty: {}

Code:

using Newtonsoft.Json;
using System;
using System.Dynamic;
                    
public class Program
{
    public static void Main()
    {
        SampleObject noName = new SampleObject() { Company = "Acme" };
        SampleObject noCompany = new SampleObject() { Name = "Fred Foo" };
        SampleObject defaultEmpty = new SampleObject();
        
        
        Console.WriteLine("Standard class serialization");
        Console.WriteLine($"    noName: { JsonConvert.SerializeObject(noName) }");
        Console.WriteLine($"    noCompany: { JsonConvert.SerializeObject(noCompany) }");
        Console.WriteLine($"    defaultEmpty: { JsonConvert.SerializeObject(defaultEmpty) }");
        
        
        Console.WriteLine("ExpandoObject serialization");
        Console.WriteLine($"    noName: { JsonConvert.SerializeObject(noName.CreateDynamicForPatch()) }");
        Console.WriteLine($"    noCompany: { JsonConvert.SerializeObject(noCompany.CreateDynamicForPatch()) }");
        Console.WriteLine($"    defaultEmpty: { JsonConvert.SerializeObject(defaultEmpty.CreateDynamicForPatch()) }");
    }
}

public class SampleObject {
    public string Name { get; set; }
    public string Company { get; set; }
    
    public object CreateDynamicForPatch()
    {
        dynamic x = new ExpandoObject();
        
        if (!string.IsNullOrWhiteSpace(Name))
        {
            x.name = Name;
        }
        
        if (!string.IsNullOrEmpty(Company))
        {
            x.Company = Company;
        }
        
        return x;
    }
}

Get the Last Inserted Id Using Laravel Eloquent

Using Eloquent Model

$user = new Report();        
$user->email= '[email protected]';  
$user->save();
$lastId = $user->id;

Using Query Builder

$lastId = DB::table('reports')->insertGetId(['email' => '[email protected]']);

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

How to merge two files line by line in Bash

You can use paste:

paste file1.txt file2.txt > fileresults.txt

Custom seekbar (thumb size, color and background)

No shadow and no rounded borders in the bar

You are using an image so the easiest solution is row your boat with the flow,

You cannot give heights manually,yes you can but make sure it gets enough space to show your full image view there

  • easiest way is use android:layout_height="wrap_content" for SeekBar
  • To get more clear rounded borders you can easily use the same image that you have used with another color.

I am no good with Photoshop but I managed to edit a background one for a test

seekbar_brown seekbar_brown_to_show_progress.png

<SeekBar
    android:splitTrack="false"   // for unwanted white space in thumb
    android:id="@+id/seekBar_luminosite"
    android:layout_width="250dp"   // use your own size
    android:layout_height="wrap_content"
    android:minHeight="10dp"
    android:minWidth="15dp"
    android:maxHeight="15dp"
    android:maxWidth="15dp"
    android:progress="50"
    android:progressDrawable="@drawable/custom_seekbar_progress"
    android:thumb="@drawable/custom_thumb" />

custom_seekbar_progress.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar" />
    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/seekbar_brown_to_show_progress" />
    </item>
</layer-list>

custom_thumb.xml is same as yours

Finally android:splitTrack="false" will remove the unwanted white space in your thumb

Let's have a look at the output :

enter image description here

ORA-00972 identifier is too long alias column name

If you have recently upgraded springboot to 1.4.3, you might need to make changes to yml file:

yml in 1.3 :

jpa: 
  hibernate: 
    namingStrategy: org.hibernate.cfg.EJB3NamingStrategy

yml in 1.4.3 :

jpa: 
  hibernate: 
    naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How do I create a Linked List Data Structure in Java?

The above linked list display in opposite direction. I think the correct implementation of insert method should be

public void insert(int d1, double d2) { 
    Link link = new Link(d1, d2); 

    if(first==null){
        link.nextLink = null;
        first = link; 
        last=link;
    }
    else{
        last.nextLink=link;
        link.nextLink=null;
        last=link;
    }
} 

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Try the following steps:

  1. Open Services window (open "run box" and type services.msc).

  2. Looking for SQL services (with SQL prefix).

  3. Start them (if cannot start. Goto step 4).

  4. Right_click to each service -> Properties -> Change to tab "Log on"-> choise log on as "Local ..." -> 0K. Then start SQL services again.

Try Open SQL and connect database.

Hover and Active only when not disabled

In sass (scss):

 button {
  color: white;
  cursor: pointer;
  border-radius: 4px;

  &:disabled{
    opacity: 0.4;

    &:hover{
      opacity: 0.4;  //this is what you want
    }
  }

  &:hover{
    opacity: 0.9;
  }
}

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

SFTP in Python? (platform independent)

Paramiko is so slow. Use subprocess and shell, here is an example:

remote_file_name = "filename"
remotedir = "/remote/dir"
localpath = "/local/file/dir"
    ftp_cmd_p = """
    #!/bin/sh
    lftp -u username,password sftp://ip:port <<EOF
    cd {remotedir}
    lcd {localpath}
    get {filename}
    EOF
    """
subprocess.call(ftp_cmd_p.format(remotedir=remotedir,
                                 localpath=localpath,
                                 filename=remote_file_name 
                                 ), 
                shell=True, stdout=sys.stdout, stderr=sys.stderr)

How to check the version of GitLab?

cd /opt/gitlab

cat version-manifest.txt

Example:

gitlab-ctl 6.8.2-omnibus
gitlab-rails v6.8.2

Current gitlab version is 6.8.2

Screenshot of the console

SSIS Connection not found in package

For package developed in Visual Studio 2015, I found i must supply a value for the parameter (which would be the case when you deploy or run on different server) which sets the connection manager's connection string instead of using the design time value. This will suppress the error message. I think this could be a bug.

dtexec /project c:\mypath\ETL.ispac /package mypackage.dtsx /SET \Package.Variables[$Project::myParameterName];"myValueForTheParameter"

I tested this without or without parameterize the connection string, which is at the project level. The result was the same: i.e. I have to set the value for the parameter even thought it was not used.

Set custom attribute using JavaScript

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");

But you really should be using data followed with a dash and with its property, like:

<li ... data-icon="base.gif" ...>

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif";

Dynamically create Bootstrap alerts box through JavaScript

function bootstrap_alert() {
        create = function (message, color) {
            $('#alert_placeholder')
                .html('<div class="alert alert-' + color
                    + '" role="alert"><a class="close" data-dismiss="alert">×</a><span>' + message
                    + '</span></div>');
        };
        warning = function (message) {
            create(message, "warning");
        };
        info = function (message) {
            create(message, "info");
        };
        light = function (message) {
            create(message, "light");
        };
        transparent = function (message) {
            create(message, "transparent");
        };
        return {
            warning: warning,
            info: info,
            light: light,
            transparent: transparent
        };
    }

How to change the height of a div dynamically based on another div using css?

#container-of-boxes {
    display: table;
    width: 1158px;
}
#box-1 {
    width: 578px;
}
#box-2 {
    width: 386px;
}
#box-3 {
    width: 194px;
}
#box-1, #box-2, #box-3 {
    min-height: 210px;
    padding-bottom: 20px;
    display: table-cell;
    height: auto;
    overflow: hidden;
}
  • The container must have display:table
  • The boxes inside container must be: display:table-cell
  • Don't put floats.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

How to parse JSON in Java

Read the following blog post, JSON in Java.

This post is a little bit old, but still I want to answer you question.

Step 1: Create a POJO class of your data.

Step 2: Now create a object using JSON.

Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try {
    employee =  mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
} 
catch(JsonGenerationException e) {
    e.printStackTrace();
}

For further reference you can refer to the following link.

Visual Studio: How to show Overloads in IntelliSense?

Ctrl+Shift+Space shows the Edit.ParameterInfo for the selected method, and by selected method I mean the caret must be within the method parentheses.

Here is the Visual Studio 2010 Keybinding Poster.

And for those still using 2008.

Java: Why is the Date constructor deprecated, and what do I use instead?

I got this from Secure Code Guideline for Java

The examples in this section use java.util.Date extensively as it is an example of a mutable API class. In an application, it would be preferable to use the new Java Date and Time API (java.time.*) which has been designed to be immutable.

Scala Doubles, and Precision

It's actually very easy to handle using Scala f interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html

Suppose we want to round till 2 decimal places:

scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198

scala> println(f"$sum%1.2f")
1.57

Jquery - How to make $.post() use contentType=application/json?

Guess what? @BenCreasy was totally right!!

Starting version 1.12.0 of jQuery we can do this:

$.post({
    url: yourURL,
    data: yourData,
    contentType: 'application/json; charset=utf-8'
})
    .done(function (response) {
        //Do something on success response...
    });

I just tested it and it worked!!

redirect COPY of stdout to log file from within bash script itself

Bash 4 has a coproc command which establishes a named pipe to a command and allows you to communicate through it.

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

Detect if Android device has Internet connection

try this one

public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        if (networkConnectivity()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL(
                        "http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(3000);
                urlc.setReadTimeout(4000);
                urlc.connect();
                // networkcode2 = urlc.getResponseCode();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e) {
                return (false);
            }
        } else
            return false;

    }

    private boolean networkConnectivity() {
        ConnectivityManager cm = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}

you'll have to add the following permission to your manifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

Then call like that:

if((new ConnectionDetector(MyService.this)).isConnectingToInternet()){
    Log.d("internet status","Internet Access");
}else{
    Log.d("internet status","no Internet Access");
}

Xcode 10, Command CodeSign failed with a nonzero exit code

I had just added the SystemConfiguration.framework and Reachability h and m when the issue began. I tried all of these solutions and ended up removing systemConfiguration.framework and that fixed it for me. The Reachability h and m are still in the project.

Displaying tooltip on mouse hover of a text

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

In Python, how do I iterate over a dictionary in sorted key order?

Assuming you are using CPython 2.x and have a large dictionary mydict, then using sorted(mydict) is going to be slow because sorted builds a sorted list of the keys of mydict.

In that case you might want to look at my ordereddict package which includes a C implementation of sorteddict in C. Especially if you have to go over the sorted list of keys multiple times at different stages (ie. number of elements) of the dictionaries lifetime.

http://anthon.home.xs4all.nl/Python/ordereddict/

How to list the certificates stored in a PKCS12 keystore with keytool?

What is missing in the question and all the answers is that you might need the passphrase to read public data from the PKCS#12 (.pfx) keystore. If you need a passphrase or not depends on how the PKCS#12 file was created. You can check the ASN1 structure of the file (by running it through a ASN1 parser, openssl or certutil can do this too), if the PKCS#7 data (e.g. OID prefix 1.2.840.113549.1.7) is listed as 'encrypted' or with a cipher-spec or if the location of the data in the asn1 tree is below an encrypted node, you won't be able to read it without knowledge of the passphrase. It means your 'openssl pkcs12' command will fail with errors (output depends on the version). For those wondering why you might be interested in the certificate of a PKCS#12 without knowledge of the passphrase. Imagine you have many keystores and many phassphrases and you are really bad at keeping them organized and you don't want to test all combinations, the certificate inside the file could help you find out which password it might be. Or you are developing software to migrate/renew a keystore and you need to decide in advance which procedure to initiate based on the contained certicate without user interaction. So the latter examples work without passphrase depending on the PKCS#12 structure.

Just wanted to add that, because I didn't find an answer myself and spend a lot of time to figure it out.

Unable to set data attribute using jQuery Data() API

@andyb's accepted answer has a small bug. Further to my comment on his post above...

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

You need to access the attribute like this:

$('#foo').attr('data-helptext', 'Testing 123');

but the data method like this:

$('#foo').data('helptext', 'Testing 123');

The fix above for the .data() method will prevent "undefined" and the data value will be updated (while the HTML will not)

The point of the "data" attribute is to bind (or "link") a value with the element. Very similar to the onclick="alert('do_something')" attribute, which binds an action to the element... the text is useless you just want the action to work when they click the element.

Once the data or action is bound to the element, there is usually* no need to update the HTML, only the data or method, since that is what your application (JavaScript) would use. Performance wise, I don't see why you would want to also update the HTML anyway, no one sees the html attribute (except in Firebug or other consoles).

One way you might want to think about it: The HTML (along with attributes) are just text. The data, functions, objects, etc that are used by JavaScript exist on a separate plane. Only when JavaScript is instructed to do so, it will read or update the HTML text, but all the data and functionality you create with JavaScript are acting completely separate from the HTML text/attributes you see in your Firebug (or other) console.

*I put emphasis on usually because if you have a case where you need to preserve and export HTML (e.g. some kind of micro format/data aware text editor) where the HTML will load fresh on another page, then maybe you need the HTML updated too.

AWS : The config profile (MyName) could not be found

can you check your config file under ~/.aws/config- you might have an invalid section called [myname], something like this (this is an example)

[default]
region=us-west-2
output=json

[myname]
region=us-east-1
output=text

Just remove the [myname] section (including all content for this profile) and you will be fine to run aws cli again

Hidden features of Python

Dict Comprehensions

>>> {i: i**2 for i in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Python documentation

Wikipedia Entry

How to create EditText with cross(x) button at end of it?

Here is the simple complete solution in kotlin.

This whole layout will be your search bar

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_margin="10dp"
        android:background="@drawable/your_desired_drawable">

        <EditText
            android:id="@+id/search_et"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_toStartOf="@id/clear_btn"
            android:background="@null"
            android:hint="search..."
            android:imeOptions="actionSearch"
            android:inputType="text"
            android:maxLines="1"
            android:paddingStart="15dp"
            android:paddingEnd="10dp" />

        <ImageView
            android:id="@+id/clear_btn"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginEnd="15dp"
            android:visibility="gone"
            android:src="@drawable/ic_baseline_clear_24"/>

    </RelativeLayout>

Now this is the functionality of clear button, paste this code in onCreate method.

search_et.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {
            }
            override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
            }
            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()){
                    clear_btn.visibility = VISIBLE
                    clear_btn.setOnClickListener {
                        search_et.text.clear()
                    }
                }else{
                    clear_btn.visibility = GONE
                }
            }
        })

How to format string to money

Parse to your string to a decimal first.

Chrome desktop notification example

Notify.js is a wrapper around the new webkit notifications. It works pretty well.

http://alxgbsn.co.uk/2013/02/20/notify-js-a-handy-wrapper-for-the-web-notifications-api/

How to generate a random string in Ruby

This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, L with 1, etc.

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
  charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
  (0...size).map{ charset.to_a[rand(charset.size)] }.join
end

Difference between res.send and res.json in Express.js

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

app.set('json spaces', 2);
app.set('json replacer', replacer);

And passed to a JSON.stringify() like so:

JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation

This is the code in the res.json() method that the send method doesn't have:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

The method ends up as a res.send() in the end:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

What are the differences between Abstract Factory and Factory design patterns?

abstract factory design pattern with realtime example: what is an abstract factory design pattern? It is similar to the factory method design pattern. we need to use this pattern when we have multiple factories. there will be a grouping of factories defined in this pattern. factory method pattern is a subset of abstract factory design pattern. They have the same advantages as factory patterns. abstract factory relies on object composition whereas the factory method deals with inheritance. factory design pattern in java with a realtime example: what is the factory design pattern? it is mostly used design in object-oriented programming. It is one of the creational patterns. it is all about creating instances. Clients will create the object without exposed to object creational logic. it is widely used in different frameworks ex: the spring framework. we use this pattern when the class doesn’t know the objects of another it must create. Realtime example: when our car breaks down on the road. We need to inform the repairman about what type of vehicle we are using so that repairman will carry tools to fix the repair. as per our input, the repairman will fix the issue and make it ready for us to travel again. There are a few built-in methods that use these patterns. example getInstance() method in JavaUtilcalendar class. With help of getInstance(), we can get objects whenever we execute this method. Javautilcalendar : getInstance() is method return object. https://trendydevx.com/factory-design-pattern-in-java-with-realtime-example/

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

C# importing class into another class doesn't work

namespace MyNamespace
{
    public class MyMainClass
    {
        static void Main()
        {
            MyClass test = new MyClass();
        }
    }

    public class MyClass
    {
        void Stuff()
        {

        }
    }
}

You have no need for using a namespace then because it is all encompased in the same namespace.

If you are unsure of what namespace your class is located, type the class (case sensitive you wish to use) then with your cursor on the class, use CTRL + . and it will offer you a manual import.

Display a view from another controller in ASP.NET MVC

Yes, you can. Return an Action like this :

return RedirectToAction("View", "Name of Controller");

An example:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees");

This approach will call the GET method

Also you could pass values to action like this:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees", new {id = id.ToString(), viewtype = "extended" });

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

How do I download/extract font from chrome developers tools?

Although Marcelo's solution seems to be working great, you may not need to download the font at all! Just link to it remotely.

E.g the font is hosted on example.com, do

@font-face {
  font-family: "Font Name";
  font-style: normal;
  src: url(http://example.com/webfonts/font-name.woff);
}

You may easily figure out the direct url to the font by looking into css code from example.com and see how they linked the file.

ERROR: Sonar server 'http://localhost:9000' can not be reached

In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.

What exactly is nullptr?

NULL need not to be 0. As long you use always NULL and never 0, NULL can be any value. Asuming you programme a von Neuman Microcontroller with flat memory, that has its interrupt vektors at 0. If NULL is 0 and something writes at a NULL Pointer the Microcontroller crashes. If NULL is lets say 1024 and at 1024 there is a reserved variable, the write won't crash it, and you can detect NULL Pointer assignments from inside the programme. This is Pointless on PCs, but for space probes, military or medical equipment it is important not to crash.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

range() for floats

using itertools: lazily evaluated floating point range:

>>> from itertools import count, takewhile
>>> def frange(start, stop, step):
        return takewhile(lambda x: x< stop, count(start, step))

>>> list(frange(0.5, 5, 1.5))
# [0.5, 2.0, 3.5]

Corrupt jar file

As I just came across this topic I wanted to share the reason and solution why I got the message "invalid or corrupt jarfile":

I had updated the version of the "maven-jar-plugin" in my pom.xml from 2.1 to 3.1.2. Everything still went fine and a jar file was built. But somehow it obviously wouldn't run anymore.

As soon as i set the "maven-jar-plugin" version back to 2.1 again, the problem was gone.

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

Defining private module functions in python

You can add an inner function:

def public(self, args):
   def private(self.root, data):
       if (self.root != None):
          pass #do something with data

Something like that if you really need that level of privacy.

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

Limiting floats to two decimal points

You can modify the output format:

>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95

Why XML-Serializable class need a parameterless constructor

The answer is: for no good reason whatsoever.

Contrary to its name, the XmlSerializer class is used not only for serialization, but also for deserialization. It performs certain checks on your class to make sure that it will work, and some of those checks are only pertinent to deserialization, but it performs them all anyway, because it does not know what you intend to do later on.

The check that your class fails to pass is one of the checks that are only pertinent to deserialization. Here is what happens:

  • During deserialization, the XmlSerializer class will need to create instances of your type.

  • In order to create an instance of a type, a constructor of that type needs to be invoked.

  • If you did not declare a constructor, the compiler has already supplied a default parameterless constructor, but if you did declare a constructor, then that's the only constructor available.

  • So, if the constructor that you declared accepts parameters, then the only way to instantiate your class is by invoking that constructor which accepts parameters.

  • However, XmlSerializer is not capable of invoking any constructor except a parameterless constructor, because it does not know what parameters to pass to constructors that accept parameters. So, it checks to see if your class has a parameterless constructor, and since it does not, it fails.

So, if the XmlSerializer class had been written in such a way as to only perform the checks pertinent to serialization, then your class would pass, because there is absolutely nothing about serialization that makes it necessary to have a parameterless constructor.

As others have already pointed out, the quick solution to your problem is to simply add a parameterless constructor. Unfortunately, it is also a dirty solution, because it means that you cannot have any readonly members initialized from constructor parameters.

In addition to all this, the XmlSerializer class could have been written in such a way as to allow even deserialization of classes without parameterless constructors. All it would take would be to make use of "The Factory Method Design Pattern" (Wikipedia). From the looks of it, Microsoft decided that this design pattern is far too advanced for DotNet programmers, who apparently should not be unnecessarily confused with such things. So, DotNet programmers should better stick to parameterless constructors, according to Microsoft.

Android: Creating a Circular TextView?

Much of the Answer here seems to be hacks to the shape drawable, while android in itself supports this with the shapes functionality. This is something that worked perfectly for me.You can do this in two ways

Using a fixed height and width, that would stay the same regardless of the text that you put it as shown below

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">

<solid android:color="@color/alpha_white" />

    <size android:width="25dp" android:height="25dp"/>

<stroke android:color="@color/color_primary" android:width="1dp"/>

</shape>

Using Padding which re-adjusts the shape regardless of the text in the textview it as shown below

<solid android:color="@color/alpha_white" />

<padding
    android:bottom="@dimen/semi_standard_margin"
    android:left="@dimen/semi_standard_margin"
    android:right="@dimen/semi_standard_margin"
    android:top="@dimen/semi_standard_margin" />

<stroke android:color="@color/color_primary" android:width="2dp"/>

semi_standard_margin = 4dp

Angular - Use pipes in services and components

You can use formatDate() to format the date in services or component ts. syntax:-

    formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string

import the formatDate() from common module like this,

    import { formatDate } from '@angular/common';

and just use it in the class like this ,

    formatDate(new Date(), 'MMMM dd yyyy', 'en');

You can also use the predefined format options provided by angular like this ,

    formatDate(new Date(), 'shortDate', 'en');

You can see all other predefined format options here ,

https://angular.io/api/common/DatePipe

Java Scanner String input

use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

Google Chrome form autofill and its yellow background

Solution here:

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

Changing cursor to waiting in javascript/jquery

A colleague suggested an approach that I find preferable to the chosen solution here. First, in CSS, add this rule:

body.waiting * {
    cursor: progress;
}

Then, to turn on the progress cursor, say:

$('body').addClass('waiting');

and to turn off the progress cursor, say:

$('body').removeClass('waiting');

The advantage of this approach is that when you turn off the progress cursor, whatever other cursors may have been defined in your CSS will be restored. If the CSS rule is not powerful enough in precedence to overrule other CSS rules, you can add an id to the body and to the rule, or use !important.

How to save DataFrame directly to Hive?

You could use Hortonworks spark-llap library like this

import com.hortonworks.hwc.HiveWarehouseSession

df.write
  .format("com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector")
  .mode("append")
  .option("table", "myDatabase.myTable")
  .save()

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

Does MySQL foreign_key_checks affect the entire database?

I had the same error when I tried to migrate Drupal database to a new local apache server(I am using XAMPP on Windows machine). Actually I don't know the meaning of this error, but after trying steps below, I imported the database without errors. Hope this could help:

Changing php.ini at C:\xampp\php\php.ini

max_execution_time = 600
max_input_time = 600
memory_limit = 1024M
post_max_size = 1024M

Changing my.ini at C:\xampp\mysql\bin\my.ini

max_allowed_packet = 1024M

getting a checkbox array value from POST

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

$invite = implode(', ', $_POST['invite']);
echo $invite;

Angular2 QuickStart npm start is not working correctly

Please make sure the names are correct, thus changing component in boot.js to components. enter image description here

Check if an element is present in an array

You can use the _contains function from the underscore.js library to achieve this:

if (_.contains(haystack, needle)) {
  console.log("Needle found.");
};

finding and replacing elements in a list

>>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for n, i in enumerate(a):
...   if i == 1:
...      a[n] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

Using PHP with Socket.io

If you want to use socket.io together with php this may be your answer!

project website:

elephant.io

they are also on github:

https://github.com/wisembly/elephant.io

Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.

example from the project website (communicate with websocket server through php)

php server

use ElephantIO\Client as Elephant;

$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->send(
    ElephantIOClient::TYPE_EVENT,
    null,
    null,
    json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();

echo 'tryin to send `bar` to the event `foo`';

socket io server

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.

How to make a promise from setTimeout

This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.

Code below serves as an explanation:

//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
    setTimeout (function(){
       console.log ('using callback:'); 
       let mockResponseData = '{"data": "something for callback"}'; 
       if (callback){
          callback (mockResponseData);
       }
    }, 2000);

} 

function b (dataJson) {
   let dataObject = JSON.parse (dataJson);
   console.log (dataObject.data);   
}

a (b);

//rewriting above code using Promise
//function c is asynchronous function
function c () {
   return new Promise(function (resolve, reject) {
     setTimeout (function(){
       console.log ('using promise:'); 
       let mockResponseData = '{"data": "something for promise"}'; 
       resolve(mockResponseData); 
    }, 2000);      
   }); 

}

c().then (b);

JsFiddle

How to reload current page without losing any form data?

You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

An explanation of the following error:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

Summary:

You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open(); inside of a loop, and forgot to run conn.close();. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:

protected void finalize() throws Throwable  
{  
    try { your_connection.close(); } 
    catch (SQLException e) { 
        e.printStackTrace();
    }
    super.finalize();  
}  

Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.

Run this SQL to see postgresql max connections allowed:

show max_connections;

The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.

Take a look at exactly who/what/when/where is holding open your connections:

SELECT * FROM pg_stat_activity;

The number of connections currently used is:

SELECT COUNT(*) from pg_stat_activity;

Debugging strategy

  1. You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.

  2. Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection, make sure every code line where you create a connection ends with a connection.close();

How to set the max_connections higher:

max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.

  1. First find your postgresql.conf file
  2. If you don't know where it is, query the database with the sql: SHOW config_file;
  3. Mine is in: /var/lib/pgsql/data/postgresql.conf
  4. Login as root and edit that file.
  5. Search for the string: "max_connections".
  6. You'll see a line that says max_connections=100.
  7. Set that number bigger, check the limit for your postgresql version.
  8. Restart the postgresql database for the changes to take effect.

What's the maximum max_connections?

Use this query:

select min_val, max_val from pg_settings where name='max_connections';

I get the value 8388607, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.

How to clone ArrayList and also clone its contents?

Java 8 provides a new way to call the copy constructor or clone method on the element dogs elegantly and compactly: Streams, lambdas and collectors.

Copy constructor:

List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());

The expression Dog::new is called a method reference. It creates a function object which calls a constructor on Dog which takes another dog as argument.

Clone method[1]:

List<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toList());

Getting an ArrayList as the result

Or, if you have to get an ArrayList back (in case you want to modify it later):

ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));

Update the list in place

If you don't need to keep the original content of the dogs list you can instead use the replaceAll method and update the list in place:

dogs.replaceAll(Dog::new);

All examples assume import static java.util.stream.Collectors.*;.


Collector for ArrayLists

The collector from the last example can be made into a util method. Since this is such a common thing to do I personally like it to be short and pretty. Like this:

ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

[1] Note on CloneNotSupportedException:

For this solution to work the clone method of Dog must not declare that it throws CloneNotSupportedException. The reason is that the argument to map is not allowed to throw any checked exceptions.

Like this:

    // Note: Method is public and returns Dog, not Object
    @Override
    public Dog clone() /* Note: No throws clause here */ { ...

This should not be a big problem however, since that is the best practice anyway. (Effectice Java for example gives this advice.)

Thanks to Gustavo for noting this.


PS:

If you find it prettier you can instead use the method reference syntax to do exactly the same thing:

List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How to export a Hive table into a CSV file?

The following script should work for you:

#!/bin/bash
hive -e "insert overwrite local directory '/LocalPath/'
row format delimited fields terminated by ','
select * from Mydatabase,Mytable limit 100"
cat /LocalPath/* > /LocalPath/table.csv

I used limit 100 to limit the size of data since I had a huge table, but you can delete it to export the entire table.

How do you write multiline strings in Go?

For me this is what I use if adding \n is not a problem.

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

Else you can use the raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.
             `

Priority queue in .Net

The following implementation of a PriorityQueue uses SortedSet from the System library.

using System;
using System.Collections.Generic;

namespace CDiggins
{
    interface IPriorityQueue<T, K> where K : IComparable<K>
    {
        bool Empty { get; }
        void Enqueue(T x, K key);
        void Dequeue();
        T Top { get; }
    }

    class PriorityQueue<T, K> : IPriorityQueue<T, K> where K : IComparable<K>
    {
        SortedSet<Tuple<T, K>> set;

        class Comparer : IComparer<Tuple<T, K>> {
            public int Compare(Tuple<T, K> x, Tuple<T, K> y) {
                return x.Item2.CompareTo(y.Item2);
            }
        }

        PriorityQueue() { set = new SortedSet<Tuple<T, K>>(new Comparer()); }
        public bool Empty { get { return set.Count == 0;  } }
        public void Enqueue(T x, K key) { set.Add(Tuple.Create(x, key)); }
        public void Dequeue() { set.Remove(set.Max); }
        public T Top { get { return set.Max.Item1; } }
    }
}

Android - java.lang.SecurityException: Permission Denial: starting Intent

In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.olddirectory"
            android:targetClass="com.ssimon.olddirectory.RecipeEditActivity"/>
    </Preference>
</PreferenceScreen> 

I needed the following instead:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.newdirectory"
            android:targetClass="com.ssimon.newdirectory.RecipeEditActivity"/>
</Preference>

Correcting the path names fixed the problem.

Set value for particular cell in pandas DataFrame using index

This is the only thing that worked for me!

df.loc['C', 'x'] = 10

Learn more about .loc here.

How to set cornerRadius for only top-left and top-right corner of a UIView?

Swift 4

extension UIView {

    func roundTop(radius:CGFloat = 5){
        self.clipsToBounds = true
        self.layer.cornerRadius = radius
        if #available(iOS 11.0, *) {
            self.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
        } else {
            // Fallback on earlier versions
        }
    }

    func roundBottom(radius:CGFloat = 5){
        self.clipsToBounds = true
        self.layer.cornerRadius = radius
        if #available(iOS 11.0, *) {
            self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
        } else {
            // Fallback on earlier versions
        }
    }
}

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

postgreSQL - psql \i : how to execute script in a given path

i did try this and its working in windows machine to run a sql file on a specific schema.

psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql

How do you run a .exe with parameters using vba's shell()?

The below code will help you to auto open the .exe file from excel...

Sub Auto_Open()


    Dim x As Variant
    Dim Path As String

    ' Set the Path variable equal to the path of your program's installation
    Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
    x = Shell(Path, vbNormalFocus)

End Sub

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

The model backing the <Database> context has changed since the database was created

I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:

  • Console Application "DataModel" that mainly using as assembly which contains all my code first entities, DbContext, Mirgations and generic repository. I have included to this project separate empty local database file (in DataModel/App_Data folder) to be able generate migrations from Package Manager Console.
  • WebApi, which references to DataModel project and uses local database file from WebApi/App_Data folder, that not included in project

I got this error when requested WebApi...

My environment:

  • Windows 8.1 x64
  • Visual Studio 2015 Professional with Update 1
  • all my projects targeted for .NET Framework 4.6.1
  • EntityFramework 6.1.3 from NuGet

Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :

  1. You should use only one version of EntityFramework Nuget package for all projects in your solution.
  2. Database, created by running sequentially all migration scripts should have the same structure/schema as you target database and correspond to entity model. Following 3 things must exactly correspond/reflect/match each other:
    • Your all migration script up to last
    • Current code first entity model state (DbContext, entities)
    • Target database
  3. Target database (mdf file) should be updated/correspond up to last migration script. Verify that "__MigrationHistory" table in your target database contains records for all migration scripts that you have, it means that all migration scripts was successfully applied to that database. I recommend you to use Visual Studio for generation correct code first entities and context that corresponds to your database, Project -> Add New Item -> ADO.NET Entity Data Model -> Code First from database: Of course, as an alternative, if you have no database you can write manually model (code first entities and context) and then generate initial migration and database.
  4. Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):

    <configuration>
      <connectionStrings>
        <add name="MyConnectionString" connectionString="...">
      </connectionStrings>
    <configuration>
    

    should be equal to parameter passed in constructor of your DbContext:

     public partial class MyDbContext : DbContext
     {
        public MyDbContext()
           : base("name=MyConnectionString"){}
        ...
    
  5. Before using Package Manager Console, make sure that you are using correct database for update or generate migration and needed project is set as startup project of solution. For connect to database it will use connection string from that .config file, which in project, that is set as startup project.
  6. And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.

       public class WebApiApplication : System.Web.HttpApplication
       {
           protected void Application_Start()
           {
               Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); 
               ...
    

    I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:

    1. remove manually bin, obj folders from your startup project (which generates/updates your database)
    2. build your startup project or better clean and rebuild all you solution.
    3. recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
    4. manually check whether generated db and __MirgationHistory corresponds to latest migration script.

Static class initializer in PHP

Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...

iOS Swift - Get the Current Local Time and Date Timestamp

in Swift 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

Best way to integrate Python and JavaScript?

Use Js2Py to translate JavaScript to Python, this is the only tool available :)

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

How do I include a JavaScript file in another JavaScript file?

I basically do it like the following, creating a new element and attach that to head:

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

In jQuery:

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // Script is now loaded and executed.
    // Put your dependent JavaScript code here.
});

how to get domain name from URL

Basically, what you want is:

google.com        -> google.com    -> google
www.google.com    -> google.com    -> google
google.co.uk      -> google.co.uk  -> google
www.google.co.uk  -> google.co.uk  -> google
www.google.org    -> google.org    -> google
www.google.org.uk -> google.org.uk -> google

Optional:

www.google.com     -> google.com    -> www.google
images.google.com  -> google.com    -> images.google
mail.yahoo.co.uk   -> yahoo.co.uk   -> mail.yahoo
mail.yahoo.com     -> yahoo.com     -> mail.yahoo
www.mail.yahoo.com -> yahoo.com     -> mail.yahoo

You don't need to construct an ever-changing regex as 99% of domains will be matched properly if you simply look at the 2nd last part of the name:

(co|com|gov|net|org)

If it is one of these, then you need to match 3 dots, else 2. Simple. Now, my regex wizardry is no match for that of some other SO'ers, so the best way I've found to achieve this is with some code, assuming you've already stripped off the path:

 my @d=split /\./,$domain;                # split the domain part into an array
 $c=@d;                                   # count how many parts
 $dest=$d[$c-2].'.'.$d[$c-1];             # use the last 2 parts
 if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
   $dest=$d[$c-3].'.'.$dest;              # if so, add a third part
 };
 print $dest;                             # show it

To just get the name, as per your question:

 my @d=split /\./,$domain;                # split the domain part into an array
 $c=@d;                                   # count how many parts
 if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
   $dest=$d[$c-3];                        # if so, give the third last
   $dest=$d[$c-4].'.'.$dest if ($c>3);    # optional bit
 } else {
   $dest=$d[$c-2];                        # else the second last
   $dest=$d[$c-3].'.'.$dest if ($c>2);    # optional bit 
 };
 print $dest;                             # show it

I like this approach because it's maintenance-free. Unless you want to validate that it's actually a legitimate domain, but that's kind of pointless because you're most likely only using this to process log files and an invalid domain wouldn't find its way in there in the first place.

If you'd like to match "unofficial" subdomains such as bozo.za.net, or bozo.au.uk, bozo.msf.ru just add (za|au|msf) to the regex.

I'd love to see someone do all of this using just a regex, I'm sure it's possible.

Can I use GDB to debug a running process?

You can attach to a running process with gdb -p PID.

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

Simple DateTime sql query

You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:

 SELECT *
   FROM TABLENAME
  WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'

See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:

Sql Server string to date conversion

Yarn: How to upgrade yarn version using terminal?

Not remembering how i've installed yarn the command that worked for me was:

yarn policies set-version

This command updates the current yarn version to the latest stable.

From the documentation:

Note that this command also is the preferred way to upgrade Yarn - it will work no matter how you originally installed it, which might sometimes prove difficult to figure out otherwise.

Reference

How to convert all text to lowercase in Vim

I had a similar issue, and I wanted to use ":%s/old/new/g", but ended up using two commands:

:0
gu:$

How to include Javascript file in Asp.Net page

If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:

<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>' 
type="text/javascript"></script>

What is the best way to remove the first element from an array?

An alternative ugly method:

   String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
   String[] k=Arrays.toString(a).split(", ",2)[1].split("]")[0].split(", ");

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Generate PDF from Swagger API documentation

You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.

If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).

  1. rest-api -> swagger.json : swagger-maven-plugin
  2. swagger.json -> Asciidoc : swagger2markup-maven-plugin
  3. Asciidoc -> PDF : asciidoctor-maven-plugin

Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.3</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>false</springmvc>
                <locations>some.package</locations>
                <basePath>/api</basePath>
                <info>
                    <title>Put your REST service's name here</title>
                    <description>Add some description</description>
                    <version>v1</version>
                </info>
                <swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
                <attachSwaggerArtifact>true</attachSwaggerArtifact>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <!-- fx process-classes phase -->
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>io.github.robwin</groupId>
    <artifactId>swagger2markup-maven-plugin</artifactId>
    <version>0.9.3</version>
    <configuration>
        <inputDirectory>${project.build.directory}/api</inputDirectory>
        <outputDirectory>${generated.asciidoc.directory}</outputDirectory>
        <!-- specify location to place asciidoc files -->
        <markupLanguage>asciidoc</markupLanguage>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-swagger</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.3</version>
    <dependencies>
        <dependency>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoctorj-pdf</artifactId>
            <version>1.5.0-alpha.11</version>
        </dependency>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
    <configuration>
        <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
        <!-- You will need to create an .adoc file. This is the input to this plugin -->
        <sourceDocumentName>swagger.adoc</sourceDocumentName>
        <attributes>
            <doctype>book</doctype>
            <toc>left</toc>
            <toclevels>2</toclevels>
            <generated>${generated.asciidoc.directory}</generated>
            <!-- this path is referenced in swagger.adoc file. The given file will simply 
                point to the previously create adoc files/assemble them. -->
        </attributes>
    </configuration>
    <executions>
        <execution>
            <id>asciidoc-to-html</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>html5</backend>
                <outputDirectory>${generated.html.directory}</outputDirectory>
                <!-- specify location to place html file -->
            </configuration>
        </execution>
        <execution>
            <id>asciidoc-to-pdf</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>pdf</backend>
                <outputDirectory>${generated.pdf.directory}</outputDirectory>
                <!-- specify location to place pdf file -->
            </configuration>
        </execution>
    </executions>
</plugin>

The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:

include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]

If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <warSourceDirectory>WebContent</warSourceDirectory>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <webResources>
            <resource>
                <directory>${generated.html.directory}</directory>
            <!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
            </resource>
            <resource>
                <directory>${generated.pdf.directory}</directory>
            <!-- Add swagger.html to WAR file, so as to make it available as static content. -->
            </resource>
        </webResources>
    </configuration>
</plugin>

The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.

Detect if range is empty

Found a solution from the comments I got.

Sub TestIsEmpty()
    If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
        MsgBox "Empty"
    Else
        MsgBox "Not Empty"
    End If
End Sub

Darkening an image with CSS (In any shape)

if you want only the background-image to be affected, you can use a linear gradient to do that, just like this:

  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(IMAGE_URL);

If you want it darker, make the alpha value higher, else you want it lighter, make alpha lower

jQueryUI modal dialog does not show close button (x)

You need to add quotes around the "ok". That is the text of the button. As it is, the button's text is currently empty (and hence not displayed) because it is trying to resolve the value of that variable.

Modal dialogs aren't meant to be closed in any fashion other than pressing the [ok] or [cancel] buttons. If you want the [x] in the right hand corner, set modal: false or just remove it altogether.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Get URL of ASP.Net Page in code-behind

If you want only the scheme and authority part of the request (protocol, host and port) use

Request.Url.GetLeftPart(UriPartial.Authority)

R: Print list to a text file

I solve this problem by mixing the solutions above.

sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()

I think it works well

Changing Shell Text Color (Windows)

Try to look at the following link: Python | change text color in shell

Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines

In general solution is to use ANSI codes while printing your string.

There is a solution that performs exactly what you need.

Travel/Hotel API's?

You could probably trying using Yahoo or Google's APIs. They are generic, but by specifying the right set of parameters, you could probably narrow down the results to just hotels. Check out Yahoo's Local Search API and Google's Local Search API

Disable a textbox using CSS

Another way is by making it readonly:

<input type="text" id="txtDis" readonly />

AngularJS : How to watch service variables?

Have a look at this plunker:: this is the simplest example i could think of

http://jsfiddle.net/HEdJF/

<div ng-app="myApp">
    <div ng-controller="FirstCtrl">
        <input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
        <br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
    </div>
    <hr>
    <div ng-controller="SecondCtrl">
        Input should also be here: {{Data.FirstName}}<!-- How do I automatically updated it here? -->
    </div>
</div>



// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
   return { FirstName: '' };
});

myApp.controller('FirstCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

myApp.controller('SecondCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

PDO error message?

Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:

$field1 = 'foo';
$field2 = 'bar';

$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);

$insert_QUERY->execute();

$databaseErrors = $insert_QUERY->errorInfo();

if( !empty($databaseErrors) ){  
    $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
    $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         

/* 
 $errorLogMsg will return something like: 
 error info:  
 Array(
  [0] => 42000
  [1] => 1064
  [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
 )
*/
} else {
    # no SQL errors.
}

<!--[if !IE]> not working

The Microsoft-recommended syntax for downlevel-revealed conditional “comments” is this:

<![if !IE]>
<link type="text/css" rel="stylesheet" href="/stylesheets/no-ie.css" />
<![endif]>

These aren’t comments, but they work properly.

Git fatal: protocol 'https' is not supported

You might be using a windows or linux computer where you have not logged into git hub so the certificate is not verified. From the sytem where you are getting error login to github with the credential then try to use the command it will work . Good Luck

Where does mysql store data?

In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data

ToList()-- does it create a new list?

Just stumble upon this old post and thought of adding my two cents. Generally, if I am in doubt, I quickly use the GetHashCode() method on any object to check the identities. So for above -

    public class MyObject
{
    public int SimpleInt { get; set; }
}


class Program
{

    public static void RunChangeList()
    {
        var objs = new List<MyObject>() { new MyObject() { SimpleInt = 0 } };
        Console.WriteLine("objs: {0}", objs.GetHashCode());
        Console.WriteLine("objs[0]: {0}", objs[0].GetHashCode());
        var whatInt = ChangeToList(objs);
        Console.WriteLine("whatInt: {0}", whatInt.GetHashCode());
    }

    public static int ChangeToList(List<MyObject> objects)
    {
        Console.WriteLine("objects: {0}", objects.GetHashCode());
        Console.WriteLine("objects[0]: {0}", objects[0].GetHashCode());
        var objectList = objects.ToList();
        Console.WriteLine("objectList: {0}", objectList.GetHashCode());
        Console.WriteLine("objectList[0]: {0}", objectList[0].GetHashCode());
        objectList[0].SimpleInt = 5;
        return objects[0].SimpleInt;

    }

    private static void Main(string[] args)
    {
        RunChangeList();
        Console.ReadLine();
    }

And answer on my machine -

  • objs: 45653674
  • objs[0]: 41149443
  • objects: 45653674
  • objects[0]: 41149443
  • objectList: 39785641
  • objectList[0]: 41149443
  • whatInt: 5

So essentially the object that list carries remain the same in above code. Hope the approach helps.

Automatically set appsettings.json for dev and release environments in asp.net core?

Update for .NET Core 3.0+

  1. You can use CreateDefaultBuilder which will automatically build and pass a configuration object to your startup class:

    WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    
    public class Startup
    {
        public Startup(IConfiguration configuration) // automatically injected
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        /* ... */
    }
    
  2. CreateDefaultBuilder automatically includes the appropriate appsettings.Environment.json file so add a separate appsettings file for each environment:

    appsettings.env.json

  3. Then set the ASPNETCORE_ENVIRONMENT environment variable when running / debugging

How to set Environment Variables

Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:

  • For Visual Studio go to Project > Properties > Debug > Environment Variables:

    Visual Studio - Environment Variables

  • For Visual Studio Code, edit .vscode/launch.json > env:

    Visual Studio Code > Launch Environment

  • Using Launch Settings, edit Properties/launchSettings.json > environmentVariables:

    Launch Settings

    Which can also be selected from the Toolbar in Visual Studio

    Launch Settings Dropdown

  • Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS

    Note: When an app is launched with dotnet run, launchSettings.json is read if available, and environmentVariables settings in launchSettings.json override environment variables.

How does Host.CreateDefaultBuilder work?

.NET Core 3.0 added Host.CreateDefaultBuilder under platform extensions which will provide a default initialization of IConfiguration which provides default configuration for the app in the following order:

  1. appsettings.json using the JSON configuration provider.
  2. appsettings.Environment.json using the JSON configuration provider. For example:
    • appsettings.Production.json or
    • appsettings.Development.json
  3. App secrets when the app runs in the Development environment.
  4. Environment variables using the Environment Variables configuration provider.
  5. Command-line arguments using the Command-line configuration provider.

Further Reading - MS Docs

Enum ToString with user friendly strings

Some other more primitive options that avoid classes/reference types:

  • Array method
  • Nested struct method

Array method

private struct PublishStatusses
{
    public static string[] Desc = {
        "Not Completed",
        "Completed",
        "Error"
    };

    public enum Id
    {
        NotCompleted = 0,
        Completed,
        Error
    };
}

Usage

string desc = PublishStatusses.Desc[(int)PublishStatusses.Id.Completed];

Nested struct method

private struct PublishStatusses
{
    public struct NotCompleted
    {
        public const int Id = 0;
        public const string Desc = "Not Completed";
    }

    public struct Completed
    {
        public const int Id = 1;
        public const string Desc = "Completed";
    }

    public struct Error
    {
        public const int Id = 2;
        public const string Desc = "Error";
    }            
}

Usage

int id = PublishStatusses.NotCompleted.Id;
string desc = PublishStatusses.NotCompleted.Desc;

Update (03/09/2018)

A hybrid of Extension Methods and the first technique above.

I prefer enums to be defined where they "belong" (closest to their source of origin and not in some common, global namespace).

namespace ViewModels
{
    public class RecordVM
    {
        //public enum Enum { Minutes, Hours }
        public struct Enum
        {
            public enum Id { Minutes, Hours }
            public static string[] Name = { "Minute(s)", "Hour(s)" };
        }
    }
}

The extension method seems suited for a common area, and the "localized" definition of the enum now makes the extension method more verbose.

namespace Common
{
    public static class EnumExtensions
    {
        public static string Name(this RecordVM.Enum.Id id)
        {
            return RecordVM.Enum.Name[(int)id];
        }
    }   
}

A usage example of the enum and it's extension method.

namespace Views
{
    public class RecordView 
    {
        private RecordDataFieldList<string, string> _fieldUnit;

        public RecordView()
        {
            _fieldUnit.List = new IdValueList<string, string>
            {            
                new ListItem<string>((int)RecordVM.Enum.Id.Minutes, RecordVM.Enum.Id.Minutes.Name()),
                new ListItem<string>((int)RecordVM.Enum.Id.Hours, RecordVM.Enum.Id.Hours.Name())
            };
        }

        private void Update()
        {    
            RecordVM.Enum.Id eId = DetermineUnit();

            _fieldUnit.Input.Text = _fieldUnit.List.SetSelected((int)eId).Value;
        }
    }
}

Note: I actually decided to eliminate the Enum wrapper (and Name array), since it's best that the name strings come from a resource (ie config file or DB) instead of being hard-coded, and because I ended up putting the extension method in the ViewModels namespace (just in a different, "CommonVM.cs" file). Plus the whole .Id thing becomes distracting and cumbersome.

namespace ViewModels
{
    public class RecordVM
    {
        public enum Enum { Minutes, Hours }
        //public struct Enum
        //{
        //    public enum Id { Minutes, Hours }
        //    public static string[] Name = { "Minute(s)", "Hour(s)" };
        //}
    }
}

CommonVM.cs

//namespace Common
namespace ViewModels
{
    public static class EnumExtensions
    {
        public static string Name(this RecordVM.Enum id)
        {
            //return RecordVM.Enum.Name[(int)id];
            switch (id)
            {
                case RecordVM.Enum.Minutes: return "Minute(s)";                    
                case RecordVM.Enum.Hours: return "Hour(s)";
                default: return null;
            }
        }
    }   
}

A usage example of the enum and it's extension method.

namespace Views
{
    public class RecordView 
    {
        private RecordDataFieldList<string, string> _fieldUnit

        public RecordView()
        {
            _fieldUnit.List = new IdValueList<string, string>
            {            
                new ListItem<string>((int)RecordVM.Enum.Id.Minutes, RecordVM.Enum.Id.Minutes.Name()),
                new ListItem<string>((int)RecordVM.Enum.Id.Hours, RecordVM.Enum.Id.Hours.Name())
            };
        }

        private void Update()
        {    
            RecordVM.Enum eId = DetermineUnit();

            _fieldUnit.Input.Text = _fieldUnit.List.SetSelected((int)eId).Value;
        }
    }
}

Node.js - Maximum call stack size exceeded

I thought of another approach using function references that limits call stack size without using setTimeout() (Node.js, v10.16.0):

testLoop.js

let counter = 0;
const max = 1000000000n  // 'n' signifies BigInteger
Error.stackTraceLimit = 100;

const A = () => {
  fp = B;
}

const B = () => {
  fp = A;
}

let fp = B;

const then = process.hrtime.bigint();

for(;;) {
  counter++;
  if (counter > max) {
    const now = process.hrtime.bigint();
    const nanos = now - then;

    console.log({ "runtime(sec)": Number(nanos) / (1000000000.0) })
    throw Error('exit')
  }
  fp()
  continue;
}

output:

$ node testLoop.js
{ 'runtime(sec)': 18.947094799 }
C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25
    throw Error('exit')
    ^

Error: exit
    at Object.<anonymous> (C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25:11)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

SQL Server command line backup statement

if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE returns the system date, of the system on which the database resides

CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE

execute this comman

    ALTER SESSION SET TIME_ZONE = '+3:0';

and it will provide you the same result.

Select records from today, this week, this month php mysql

Well, this solution will help you select only current month, current week and only today

SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;

For Weekly added posts:

WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())

For Monthly added posts:

MONTH(addedon_gm) = MONTH(NOW())

For Yearly added posts:

YEAR(addedon_gm) = YEAR(NOW())

you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Error: Jump to case label

Declaration of new variables in case statements is what causing problems. Enclosing all case statements in {} will limit the scope of newly declared variables to the currently executing case which solves the problem.

switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    

WMI "installed" query different from add/remove programs list?

All that Add/Remove Programs is really doing is reading this Registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Concatenate string with field value in MySQL

Here is a great answer to that:

SET sql_mode='PIPES_AS_CONCAT';

Find more here: https://stackoverflow.com/a/24777235/4120319

Here's the full SQL:

SET sql_mode='PIPES_AS_CONCAT';

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = 'category_id=' || tableOne.category_id;

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

WebView and Cookies on Android

I figured out what's going on.

When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.

You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.

  WebView webview = new WebView(this);      
  webview.setWebViewClient(new WebViewClient() {  
      @Override  
      public boolean shouldOverrideUrlLoading(WebView view, String url)  
      {  
        view.loadUrl(url); //this is controversial - see comments and other answers
        return true;  
      }  
    });                 
  setContentView(webview);      
  webview.loadUrl([MY URL]);

This fixes the problem.

How to use mongoimport to import csv

you will most likely need to authenticate if you're working in production sort of environments. You can use something like this to authenticate against the correct database with appropriate credentials.

mongoimport -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'

Stretch and scale CSS background

This is what I've made of it. In the stretch class, I simply changed the height to auto. This way your background picture has always got the same size as the width of the screen and the height will allways have the right size.

#background {
    width: 100%;
    height: 100%;
    position: absolute;
    margin-left: 0px;
    margin-top: 0px;
    z-index: 0;
}

.stretch {
    width:100%;
    height:auto;
}

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

SQL Server: How to check if CLR is enabled?

The correct result for me with SQL Server 2017:

USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO

RECONFIGURE
GO
EXEC sp_configure 'clr enabled'   -- make sure it took
GO

USE <DATABASE>
GO

EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO

ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;  

From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

HTML - Arabic Support

This is the answer that was required but everybody answered only part one of many.

  • Step 1 - You cannot have the multilingual characters in unicode document.. convert the document to UTF-8 document

advanced editors don't make it simple for you... go low level...
use notepad to save the document as meName.html & change the encoding
type to UTF-8

  • Step 2 - Mention in your html page that you are going to use such characters by

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    
  • Step 3 - When you put in some characters make sure your container tags have the following 2 properties set

    dir='rtl'
    lang='ar'
    
  • Step 4 - Get the characters from some specific tool\editor or online editor like i did with Arabic-Keyboard.org

example

<p dir="rtl" lang="ar" style="color:#e0e0e0;font-size:20px;">????? ??????? ??????</p>

NOTE: font type, font family, font face setting will have no effect on special characters

How can I get my Android device country code without using GPS?

If you wish to get the country code without asking for any permission, you can choose a tricky way.

The method simply uses an API to get the country code, and there aren't any third-party libraries to depend on. We can create one for us.

Here I have used Google Cloud Functions to write an API and it is so effortless.

Step 1: Create a Google Cloud Account, and set up billing (the free tier is enough)

Step 2: Create a cloud function to get the geo location

Copy this basic function to the code editor of index.js:

const cors = require('cors')

function _geolocation(req, res) {
  const data = {
    country_code: req.headers["x-appengine-country"],
    region: req.headers["x-appengine-region"],
    city: req.headers["x-appengine-city"],
    cityLatLong: req.headers["x-appengine-citylatlong"],
    userIP: req.headers["x-appengine-user-ip"]
  }

  res.json(data)
};

exports.geolocation = (req, res) => {
  const corsHandler = cors({ origin: true })

  return corsHandler(req, res, function() {
    return _geolocation(req, res);
  });
};

Also we need to copy the package.json definition:

{
  "name": "gfc-geolocation",
  "version": "0.0.1",
  "dependencies": {
    "cors": "^2.8.4"
  }
}

Step 3: finish, and get the URL similar to: "https://us-central1-geolocation-mods-sdde.cloudfunctions.net/geolocation"

Step 4: parse the JSON response and get the country code

The response will look like:

{
   "country": "IN",
   "region": "kl",
   "city": "kochi",
   "cityLatLong": "9.9312,76.2673",
   "userIP": "xx.xx.xx.xx"
}

Thanks and credits go to the Medium article: Free IP-based Geolocation with Google Cloud Functions

Remove carriage return in Unix

you can simply do this :

$ echo $(cat input) > output

vertical-align: middle doesn't work

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>

Correct way to populate an Array with a Range in Ruby

This is another way:

irb> [*1..10]

=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Letter Count on a string

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter
Counter('banana')

Of course, you can specify one element, e.g.

Counter('banana')['a']

Python equivalent of a given wget command

easy as py:

class Downloder():
    def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
        #threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
        if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
            return True
        else:
            return False


    def _wget_dl(self,url, destination, try_number, time_out):
        import subprocess
        command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
        try:
            download_state=subprocess.call(command)
        except Exception as e:
            print(e)
        #if download_state==0 => successfull download
        return download_state

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :

str.Trim().Length