Programs & Examples On #Ilmerge

ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and dlls alike. It comes with several options for controlling the processing and format of the output.

Merge DLL into EXE?

The command should be the following script:

ilmerge myExe.exe Dll1.dll /target:winexe /targetplatform:"v4,c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\" /out:merged.exe /out:merged.exe

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

What does the question mark in Java generics' type parameter mean?

Perhaps a contrived "real world" example would help.

At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish> and Bin<RecylcableRubbish>. The type system needs to make sure I can't put my HalfEatenSandwichRubbish into either of these types, but it can go into a general rubbish bin Bin<Rubbish>. If I wanted to talk about a Bin of Rubbish which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>.

(Note: ? extends does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)

Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.

How can I convert my Java program to an .exe file?

Java projects are exported as Jar executables. When you wanna do a .exe file of a java project, what you can do is 'convert' the JAR to EXE (i remark that i putted between quotes convert because isn't exactly this).

From intelij you gonna be able to generate only the jar

Try following the next example : https://www.genuinecoder.com/convert-java-jar-to-exe/

Find an element in DOM based on an attribute value

We can use attribute selector in DOM by using document.querySelector() and document.querySelectorAll() methods.

for yours:

document.querySelector("[myAttribute='aValue']");

and by using querySelectorAll():

document.querySelectorAll("[myAttribute='aValue']");

In querySelector() and querySelectorAll() methods we can select objects as we select in "CSS".

More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

You can install SideBarEnhancements plugin, which among other things will give you ability to open file in browser just by clicking F12.

To open exactly in Chrome, you will need to fix up “Side Bar.sublime-settings” file and set "default_browser" to be "chrome".

I also recommend to learn this video tutorial on Sublime Text 2.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

How to update record using Entity Framework 6?

I have the same problem when trying to update record using Attach() and then SaveChanges() combination, but I am using SQLite DB and its EF provider (the same code works in SQLServer DB without problem).

I found out, when your DB column has GUID (or UniqueIdentity) in SQLite and your model is nvarchar, SQLIte EF treats it as Binary(i.e., byte[]) by default. So when SQLite EF provider tries to convert GUID into the model (string in my case) it will fail as it will convert to byte[]. The fix is to tell the SQLite EF to treat GUID as TEXT (and therefore conversion is into strings, not byte[]) by defining "BinaryGUID=false;" in the connectionstring (or metadata, if you're using database first) like so:

  <connectionStrings>
    <add name="Entities" connectionString="metadata=res://savetyping...=System.Data.SQLite.EF6;provider connection string=&quot;data source=C:\...\db.sqlite3;Version=3;BinaryGUID=false;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Link to the solution that worked for me: How does the SQLite Entity Framework 6 provider handle Guids?

Dialog with transparent background in Android

if you want destroy dark background of dialog , use this

dialog.getWindow().setDimAmount(0);

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

How do I start my app on startup?

The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.

What is this weird colon-member (" : ") syntax in the constructor?

It's an initialization list for the constructor. Instead of default constructing x, y and z and then assigning them the values received in the parameters, those members will be initialized with those values right off the bat. This may not seem terribly useful for floats, but it can be quite a timesaver with custom classes that are expensive to construct.

Convert timestamp to date in Oracle SQL

This may not be the correct way to do it. But I have solved the problem using substring function.

Select max(start_ts), min(start_ts)from db where SUBSTR(start_ts, 0,9) ='13-may-2016'

using this I was able to retrieve the max and min timestamp.

Parsing JSON with Unix tools

For more complex JSON parsing I suggest using python jsonpath module (by Stefan Goessner) -

  1. Install it -

sudo easy_install -U jsonpath

  1. Use it -

Example file.json (from http://goessner.net/articles/JsonPath) -

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Parse it (extract all book titles with price < 10) -

$ cat file.json | python -c "import sys, json, jsonpath; print '\n'.join(jsonpath.jsonpath(json.load(sys.stdin), 'store.book[?(@.price < 10)].title'))"

Will output -

Sayings of the Century
Moby Dick

NOTE: The above command line does not include error checking. for full solution with error checking you should create small python script, and wrap the code with try-except.

Binding Combobox Using Dictionary as the Datasource

userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";

Switch statement equivalent in Windows batch file

It might be a bit late, but this does it:

set "case1=operation1"
set "case2=operation2"
set "case3=operation3"

setlocal EnableDelayedExpansion
!%switch%!
endlocal

%switch% gets replaced before line execution. Serious downsides:

  • You override the case variables
  • It needs DelayedExpansion

Might eventually be usefull in some cases.

How to create a Date in SQL Server given the Day, Month and Year as Integers

CREATE DATE USING MONTH YEAR IN SQL::

DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL

/**Region For Create Date**/
        DECLARE @FromDate DATE=NULL
        DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/

Detecting which UIButton was pressed in a UITableView

I always use tags.

You need to subclass the UITableviewCell and handle the button press from there.

How to make inactive content inside a div?

if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.

div.disabled{
  display: none;
}

How to randomize (or permute) a dataframe rowwise and columnwise?

Of course you can sample each row:

sapply (1:4, function (row) df1[row,]<<-sample(df1[row,]))

will shuffle the rows itself, so the number of 1's in each row doesn't change. Small changes and it also works great with columns, but this is a exercise for the reader :-P

How to set index.html as root file in Nginx?

The answer is to place the root dir to the location directives:

root   /srv/www/ducklington.org/public_html;

Escaping single quotes in JavaScript string for JavaScript evaluation

That worked for me.

string address=senderAddress.Replace("'", "\\'");

How to Calculate Execution Time of a Code Snippet in C++

boost::timer will probably give you as much accuracy as you'll need. It's nowhere near accurate enough to tell you how long a = a+1; will take, but I what reason would you have to time something that takes a couple nanoseconds?

Configure nginx with multiple locations with different root folders on subdomain

You need to use the alias directive for location /static:

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}

The nginx wiki explains the difference between root and alias better than I can:

Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.

Note that root and alias handle trailing slashes differently.

Query to get the names of all tables in SQL Server 2008 Database

another way, will also work on MySQL and PostgreSQL

select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'

Copying a rsa public key to clipboard

With PowerShell on Windows, you can use:

Get-Content ~/.ssh/id_rsa.pub | Set-Clipboard

Try-catch-finally-return clarification

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

PHP Fatal error: Using $this when not in object context

When you call the function in a static context, $this simply doesn't exist.

You would have to use this::xyz() instead.

To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?

What to do on TransactionTooLargeException

I got this in my syncadapter when trying to bulkInsert a large ContentValues[]. I decided to fix it as follows:

try {
    count = provider.bulkInsert(uri, contentValueses);
} catch (TransactionTooLarge e) {
    int half = contentValueses.length/2;
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, 0, half));
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, half, contentValueses.length));
}

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

TypeError: Router.use() requires middleware function but got a Object

You are missing router exports module and that is the reason why this error is present.

use module.exports = router; and that would work

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

As a matter of fact, if unsuccessful after following suggestions by marc_s, please keep in mind that a <security> element in server binding configuration (or lack thereof) in web.config on the server may cause this exception. For instance the server is expecting Message-level security and client is configured to None (or, if the server is not part of an Active Directory domain but the remote client host is).

Tip: In such cases the client app will most likely invoke the web service fine when executed directly on the server machine under administrative account in RDP session.

How to return 2 values from a Java method?

Here is the really simple and short solution with SimpleEntry:

AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);

String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();

Only uses Java built in functions and it comes with the type safty benefit.

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

How to use System.Net.HttpClient to post a complex type?

Note that if you are using a Portable Class Library, HttpClient will not have PostAsJsonAsync method. To post a content as JSON using a Portable Class Library, you will have to do this:

HttpClient client = new HttpClient();
HttpContent contentPost = new StringContent(argsAsJson, Encoding.UTF8, 
"application/json");

await client.PostAsync(new Uri(wsUrl), contentPost).ContinueWith(
(postTask) => postTask.Result.EnsureSuccessStatusCode());

c# open file with default application and parameters

If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.

On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:


You can do it without telling the full Acrobat path, like this:

Process myProcess = new Process();    
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();

If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:

myProcess.StartInfo.FileName = "Acrobat.exe";

You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.

Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows

How do I extract Month and Year in a MySQL date and compare them?

You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?

Array or List in Java. Which is faster?

Arrays recommended everywhere you may use them instead of list, especially in case if you know items count and size would not be changing.

See Oracle Java best practice: http://docs.oracle.com/cd/A97688_16/generic.903/bp/java.htm#1007056

Of course, if you need add and remove objects from collection many times easy use lists.

Where are Docker images stored on the host machine?

In Windows 2016, docker (DockerMsftProvider) uses the folder "windowsfilter" under docker root

>docker info
...
Storage Driver: windowsfilter
...
Docker Root Dir: C:\ProgramData\docker
...

It uses the "tmp" folder under docker root to download the files and it deletes the files after extracting the downloaded files to "windowsfilter" folder.

Get the Highlighted/Selected text

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)

Display / print all rows of a tibble (tbl_df)

The tibble vignette has an updated way to change its default printing behavior:

You can control the default appearance with options:

options(tibble.print_max = n, tibble.print_min = m): if there are more than n rows, print only the first m rows. Use options(tibble.print_max = Inf) to always show all rows.

options(tibble.width = Inf) will always print all columns, regardless of the width of the screen.

examples

This will always print all rows:

options(tibble.print_max = Inf)

This will not actually limit the printing to 50 lines:

options(tibble.print_max = 50)

But this will restrict printing to 50 lines:

options(tibble.print_max = 50, tibble.print_min = 50)

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

How can I get Apache gzip compression to work?

In my case i have used following code for enabling gzip compression in apache web server.

  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.

How do I put a clear button inside my HTML text input box like the iPhone does?

You can't actually put it inside the text box unfortunately, only make it look like its inside it, which unfortunately means some css is needed :P

Theory is wrap the input in a div, take all the borders and backgrounds off the input, then style the div up to look like the box. Then, drop in your button after the input box in the code and the jobs a good'un.

Once you've got it to work anyway ;)

How to find pg_config path

I recommend that you try to use Postgres.app. (http://postgresapp.com) This way you can easily turn Postgres on and off on your Mac. Once you do, add the path to Postgres to your .profile file by appending the following:

PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"

Only after you added Postgres to your path you can try to install psycopg2 either within a virtual environment (using pip) or into your global site packages.

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

How to get the row number from a datatable?

You have two options here.

  1. You can create your own index counter and increment it
  2. Rather than using a foreach loop, you can use a for loop

The individual row simply represents data, so it will not know what row it is located in.

How to remove numbers from a string?

You're remarkably close.

Here's the code you wrote in the question:

questionText.replace(/[0-9]/g, '');

The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.

However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:

questionText = questionText.replace(/[0-9]/g, '');

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Java Date - Insert into database

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

RegEx to parse or validate Base64 data

The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex

which is in the current version looks like:

module.exports = function (opts) {
  opts = opts || {};
  var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';

  return opts.exact ? new RegExp('(?:^' + regex + '$)') :
                    new RegExp('(?:^|\\s)' + regex, 'g');
};

How can I output a UTF-8 CSV in PHP that Excel will read properly?

//convert UTF-8 file without BOM to UTF-16LE for excel on mac
$fileUtf8String = file_get_contents("file.ext");
file_put_contents("file.ext", "\xFF\xFE" . mb_convert_encoding($fileUtf8String, "UTF-16LE", "UTF-8"));

How to configure PostgreSQL to accept all incoming connections

Just use 0.0.0.0/0.

host    all             all             0.0.0.0/0            md5

Make sure the listen_addresses in postgresql.conf (or ALTER SYSTEM SET) allows incoming connections on all available IP interfaces.

listen_addresses = '*'

After the changes you have to reload the configuration. One way to do this is execute this SELECT as a superuser.

SELECT pg_reload_conf();

Note: to change listen_addresses, a reload is not enough, and you have to restart the server.

Regex pattern including all special characters

Try this. It works on C# it should work on java also. If you want to exclude spaces just add \s in there @"[^\p{L}\p{Nd}]+"

How to remove listview all items

use any one of the bellow options which suites your requirement

listview.removeViews(1,listview.getChildCount());

or

listview.removeViewInLayout(your view);

Error You must specify a region when running command aws ecs list-container-instances

"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.

For the CLI, either set the AWS_DEFAULT_REGION environment variable. e.g.

export AWS_DEFAULT_REGION=us-east-1

or add it into the command (you will need this every time you use a region-specific command)

AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default

or set it in the CLI configuration file: ~/.aws/config

[default]
region=us-east-1

or pass/override it with the CLI call:

aws ecs list-container-instances --cluster default --region us-east-1

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

When is assembly faster than C?

This is very hard to answer specifically, because the question is very unspecific: what exactly is a "modern compiler"?

Pretty much any manual assembler optimization could in theory be done by a compiler as well - Whether it actually is done cannot be said in general, only about a specific version of a specific compiler. Many probably require so much effort to determine whether they can be applied without side effects in a particular context that compiler writers don't bother with them.

What's the UIScrollView contentInset property for?

It sets the distance of the inset between the content view and the enclosing scroll view.

Obj-C

aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);

Swift 5.0

aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)

Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?


   (cH = contentSize.height; cW = contentSize.width)

The scroll view encloses the content view plus whatever padding is provided by the specified content insets.

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

How to view table contents in Mysql Workbench GUI?

To get the convenient list of tables on the left panel below each database you have to click the tiny icon on the top right of the left panel. At least in MySQL Workbench 6.3 CE on Win7 this worked to get the full list of tables.

See my screenshot to explain.enter image description here

Sadly this icon not even has a mouseover title attribute, so it was a lucky guess that I found it.

Clearing coverage highlighting in Eclipse

I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: enter image description here

Check if string contains a value in array

    $message = "This is test message that contain filter world test3";

    $filterWords = array('test1', 'test2', 'test3');

    $messageAfterFilter =  str_replace($filterWords, '',$message);

    if( strlen($messageAfterFilter) != strlen($message) )
        echo 'message is filtered';
    else
        echo 'not filtered';

How do you run a single test/spec file in RSpec?

Ruby 1.9.2 and Rails 3 have an easy way to run one spec file:

  ruby -I spec spec/models/user_spec.rb

Explanation:

  • ruby command tends to be faster than the rake command
  • -I spec means "include the 'spec' directory when looking for files"
  • spec/models/user_spec.rb is the file we want to run.

How to import functions from different js file in a Vue+webpack+vue-loader project

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>

Counting unique / distinct values by group in a data frame

You can just use the built-in R functions tapply with length

tapply(myvec$order_no, myvec$name, FUN = function(x) length(unique(x)))

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

Adding and removing style attribute from div with jquery

Remove style attribute from div using J query:

$("#TableDiv").removeAttr("style");

Add style to div using J query:

$("#TableDiv").attr("style", "display: none;");

Add style using html:

<div class="row" id="TableDiv" style="display: none;">
</div>

Hope it will helpful :)

Node Sass couldn't find a binding for your current environment

For me it was the maven-war-plugin that applied filters to the files and corrupted the woff files.

<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
    <webResources>
        <resource>
            <directory>dist</directory>
            <filtering>true</filtering>
        </resource>
    </webResources>
</configuration>

Remove <filtering>true</filtering>

Or if you need filtering you can do something like this:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <webResources>
            <resource>
                <directory>dist</directory>
                <excludes>
                    <exclude>assets/**/*</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>dist</directory>
                <includes>
                    <include>assets/**/*</include>
                </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>

How do I Search/Find and Replace in a standard string?

My templatized inline in-place find-and-replace:

template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
    int num=0;
    typename T::size_t fLen = find.size();
    typename T::size_t rLen = replace.size();
    for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
        num++;
        source.replace(pos, fLen, replace);
    }
    return num;
}

It returns a count of the number of items substituted (for use if you want to successively run this, etc). To use it:

std::string str = "one two three";
int n = findAndReplace(str, "one", "1");

Angular JS POST request not sending JSON data

I have tried your example and it works just fine:

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/test',
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    data: {application: app, from: d1, to: d2}
});

Output:

Content-Length:91
Content-Type:application/json
Host:localhost:1234
Origin:http://localhost:1234
Referer:http://localhost:1234/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{"application":"AirFare","from":"2013-10-10T11:47:50.681Z","to":"2013-10-10T11:47:50.681Z"}

Are you using the latest version of AngularJS?

Why can't DateTime.Parse parse UTC date

You need to specify the format:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);

How to debug in Android Studio using adb over WiFi

if adb command not found.

-----------------------------

Install homebrew

 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Install adb

brew install android-platform-tools

---------------------------

Connect the device now.

  • Enable USB debugging in the Android device
  • Enable Allow ADB debugging in charge only mode
  • Connect the device to the computer via a USB port.

Start using adb

adb devices

List of devices attached
DUM0219A21000314 device

the first item is device id.

adb -s <device id> tcpip 5555

adb -s DUM0219A21000314 tcpip 5555

restarting in TCP mode port: 5555

Find the local IP address of your Android device. You can find this information in the quick settings drop-down menu by pressing / long pressing the WiFi icon and then clicking on the WiFi network you are connected to.

adb connect <IP address>:5555
adb connect 192.168.2.2:5555

connected to 192.168.2.2:5555

Don't forget! Allow ADB debugging in charge only mode enabled before connecting the device

How to configure Fiddler to listen to localhost?

Replace localhost by lvh.me in your URL

For example if you had http://localhost:24448/HomePage.aspx

Change it to http://lvh.me:24448/HomePage.aspx

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

Using pip behind a proxy with CNTLM

for windows; set your proxy in command prompt as
set HTTP_PROXY=domain\username:password@myproxy:myproxyport

example:
set http_proxy=IND\namit.kewat:[email protected]:8880

Maximum number of threads in a .NET app?

You can test it by using this snipped code:

private static void Main(string[] args)
{
   int threadCount = 0;
   try
   {
      for (int i = 0; i < int.MaxValue; i ++)
      {
         new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
         threadCount ++;
      }
   }
   catch
   {
      Console.WriteLine(threadCount);
      Console.ReadKey(true);
   }
}

Beware of 32-bit and 64-bit mode of application.

JavaScript chop/slice/trim off last character in string

In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().

I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:

var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";

To remove the last comma I did the following:

str = str.slice(0, -5) + str.substr(-4);

Squash my last X commits together using Git

First I find out the number of commits between my feature branch and current master branch by

git checkout master
git rev-list master.. --count

Then, I create another branch based out my-feature branch, keep my-feature branch untouched.

Lastly, I run

git checkout my-feature
git checkout -b my-rebased-feature
git checkout master
git checkout my-rebased-feature
git rebase master
git rebase head^x -i
// fixup/pick/rewrite
git push origin my-rebased-feature -f // force, if my-rebased-feature was ever pushed, otherwise no need for -f flag
// make a PR with clean history, delete both my-feature and my-rebased-feature after merge

Hope it helps, thanks.

How to fill in proxy information in cntlm config file?

For me just using cntlm -H wasn't generating the right hash, but it does with the command below providing the user name.

If you need to generate a new password hash for cntlm, because you have change it or you've been forced to update it, you can just type the below command and update your cntlm.conf configuration file with the output:

$ cntlm -u test -H
Password: 
PassLM          D2AABAF8828482D5552C4BCA4AEBFB11
PassNT          83AC305A1582F064C469755F04AE5C0A
PassNTLMv2      4B80D9370D353EE006D714E39715A5CB    # Only for user 'test', domain ''

How to destroy an object?

May be in a situation where you are creating a new mysqli object.

$MyConnection = new mysqli($hn, $un, $pw, $db);

but even after you close the object

$MyConnection->close();

if you will use print_r() to check the contents of $MyConnection, you will get an error as below:

Error:
mysqli Object

Warning: print_r(): Property access is not allowed yet in /path/to/program on line ..
( [affected_rows] => [client_info] => [client_version] =>.................)

in which case you can't use unlink() because unlink() will require a path name string but in this case $MyConnection is an Object.

So you have another choice of setting its value to null:

$MyConnection = null;

now things go right, as you have expected. You don't have any content inside the variable $MyConnection as well as you already cleaned up the mysqli Object.

It's a recommended practice to close the Object before setting the value of your variable to null.

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

Running a cron every 30 seconds

I just had a similar task to do and use the following approach :

nohup watch -n30 "kill -3 NODE_PID" &

I needed to have a periodic kill -3 (to get the stack trace of a program) every 30 seconds for several hours.

nohup ... & 

This is here to be sure that I don't lose the execution of watch if I loose the shell (network issue, windows crash etc...)

Regex to match only uppercase "words" with some exceptions

Why do you need to do this in one monster-regex? You can use actual code to implement some of these rules, and doing so would be much easier to modify if those requirements change later.

For example:

if(/^[A-Z0-9\s]*$/)
    # sentence is all uppercase, so just fail out
    return 0;

# Carry on with matching uppercase terms

Programmatically scroll a UIScrollView

Another way is

scrollView.contentOffset = CGPointMake(x,y);

How to clear Facebook Sharer cache?

I thing these two links have a wide discussion on your problem related stuff. fb:ref clear cashes by calling

fbml.refreshRefUrl

like this

<tt>fbml.refreshRefUrl("http://www.mysite.com/someurl.php")

You can study the related stuff from here fb:ref. I hope it will work for you

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

How to create CSV Excel file C#?

Slightly different version I wrote using reflection for my needs. I had to export a list of objects to csv. In case someone wants to use it for future.

public class CsvExport<T> where T: class
    {
        public List<T> Objects;

        public CsvExport(List<T> objects)
        {
            Objects = objects;
        }

        public string Export()
        {
            return Export(true);
        }

        public string Export(bool includeHeaderLine)
        {

            StringBuilder sb = new StringBuilder();
            //Get properties using reflection.
            IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

            if (includeHeaderLine)
            {
                //add header line.
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(propertyInfo.Name).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            //add value for each property.
            foreach (T obj in Objects)
            {               
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            return sb.ToString();
        }

        //export to a file.
        public void ExportToFile(string path)
        {
            File.WriteAllText(path, Export());
        }

        //export as binary data.
        public byte[] ExportToBytes()
        {
            return Encoding.UTF8.GetBytes(Export());
        }

        //get the csv value for field.
        private string MakeValueCsvFriendly(object value)
        {
            if (value == null) return "";
            if (value is Nullable && ((INullable)value).IsNull) return "";

            if (value is DateTime)
            {
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                    return ((DateTime)value).ToString("yyyy-MM-dd");
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            string output = value.ToString();

            if (output.Contains(",") || output.Contains("\""))
                output = '"' + output.Replace("\"", "\"\"") + '"';

            return output;

        }
    }

Usage sample : (updated per comment)

CsvExport<BusinessObject> csv= new CsvExport<BusinessObject>(GetBusinessObjectList());
Response.Write(csv.Export());

How do I edit a file after I shell to a Docker container?

If you use Windows container and you want change any file, you can get and use Vim in Powershell console easily.

To shelled to the Windows Docker container with PowerShell:

docker exec -it <name> powershell

  • First install Chocolatey package manager

    Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression;

  • Install Vim

    choco install vim

  • Refresh ENVIRONMENTAL VARIABLE You can just exit and shell back to the container

  • Go to file location and Vim it vim file.txt

Better way to call javascript function in a tag

Neither is good.

Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like

$('#the-element').click(function () { /* perform action here */ });

in a separate <script> block.

The advantage of this is that it

  1. Separates markup and behaviour in the same way that CSS separates markup and style
  2. Centralises configuration (this is somewhat a corollary of 1).
  3. Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax

Furthermore, it degrades gracefully (but so would using the onclick event) since you can provide the link tags with a href in case the user doesn’t have JavaScript enabled.

Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ ! -z "$var" ] && [ -e "$var" ]; then
      # something ...
fi

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

c# .net change label text

When I had this problem I could see only a part of my text and this is the solution for that:

Be sure to set the AutoSize property to true.

output.AutoSize = true;

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

How to fix Git error: object file is empty?

I had a similar problem. My laptop ran out of battery during a git operation. Boo.

I didn't have any backups. (N.B. Ubuntu One is not a backup solution for git; it will helpfully overwrite your sane repository with your corrupted one.)

To the git wizards, if this was a bad way to fix it, please leave a comment. It did, however, work for me... at least temporarily.

Step 1: Make a backup of .git (in fact I do this in between every step that changes something, but with a new copy-to name, e.g. .git-old-1, .git-old-2, etc.):

cp -a .git .git-old

Step 2: Run git fsck --full

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
error: object file .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e is empty
fatal: loose object 8b61d0135d3195966b443f6c73fb68466264c68e (stored in .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e) is corrupt

Step 3: Remove the empty file. I figured what the heck; its blank anyway.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e 
rm: remove write-protected regular empty file `.git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e'? y

Step 3: Run git fsck again. Continue deleting the empty files. You can also cd into the .git directory and run find . -type f -empty -delete -print to remove all empty files. Eventually git started telling me it was actually doing something with the object directories:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: object file .git/objects/e0/cbccee33aea970f4887194047141f79a363636 is empty
fatal: loose object e0cbccee33aea970f4887194047141f79a363636 (stored in .git/objects/e0/cbccee33aea970f4887194047141f79a363636) is corrupt

Step 4: After deleting all of the empty files, I eventually came to git fsck actually running:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: HEAD: invalid sha1 pointer af9fc0c5939eee40f6be2ed66381d74ec2be895f
error: refs/heads/master does not point to a valid object!
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 5: Try git reflog. Fail because my HEAD is broken.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reflog
fatal: bad object HEAD

Step 6: Google. Find this. Manually get the last two lines of the reflog:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ tail -n 2 .git/logs/refs/heads/master
f2d4c4868ec7719317a8fce9dc18c4f2e00ede04 9f0abf890b113a287e10d56b66dbab66adc1662d Nathan VanHoudnos <[email protected]> 1347306977 -0400  commit: up to p. 24, including correcting spelling of my name
9f0abf890b113a287e10d56b66dbab66adc1662d af9fc0c5939eee40f6be2ed66381d74ec2be895f Nathan VanHoudnos <[email protected]> 1347358589 -0400  commit: fixed up to page 28

Step 7: Note that from Step 6 we learned that the HEAD is currently pointing to the very last commit. So let's try to just look at the parent commit:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git show 9f0abf890b113a287e10d56b66dbab66adc1662d
commit 9f0abf890b113a287e10d56b66dbab66adc1662d
Author: Nathan VanHoudnos <nathanvan@XXXXXX>
Date:   Mon Sep 10 15:56:17 2012 -0400

    up to p. 24, including correcting spelling of my name

diff --git a/tex/MCMC-in-IRT.tex b/tex/MCMC-in-IRT.tex
index 86e67a1..b860686 100644
--- a/tex/MCMC-in-IRT.tex
+++ b/tex/MCMC-in-IRT.tex

It worked!

Step 8: So now we need to point HEAD to 9f0abf890b113a287e10d56b66dbab66adc1662d.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git update-ref HEAD 9f0abf890b113a287e10d56b66dbab66adc1662d

Which didn't complain.

Step 9: See what fsck says:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 10: The invalid sha1 pointer in cache-tree seemed like it was from a (now outdated) index file (source). So I killed it and reset the repo.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/index
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reset
Unstaged changes after reset:
M   tex/MCMC-in-IRT.tex
M   tex/recipe-example/build-example-plots.R
M   tex/recipe-example/build-failure-plots.R

Step 11: Looking at the fsck again...

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a

The dangling blobs are not errors. I'm not concerned with master.u1conflict, and now that it is working I don't want to touch it anymore!

Step 12: Catching up with my local edits:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   tex/MCMC-in-IRT.tex
#   modified:   tex/recipe-example/build-example-plots.R
#   modified:   tex/recipe-example/build-failure-plots.R
#
< ... snip ... >
no changes added to commit (use "git add" and/or "git commit -a")


nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "recovering from the git fiasco"
[master 7922876] recovering from the git fiasco
 3 files changed, 12 insertions(+), 94 deletions(-)

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git add tex/sept2012_code/example-code-testing.R
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "adding in the example code"
[master 385c023] adding in the example code
 1 file changed, 331 insertions(+)
 create mode 100644 tex/sept2012_code/example-code-testing.R

So hopefully that can be of some use to people in the future. I'm glad it worked.

Changing Fonts Size in Matlab Plots

If you want to change font size for all the text in a figure, you can use findall to find all text handles, after which it's easy:

figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')

Combine Regexp?

Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Yes, WebBrowser control uses whatever version of IE you have installed. This means of course that if you run your application on a machine with IE 8 then the IE 9 features you depend on will not be available.

ActiveRecord: size vs count

tl;dr

  • If you know you won't be needing the data use count.
  • If you know you will use or have used the data use length.
  • If you don't know what you are doing, use size...

count

Resolves to sending a Select count(*)... query to the DB. The way to go if you don't need the data, but just the count.

Example: count of new messages, total elements when only a page is going to be displayed, etc.

length

Loads the required data, i.e. the query as required, and then just counts it. The way to go if you are using the data.

Example: Summary of a fully loaded table, titles of displayed data, etc.

size

It checks if the data was loaded (i.e. already in rails) if so, then just count it, otherwise it calls count. (plus the pitfalls, already mentioned in other entries).

def size
  loaded? ? @records.length : count(:all)
end

What's the problem?

That you might be hitting the DB twice if you don't do it in the right order (e.g. if you render the number of elements in a table on top of the rendered table, there will be effectively 2 calls sent to the DB).

Set default option in mat-select

This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.

In the "ngOnInit" lifecycle hook

1) Get the object you want to set as the default from your array or object literal

const countryDefault = this.countries.find(c => c.number === '826');

Here I am grabbing the United Kingdom object from my countries array.

2) Then set the formsbuilder object (the mat-select) with the default value.

this.addressForm.get('country').setValue(countryDefault.name);

3) Lastly...set the bound value property. In my case I want the name value.

<mat-select formControlName="country">
   <mat-option *ngFor="let country of countries" [value]="country.name" >
          {{country.name}}

  </mat-option>
</mat-select>

Works like a charm. I hope it helps

onclick event pass <li> id or value

Try like this...

<script>
function getPaging(str) {
  $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>

or unobtrusively

$(function() {
  $("li").on("click",function() {
    showLoader();
    $("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
  });
});

using just

<li id="1">1</li>
<li id="2">2</li>

Get text from DataGridView selected cells

the Best of both worlds.....

Private Sub tsbSendNewsLetter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSendNewsLetter.Click
        Dim tmpstr As String = ""
        Dim cnt As Integer = 0
        Dim virgin As Boolean = True
        For cnt = 0 To (dgvDetails.Rows.Count - 1)
            If Not dgvContacts.Rows(cnt).Cells(9).Value.ToString() Is Nothing Then
                If Not dgvContacts.Rows(cnt).Cells(9).Value.ToString().Length = 0 Then
                    If Not virgin Then
                        tmpstr += ", "
                    End If
                    tmpstr += dgvContacts.Rows(cnt).Cells(9).Value.ToString()
                    virgin = False
                    'MsgBox(tmpstr)
                End If
            End If
        Next
        Dim email As New qkuantusMailer()
        email.txtMailTo.Text = tmpstr
        email.Show()
    End Sub

Most efficient way to find smallest of 3 numbers Java?

Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, determines the smallest value and displays the result.

Clear terminal in Python

If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.

Without knowing more of your problem, your solution seems good enough.

Difference Between ViewResult() and ActionResult()

ActionResult is an abstract class that can have several subtypes.

ActionResult Subtypes

  • ViewResult - Renders a specifed view to the response stream

  • PartialViewResult - Renders a specifed partial view to the response stream

  • EmptyResult - An empty response is returned

  • RedirectResult - Performs an HTTP redirection to a specifed URL

  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

  • JsonResult - Serializes a given ViewData object to JSON format

  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

  • ContentResult - Writes content to the response stream without requiring a view

  • FileContentResult - Returns a file to the client

  • FileStreamResult - Returns a file to the client, which is provided by a Stream

  • FilePathResult - Returns a file to the client

Resources

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

Plotting power spectrum in python

Numpy has a convenience function, np.fft.fftfreq to compute the frequencies associated with FFT components:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

enter image description here

Note that the largest frequency you see in your case is not 30 Hz, but

In [7]: max(freqs)
Out[7]: 14.950166112956811

You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).

syntax error when using command line in python

Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.

Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

Can I escape html special chars in javascript?

It was interesting to find a better solution:

var escapeHTML = function(unsafe) {
  return unsafe.replace(/[&<"']/g, function(m) {
    switch (m) {
      case '&':
        return '&amp;';
      case '<':
        return '&lt;';
      case '"':
        return '&quot;';
      default:
        return '&#039;';
    }
  });
};

I do not parse > because it does not break XML/HTML code in the result.

Here are the benchmarks: http://jsperf.com/regexpairs Also, I created a universal escape function: http://jsperf.com/regexpairs2

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

How to add text to an existing div with jquery

we can do it in more easy way like by adding a function on button and on click we call that function for append.

<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div> 
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>

jQuery: Wait/Delay 1 second without executing code

JavaScript setTimeout is a very good solution:

function funcx()
   {
   // your code here
   // break out here if needed
   setTimeout(funcx, 3000);
   }

funcx();

The delay function in jQuery is mostly used for delaying animations in a jQuery animation queue.

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Show which git tag you are on?

This worked for me git describe --tags --abbrev=0

Edit 2020: As mentioned by some of the comments below, this might, or might not work for you, so be careful!

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

How unique is UUID?

For UUID4 I make it that there are approximately as many IDs as there are grains of sand in a cube-shaped box with sides 360,000km long. That's a box with sides ~2 1/2 times longer than Jupiter's diameter.

Working so someone can tell me if I've messed up units:

  • volume of grain of sand 0.00947mm^3 (Guardian)
  • UUID4 has 122 random bits -> 5.3e36 possible values (wikipedia)
  • volume of that many grains of sand = 5.0191e34 mm^3 or 5.0191e+25m^3
  • side length of cubic box with that volume = 3.69E8m or 369,000km
  • diameter of Jupiter: 139,820km (google)

How to compare strings in Bash

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.

Here are some examples in Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

    if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

     if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

     if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

     if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

     if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

     if [ "$a" = "$b" ] ;then

Enjoy.

How do I use StringUtils in Java?

StringUtils is in org.apache.commons.lang.* not in java.lang.*. Most importantly learn to read javadoc file. All java programmers after learning basic java learn to read javadoc, execute tests from public projects, use those jars in their projects.

If you are working on eclipse or netbeans you can make a directory (folder) called lib in your project (from within the IDE) and copy the downloaded jar from hard disk and paste it in that directory from eclipse or netbeans. Next you have to add it to your project.

E.g in case of eclipse from Project->Properties select Java Build Path -> Add Jars, point to the jar you copied earlier. In your case it might be commons-lang-version.jar.

After this step whenever you add above import in a java file, those libraries will be available on your project (in case of eclipse or netbeans).

From where do you get the jar for commons-lang? Root directory of any apache commons is http://commons.apache.org/ And for commons-lang it is http://commons.apache.org/lang/

Some of these libraries contain User Guide and other help to get you started, but javadoc is the ultimate guide for any java programmer.

It is right time you asked about this library, because you should never re-invent the wheel. Use apache commons and other well tested libraries whenever possible. By using those libraries you omit some common human errors and even test those libraries (using is testing). Sometimes in future when using this library, you may even write some modifications or addition to this library. If you contribute back, the world benefits.

Most common use of StringUtils is in web projects (when you want to check for blank or null strings, checking if a string is number, splitting strings with some token). StringUtils helps to get rid of those nasty NumberFormat and Null exceptions. But StringUtils can be used anywhere String is used.

Convert an integer to a byte array

Adding this option for dealing with basic uint8 to byte[] conversion

foo := 255 // 1 - 255
ufoo := uint16(foo) 
far := []byte{0,0}
binary.LittleEndian.PutUint16(far, ufoo)
bar := int(far[0]) // back to int
fmt.Println("foo, far, bar : ",foo,far,bar)

output : foo, far, bar : 255 [255 0] 255

How to insert a newline in front of a pattern?

in sed you can reference groups in your pattern with "\1", "\2", .... so if the pattern you're looking for is "PATTERN", and you want to insert "BEFORE" in front of it, you can use, sans escaping

sed 's/(PATTERN)/BEFORE\1/g'

i.e.

  sed 's/\(PATTERN\)/BEFORE\1/g'

'const int' vs. 'int const' as function parameters in C++ and C

They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:

int getInt() const;

It changes the this pointer in the function from Foo * const to Foo const * const. See here.

How do I check if the mouse is over an element in jQuery?

$(document).hover(function(e) {
    alert(e.type === 'mouseenter' ? 'enter' : 'leave');
});

FIDDLE

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

The PropertiesPlaceholderConfigurer bean has an alternative property called "propertiesArray". Use this instead of the "properties" property, and configure it with an <array> of property references.

iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

HttpClient won't import in Android Studio

Error:(30, 0) Gradle DSL method not found: 'classpath()' Possible causes:

  • The project 'cid' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0). Upgrade plugin to version 2.3.3 and sync project
  • The project 'cid' may be using a version of Gradle that does not contain the method. Open Gradle wrapper file
  • The build file may be missing a Gradle plugin. Apply Gradle plugin
  • WRONGTYPE Operation against a key holding the wrong kind of value php

    This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

    Remove duplicates in the list using linq

    List<Employee> employees = new List<Employee>()
    {
        new Employee{Id =1,Name="AAAAA"}
        , new Employee{Id =2,Name="BBBBB"}
        , new Employee{Id =3,Name="AAAAA"}
        , new Employee{Id =4,Name="CCCCC"}
        , new Employee{Id =5,Name="AAAAA"}
    };
    
    List<Employee> duplicateEmployees = employees.Except(employees.GroupBy(i => i.Name)
                                                 .Select(ss => ss.FirstOrDefault()))
                                                .ToList();
    

    DataTables: Cannot read property style of undefined

    most of the time it happens when the table header count and data cel count is not matched

    How to set transparent background for Image Button in code?

    This should work - imageButton.setBackgroundColor(android.R.color.transparent);

    What is the difference between a token and a lexeme?

    Using "Compilers Principles, Techniques, & Tools, 2nd Ed." (WorldCat) by Aho, Lam, Sethi and Ullman, AKA the Purple Dragon Book,

    Lexeme pg. 111

    A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.

    Token pg. 111

    A token is a pair consisting of a token name and an optional attribute value. The token name is an abstract symbol representing a kind of lexical unit, e.g., a particular keyword, or sequence of input characters denoting an identifier. The token names are the input symbols that the parser processes.

    Pattern pg. 111

    A pattern is a description of the form that the lexemes of a token may take. In the case of a keyword as a token, the pattern is just the sequence of characters that form the keyword. For identifiers and some other tokens, the pattern is more complex structure that is matched by many strings.

    Figure 3.2: Examplesof tokens pg.112

    [Token]       [Informal Description]                  [Sample Lexemes]
    if            characters i, f                         if
    else          characters e, l, s, e                   else
    comparison    < or > or <= or >= or == or !=          <=, !=
    id            letter followed by letters and digits   pi, score, D2
    number        any numeric constant                    3.14159, 0, 6.02e23
    literal       anything but ", surrounded by "'s       "core dumped"
    

    To better understand this relation to a lexer and parser we will start with the parser and work backwards to the input.

    To make it easier to design a parser, a parser does not work with the input directly but takes in a list of tokens generated by a lexer. Looking at the token column in Figure 3.2 we see tokens such as if, else, comparison, id, number and literal; these are names of tokens. Typically with a lexer/parser a token is a structure that holds not only the name of the token, but the characters/symbols that make up the token and the start and end position of the string of characters that make up the token, with the start and end position being used for error reporting, highlighting, etc.

    Now the lexer takes the input of characters/symbols and using the rules of the lexer converts the input characters/symbols into tokens. Now people who work with lexer/parser have their own words for things they use often. What you think of as a sequence of characters/symbols that make up a token are what people who use lexer/parsers call lexeme. So when you see lexeme, just think of a sequence of characters/symbols representing a token. In the comparison example, the sequence of characters/symbols can be different patterns such as < or > or else or 3.14, etc.

    Another way to think of the relation between the two is that a token is a programming structure used by the parser that has a property called lexeme that holds the character/symbols from the input. Now if you look at most definitions of token in code you may not see lexeme as one of the properties of the token. This is because a token will more likely hold the start and end position of the characters/symbols that represent the token and the lexeme, sequence of characters/symbols can be derived from the start and end position as needed because the input is static.

    Securing a password in a properties file

    enter image description here

    Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.

    http://www.jasypt.org/encrypting-configuration.html

    By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:

    datasource.driver=com.mysql.jdbc.Driver 
    datasource.url=jdbc:mysql://localhost/reportsdb 
    datasource.username=reportsUser 
    datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm) 
    

    Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).

    How do we read this value? like this:

    /*
    * First, create (or ask some other component for) the adequate encryptor for   
    * decrypting the values in our .properties file.   
    */  
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();     
    encryptor.setPassword("jasypt"); // could be got from web, env variable...    
    /*   
    * Create our EncryptableProperties object and load it the usual way.   
    */  
    Properties props = new EncryptableProperties(encryptor);  
    props.load(new FileInputStream("/path/to/my/configuration.properties"));
    
    /*   
    * To get a non-encrypted value, we just get it with getProperty...   
    */  
    String datasourceUsername = props.getProperty("datasource.username");
    
    /*   
    * ...and to get an encrypted value, we do exactly the same. Decryption will   
    * be transparently performed behind the scenes.   
    */ 
    String datasourcePassword = props.getProperty("datasource.password");
    
     // From now on, datasourcePassword equals "reports_passwd"...
    

    How to copy selected lines to clipboard in vim

    If vim is compiled with clipboard support, then you can use "*y meaning: yank visually selected text into register * ('*' is for clipboard)

    If there is no clipboard support, I think only other way is to use Ctrl+Insert after visually selecting the text in vim.

    "message failed to fetch from registry" while trying to install any module

    @therefromhere's answer is the best one. However Node versions have moved ever onwards and upwards, and the versioning was complicated by the remerge of io.js. Following the steps in his answer, you will end up with Node version 0.10.25 - not the most recent version.

    You should still purge any existing node/npm packages with

    sudo apt-get purge nodejs npm
    

    and then go and look at the nodesource deb install page at https://github.com/nodesource/distributions#debinstall.

    All Node.js versions are listed on the above page with the Linux commands to install them. And these packages will work on both Debian and Ubuntu.

    P.S. If you want to run Node v4.4 or higher on Ubuntu Precise or Debian Wheezy, you should review the information about running on older distros.

    P.P.S. If your apt-get is failing, the script will not complete (Google references were failing my apt-get update). You should see messages about the NodeSource signing key being added to your keyring and a final message instructing you to Run 'apt-get install nodejs' to install Node.js.

    P.P.P.S. npm is installed with node. Once installed, you can update to the latest npm with sudo npm install npm -g

    Adding options to a <select> using jQuery?

    Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

    var o = new Option("option text", "value");
    o.selected=true;
    $("#mySelect").append(o);
    

    how to make a html iframe 100% width and height?

    this code probable help you .

    <iframe src="" onload="this.width=screen.width;this.height=screen.height;">
    

    Parsing JSON using Json.net

    /*
         * This method takes in JSON in the form returned by javascript's
         * JSON.stringify(Object) and returns a string->string dictionary.
         * This method may be of use when the format of the json is unknown.
         * You can modify the delimiters, etc pretty easily in the source
         * (sorry I didn't abstract it--I have a very specific use).
         */ 
        public static Dictionary<string, string> jsonParse(string rawjson)
        {
            Dictionary<string, string> outdict = new Dictionary<string, string>();
            StringBuilder keybufferbuilder = new StringBuilder();
            StringBuilder valuebufferbuilder = new StringBuilder();
            StringReader bufferreader = new StringReader(rawjson);
    
            int s = 0;
            bool reading = false;
            bool inside_string = false;
            bool reading_value = false;
            //break at end (returns -1)
            while (s >= 0)
            {
                s = bufferreader.Read();
                //opening of json
                if (!reading)
                {
                    if ((char)s == '{' && !inside_string && !reading) reading = true;
                    continue;
                }
                else
                {
                    //if we find a quote and we are not yet inside a string, advance and get inside
                    if (!inside_string)
                    {
                        //read past the quote
                        if ((char)s == '\"') inside_string = true;
                        continue;
                    }
                    if (inside_string)
                    {
                        //if we reached the end of the string
                        if ((char)s == '\"')
                        {
                            inside_string = false;
                            s = bufferreader.Read(); //advance pointer
                            if ((char)s == ':')
                            {
                                reading_value = true;
                                continue;
                            }
                            if (reading_value && (char)s == ',')
                            {
                                //we know we just ended the line, so put itin our dictionary
                                if (!outdict.ContainsKey(keybufferbuilder.ToString())) outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                                //and clear the buffers
                                keybufferbuilder.Clear();
                                valuebufferbuilder.Clear();
                                reading_value = false;
                            }
                            if (reading_value && (char)s == '}')
                            {
                                //we know we just ended the line, so put itin our dictionary
                                if (!outdict.ContainsKey(keybufferbuilder.ToString())) outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                                //and clear the buffers
                                keybufferbuilder.Clear();
                                valuebufferbuilder.Clear();
                                reading_value = false;
                                reading = false;
                                break;
                            }
                        }
                        else
                        {
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                                continue;
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                                continue;
                            }
                        }
                    }
                    else
                    {
                        switch ((char)s)
                        {
                            case ':':
                                reading_value = true;
                                break;
                            default:
                                if (reading_value)
                                {
                                    valuebufferbuilder.Append((char)s);
                                }
                                else
                                {
                                    keybufferbuilder.Append((char)s);
                                }
                                break;
                        }
                    }
                }
            }
            return outdict;
        }
    

    Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

    For spring boot version 2.X.X below configuration worked for me.

    spring.datasource.url=jdbc:mysql://localhost:3306/rest
    spring.datasource.username=
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
    spring.jpa.generate-ddl=true
    spring.jpa.hibernate.ddl-auto = update 
    

    Old jdbc driver is deprecated. The new one is mentioned on above configuration. Please use the same and restart the project.

    How to read data from a file in Lua

    Just a little addition if one wants to parse a space separated text file line by line.

    read_file = function (path)
    local file = io.open(path, "rb") 
    if not file then return nil end
    
    local lines = {}
    
    for line in io.lines(path) do
        local words = {}
        for word in line:gmatch("%w+") do 
            table.insert(words, word) 
        end    
      table.insert(lines, words)
    end
    
    file:close()
    return lines;
    end
    

    How to call a function after a div is ready?

    inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

    <div id="div1">
        <script>
            $(document).ready(function(){
             //do something
            });
        </script>
    </div>
    

    and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

    Ansible: Set variable to file content

    You can use lookups in Ansible in order to get the contents of a file, e.g.

    user_data: "{{ lookup('file', user_data_file) }}"
    

    Caveat: This lookup will work with local files, not remote files.

    Here's a complete example from the docs:

    - hosts: all
      vars:
         contents: "{{ lookup('file', '/etc/foo.txt') }}"
      tasks:
         - debug: msg="the value of foo.txt is {{ contents }}"
    

    VBA collection: list of keys

    An alternative solution is to store the keys in a separate Collection:

    'Initialise these somewhere.
    Dim Keys As Collection, Values As Collection
    
    'Add types for K and V as necessary.
    Sub Add(K, V) 
    Keys.Add K
    Values.Add V, K
    End Sub
    

    You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

    Mongoose, Select a specific field with find

    Exclude

    Below code will retrieve all fields other than password within each document:

    const users = await UserModel.find({}, {
      password: 0 
    });
    console.log(users);
    

    Output

    [
      {
        "_id": "5dd3fb12b40da214026e0658",
        "email": "[email protected]"
      }
    ]
    

    Include

    Below code will only retrieve email field within each document:

    const users = await UserModel.find({}, {
      email: 1
    });
    console.log(users);
    

    Output

    [
      {
        "email": "[email protected]"
      }
    ]
    

    MVC Return Partial View as JSON

    You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

    Render a view as a string

    PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

    Using the code from the thread above, you would be able to use:

    public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
    {
        if (ModelState.IsValid)
        {
            if(Request.IsAjaxRequest())
                return PartialView("NotEvil", model);
            return View(model)
        }
        if(Request.IsAjaxRequest())
        {
            return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
        }
        return View(model);
    }
    

    Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

    Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.

    Warning comparison between pointer and integer

    In this line ...

    if (*message == "\0") {
    

    ... as you can see in the warning ...

    warning: comparison between pointer and integer
          ('int' and 'char *')
    

    ... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

    To fix this, use one of the following:

    if(*message == '\0') ...
    if(message[0] == '\0') ...
    if(!*message) ...
    

    On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

    AngularJS toggle class using ng-class

    <div data-ng-init="featureClass=false" 
         data-ng-click="featureClass=!featureClass" 
         data-ng-class="{'active': featureClass}">
        Click me to toggle my class!
    </div>
    

    Analogous to jQuery's toggleClass method, this is a way to toggle the active class on/off when the element is clicked.

    How to parse float with two decimal places in javascript?

    ceil from lodash is probably the best

    _.ceil("315.9250488",2) 
    _.ceil(315.9250488,2) 
    _.ceil(undefined,2)
    _.ceil(null,2)
    _.ceil("",2)
    

    will work also with a number and it's safe

    Calculate the mean by group

    2015 update with dplyr:

    df %>% group_by(dive) %>% summarise(percentage = mean(speed))
    Source: local data frame [2 x 2]
    
       dive percentage
    1 dive1  0.4777462
    2 dive2  0.6726483
    

    How to retrieve unique count of a field using Kibana + Elastic Search

    Be aware with Unique count you are using 'cardinality' metric, which does not always guarantee exact unique count. :-)

    the cardinality metric is an approximate algorithm. It is based on the HyperLogLog++ (HLL) algorithm. HLL works by hashing your input and using the bits from the hash to make probabilistic estimations on the cardinality.

    Depending on amount of data I can get differences of 700+ entries missing in a 300k dataset via Unique Count in Elastic which are otherwise really unique.

    Read more here: https://www.elastic.co/guide/en/elasticsearch/guide/current/cardinality.html

    How do I correct this Illegal String Offset?

    if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
    {
        if(!isset($data[$field]))
            $data[$field]="";
    }
    

    Lost connection to MySQL server at 'reading initial communication packet', system error: 0

    The problem was quite stupid for me.

    I used to get the same issue on AWS EC2 Ubuntu machine (MariaDB is installed locally for the time being), so I tried to make SSH tunneling, and had the same issue. So I tried to ssh tunnel over terminal:

    ssh -L13306:127.0.0.1:3306 [email protected] -i my/private/key.pem
    

    And it told me this:

    Please login as the user "ubuntu" rather than the user "root".

    I changed ssh user from root to ubuntu, just like my ssh config, and it connected just fine.

    So check your SSH connecting user.

    I oversaw this, so this too half an hour of my time, so I hope this will be useful for you.

    Command-line Git on Windows

    In windows 8.1, setting the PATH Environment Variable to Git's bin directory didn't work for me. Instead, I had to use the cmd directory C:\Program Files (x86)\Git\cmd.

    Credit to @VonC in this question

    jQuery .live() vs .on() method for adding a click event after loading dynamic html

    $(document).on('click', '.selector', function() { /* do stuff */ });

    EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.

    When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.

    Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.

    This is smart for a few reasons, including performance and memory utilization (in large scale applications)

    EDIT:

    Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.

    Observable.of is not a function

    For Angular 5+ :

    import { Observable } from 'rxjs/Observable';should work. The observer package should match the import as well import { Observer } from 'rxjs/Observer'; if you're using observers that is

    import {<something>} from 'rxjs'; does a huge import so it's better to avoid it.

    Selecting between two dates within a DateTime field - SQL Server

    select * 
    from blah 
    where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
    

    Depending on the country setting for the login, the month/day may need to be swapped around.

    Bulk create model objects in django

    Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

    SomeModel(Model):
        @classmethod
        def from_file(model, file_obj, headers, delimiter):
            model.objects.bulk_create([
                model(**dict(zip(headers, line.split(delimiter))))
                for line in file_obj],
                batch_size=None)
    

    Add leading zeroes to number in Java?

    Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

    static String intToString(int num, int digits) {
        assert digits > 0 : "Invalid number of digits";
    
        // create variable length array of zeros
        char[] zeros = new char[digits];
        Arrays.fill(zeros, '0');
        // format number as String
        DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
    
        return df.format(num);
    }
    

    Laravel Eloquent - distinct() and count() not working properly together

    This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()

    Using SED with wildcard

    The asterisk (*) means "zero or more of the previous item".

    If you want to match any single character use

    sed -i 's/string-./string-0/g' file.txt
    

    If you want to match any string (i.e. any single character zero or more times) use

    sed -i 's/string-.*/string-0/g' file.txt
    

    How can I get a precise time, for example in milliseconds in Objective-C?

    I would NOT use mach_absolute_time() because it queries a combination of the kernel and the processor for an absolute time using ticks (probably an uptime).

    What I would use:

    CFAbsoluteTimeGetCurrent();
    

    This function is optimized to correct the difference in the iOS and OSX software and hardware.

    Something Geekier

    The quotient of a difference in mach_absolute_time() and AFAbsoluteTimeGetCurrent() is always around 24000011.154871

    Here is a log of my app:

    Please note that final result time is a difference in CFAbsoluteTimeGetCurrent()'s

     2012-03-19 21:46:35.609 Rest Counter[3776:707] First Time: 353900795.609040
     2012-03-19 21:46:36.360 Rest Counter[3776:707] Second Time: 353900796.360177
     2012-03-19 21:46:36.361 Rest Counter[3776:707] Final Result Time (difference): 0.751137
     2012-03-19 21:46:36.363 Rest Counter[3776:707] Mach absolute time: 18027372
     2012-03-19 21:46:36.365 Rest Counter[3776:707] Mach absolute time/final time: 24000113.153295
     2012-03-19 21:46:36.367 Rest Counter[3776:707] -----------------------------------------------------
     2012-03-19 21:46:43.074 Rest Counter[3776:707] First Time: 353900803.074637
     2012-03-19 21:46:43.170 Rest Counter[3776:707] Second Time: 353900803.170256
     2012-03-19 21:46:43.172 Rest Counter[3776:707] Final Result Time (difference): 0.095619
     2012-03-19 21:46:43.173 Rest Counter[3776:707] Mach absolute time: 2294833
     2012-03-19 21:46:43.175 Rest Counter[3776:707] Mach absolute time/final time: 23999753.727777
     2012-03-19 21:46:43.177 Rest Counter[3776:707] -----------------------------------------------------
     2012-03-19 21:46:46.499 Rest Counter[3776:707] First Time: 353900806.499199
     2012-03-19 21:46:55.017 Rest Counter[3776:707] Second Time: 353900815.016985
     2012-03-19 21:46:55.018 Rest Counter[3776:707] Final Result Time (difference): 8.517786
     2012-03-19 21:46:55.020 Rest Counter[3776:707] Mach absolute time: 204426836
     2012-03-19 21:46:55.022 Rest Counter[3776:707] Mach absolute time/final time: 23999996.639500
     2012-03-19 21:46:55.024 Rest Counter[3776:707] -----------------------------------------------------
    

    How to check if a json key exists?

    You can try this to check wether the key exists or not:

    JSONObject object = new JSONObject(jsonfile);
    if (object.containskey("key")) {
      object.get("key");
      //etc. etc.
    }
    

    Best practice to run Linux service as a different user

    After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

    1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

      daemon --user=my_user my_cmd &>/dev/null &
      

      This is implemented by wrapping the process invocation with runuser - more on this later.

    2. Jonathan Leffler is right: there is setuid in Python:

      import os
      os.setuid(501) # UID of my_user is 501
      

      I still don't think you can setuid from inside a JVM, however.

    3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

      [my_user@my_host]$ id
      uid=500(my_user) gid=500(my_user) groups=500(my_user)
      [my_user@my_host]$ su my_user -c "id"
      Password: # don't want to be prompted!
      uid=500(my_user) gid=500(my_user) groups=500(my_user)
      

    To workaround that behaviour of su and runuser, I've changed my init script to something like:

    if [[ "$USER" == "my_user" ]]
    then
        daemon my_cmd &>/dev/null &
    else
        daemon --user=my_user my_cmd &>/dev/null &
    fi
    

    Thanks all for your help!

    Call JavaScript function from C#

    If you want to call JavaScript function in C#, this will help you:

    public string functionname(arg)
    {
        if (condition)
        {
            Page page = HttpContext.Current.CurrentHandler as Page;
            page.ClientScript.RegisterStartupScript(
                typeof(Page),
                "Test",
                "<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
        }
    }
    

    Vue.js - How to properly watch for nested data

    I used deep:true, but found the old and new value in the watched function was the same always. As an alternative to previous solutions I tried this, which will check any change in the whole object by transforming it to a string:

    created() {
        this.$watch(
            () => JSON.stringify(this.object),
                (newValue, oldValue) => {
                    //do your stuff                
                }
        );
    },
    

    Div vertical scrollbar show

    Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

    How to map an array of objects in React

    I think you want to print the name of the person or both the name and email :

    const renObjData = this.props.data.map(function(data, idx) {
        return <p key={idx}>{data.name}</p>;
    });
    

    or :

    const renObjData = this.props.data.map(function(data, idx) {
       return ([
           <p key={idx}>{data.name}</p>,
           <p key={idx}>{data.email}</p>,
       ]);
    });
    

    How do I convert an integer to binary in JavaScript?

    The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)

    1. Number System

    (123456).toString(2) will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.

    2. Internal Representation

    The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.

    3. Masks & Bitwise Operators

    MDN has a good overview of how bitwise operators work. Importantly:

    Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)

    Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.

    Here is the MDN example code for converting numbers into 32-bit strings.

    function createBinaryString (nMask) {
      // nMask must be between -2147483648 and 2147483647
      for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
           nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
      return sMask;
    }
    
    createBinaryString(0) //-> "00000000000000000000000000000000"
    createBinaryString(123) //-> "00000000000000000000000001111011"
    createBinaryString(-1) //-> "11111111111111111111111111111111"
    createBinaryString(-1123456) //-> "11111111111011101101101110000000"
    createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"
    

    Using WGET to run a cronjob PHP

    you can just use this code to hit the script using cron job using cpanel:

    wget https://www.example.co.uk/unique-code
    

    Change the selected value of a drop-down list with jQuery

    How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.

    If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.

    This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.

    Ignoring directories in Git repositories on Windows

    To instruct Git to ignore certain files or folders, you have to create .gitignore file.

    But in Windows Explorer you have to provide a name for the file. You just cannot create file with just an extension. The trick is that create a empty text file and go to command prompt and change the name of the file to .gitignore:

    ren "New Text Document.txt" .gitignore
    

    Now open the file with your favorite text editor and add the file/folder names you wish you ignore. You can also use wildcards like this: *.txt.

    Get file name from URL

    I've found that some urls when passed directly to FilenameUtils.getName return unwanted results and this needs to be wrapped up to avoid exploits.

    For example,

    System.out.println(FilenameUtils.getName("http://www.google.com/.."));
    

    returns

    ..

    which I doubt anyone wants to allow.

    The following function seems to work fine, and shows some of these test cases, and it returns null when the filename can't be determined.

    public static String getFilenameFromUrl(String url)
    {
        if (url == null)
            return null;
        
        try
        {
            // Add a protocol if none found
            if (! url.contains("//"))
                url = "http://" + url;
    
            URL uri = new URL(url);
            String result = FilenameUtils.getName(uri.getPath());
    
            if (result == null || result.isEmpty())
                return null;
    
            if (result.contains(".."))
                return null;
    
            return result;
        }
        catch (MalformedURLException e)
        {
            return null;
        }
    }
    

    This is wrapped up with some simple tests cases in the following example:

    import java.util.Objects;
    import java.net.URL;
    import org.apache.commons.io.FilenameUtils;
    
    class Main {
    
      public static void main(String[] args) {
        validateFilename(null, null);
        validateFilename("", null);
        validateFilename("www.google.com/../me/you?trex=5#sdf", "you");
        validateFilename("www.google.com/../me/you?trex=5 is the num#sdf", "you");
        validateFilename("http://www.google.com/test.png?test", "test.png");
        validateFilename("http://www.google.com", null);
        validateFilename("http://www.google.com#test", null);
        validateFilename("http://www.google.com////", null);
        validateFilename("www.google.com/..", null);
        validateFilename("http://www.google.com/..", null);
        validateFilename("http://www.google.com/test", "test");
        validateFilename("https://www.google.com/../../test.png", "test.png");
        validateFilename("file://www.google.com/test.png", "test.png");
        validateFilename("file://www.google.com/../me/you?trex=5", "you");
        validateFilename("file://www.google.com/../me/you?trex", "you");
      }
    
      private static void validateFilename(String url, String expectedFilename){
        String actualFilename = getFilenameFromUrl(url);
    
        System.out.println("");
        System.out.println("url:" + url);
        System.out.println("filename:" + expectedFilename);
    
        if (! Objects.equals(actualFilename, expectedFilename))
          throw new RuntimeException("Problem, actual=" + actualFilename + " and expected=" + expectedFilename + " are not equal");
      }
    
      public static String getFilenameFromUrl(String url)
      {
        if (url == null)
          return null;
    
        try
        {
          // Add a protocol if none found
          if (! url.contains("//"))
            url = "http://" + url;
    
          URL uri = new URL(url);
          String result = FilenameUtils.getName(uri.getPath());
    
          if (result == null || result.isEmpty())
            return null;
    
          if (result.contains(".."))
            return null;
    
          return result;
        }
        catch (MalformedURLException e)
        {
          return null;
        }
      }
    }
    

    How can I increase a scrollbar's width using CSS?

    If you are talking about the scrollbar that automatically appears on a div with overflow: scroll (or auto), then no, that's still a native scrollbar rendered by the browser using normal OS widgets, and not something that can be styled(*).

    Whilst you can replace it with a proxy made out of stylable divs and JavaScript as suggested by Matt, I wouldn't recommend it for the general case. Script-driven scrollbars never quite behave exactly the same as real OS scrollbars, causing usability and accessibility problems.

    (*: Except for the IE colouring styles, which I wouldn't really recommend either. Apart from being IE-only, using them forces IE to fall back from using nice scrollbar images from the current Windows theme to ugly old Win95-style scrollbars.)

    Subclipse svn:ignore

    It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.

    alt text

    For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.

    What is callback in Android?

    CallBack Interface are used for Fragment to Fragment communication in android.

    Refer here for your understanding.

    How to get the exact local time of client?

    Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api

    _x000D_
    _x000D_
    fetch("https://worldtimeapi.org/api/ip")
      .then(response => response.json())
      .then(data => console.log(data.dst,data.datetime));
    _x000D_
    _x000D_
    _x000D_

    Get a list of all functions and procedures in an Oracle database

    SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
    

    The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

    Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

    To enhance furthermore the useful .toDOM() snippet that we can find in different places, we can now safely use backticks (template literals).

    So we can have single and double quotes in the foo html declaration.

    This behave like heredocs for those familiar with the term.

    This can be enhanced furthermore with variables, to make complex templating:

    Template literals are enclosed by the back-tick () (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), this is called a "tagged template". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting. To escape a back-tick in a template literal, put a backslash \ before the back-tick.

    _x000D_
    _x000D_
    String.prototype.toDOM=function(){_x000D_
      var d=document,i_x000D_
         ,a=d.createElement("div")_x000D_
         ,b=d.createDocumentFragment()_x000D_
      a.innerHTML = this_x000D_
      while(i=a.firstChild)b.appendChild(i)_x000D_
      return b_x000D_
    }_x000D_
    _x000D_
    // Using template litterals_x000D_
    var a = 10, b = 5_x000D_
    var foo=`_x000D_
    <img _x000D_
      onclick="alert('The future start today!')"   _x000D_
      src='//placekitten.com/100/100'>_x000D_
    foo${a + b}_x000D_
      <i>bar</i>_x000D_
        <hr>`.toDOM();_x000D_
    document.body.appendChild(foo);
    _x000D_
    img {cursor: crosshair}
    _x000D_
    _x000D_
    _x000D_

    So, why not use directly .innerHTML +=? By doing so, the whole DOM is being recalculated by the browser, it's much slower.

    https://caniuse.com/template-literals

    Rotate and translate

    Something that may get missed: in my chaining project, it turns out a space separated list also needs a space separated semicolon at the end.

    In other words, this doesn't work:

    transform: translate(50%, 50%) rotate(90deg);
    

    but this does:

    transform: translate(50%, 50%) rotate(90deg) ; //has a space before ";"
    

    How to reset a timer in C#?

    I always do ...

    myTimer.Stop();
    myTimer.Start();
    

    ... is that a hack? :)

    Per comment, on Threading.Timer, it's the Change method ...

    dueTime Type: System.Int32 The amount of time to delay before the invoking the callback method specified when the Timer was constructed, in milliseconds. Specify Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.

    showing that a date is greater than current date

    For those that want a nice conditional:

    DECLARE @MyDate DATETIME  = 'some date in future' --example  DateAdd(day,5,GetDate())
    
    IF @MyDate < DATEADD(DAY,1,GETDATE())
        BEGIN
            PRINT 'Date NOT greater than today...'
    END
    ELSE 
        BEGIN
           PRINT 'Date greater than today...'
    END 
    

    How to use HTML Agility pack

    First, install the HTMLAgilityPack nuget package into your project.

    Then, as an example:

    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
    
    // There are various options, set as needed
    htmlDoc.OptionFixNestedTags=true;
    
    // filePath is a path to a file containing the html
    htmlDoc.Load(filePath);
    
    // Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)
    
    // ParseErrors is an ArrayList containing any errors from the Load statement
    if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
    {
        // Handle any parse errors as required
    
    }
    else
    {
    
        if (htmlDoc.DocumentNode != null)
        {
            HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
    
            if (bodyNode != null)
            {
                // Do something with bodyNode
            }
        }
    }
    

    (NB: This code is an example only and not necessarily the best/only approach. Do not use it blindly in your own application.)

    The HtmlDocument.Load() method also accepts a stream which is very useful in integrating with other stream oriented classes in the .NET framework. While HtmlEntity.DeEntitize() is another useful method for processing html entities correctly. (thanks Matthew)

    HtmlDocument and HtmlNode are the classes you'll use most. Similar to an XML parser, it provides the selectSingleNode and selectNodes methods that accept XPath expressions.

    Pay attention to the HtmlDocument.Option?????? boolean properties. These control how the Load and LoadXML methods will process your HTML/XHTML.

    There is also a compiled help file called HtmlAgilityPack.chm that has a complete reference for each of the objects. This is normally in the base folder of the solution.

    LocalDate to java.util.Date and vice versa simplest conversion?

    You can convert the java.util.Date object into a String object, which will format the date as yyyy-mm-dd.

    LocalDate has a parse method that will convert it to a LocalDate object. The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.

    Date to LocalDate

    LocalDate.parse(Date.toString())
    

    Whitespaces in java

    From sun docs:

    \s A whitespace character: [ \t\n\x0B\f\r]

    The simplest way is to use it with regex.

    JavaScript error: "is not a function"

    For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:

    It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

    Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.

    Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):

    • Missing script library
    • Typo
    • The function is within a scope that you currently do not have access to, e.g.:

    _x000D_
    _x000D_
    var x = function(){_x000D_
       var y = function() {_x000D_
          alert('fired y');_x000D_
       }_x000D_
    };_x000D_
        _x000D_
    //the global scope can't access y because it is closed over in x and not exposed_x000D_
    //y is not a function err triggered_x000D_
    x.y();
    _x000D_
    _x000D_
    _x000D_

    • Your object/function does not have the function your calling:

    _x000D_
    _x000D_
    var x = function(){_x000D_
       var y = function() {_x000D_
          alert('fired y');_x000D_
       }_x000D_
    };_x000D_
        _x000D_
    //z is not a function error (as above) triggered_x000D_
    x.z();
    _x000D_
    _x000D_
    _x000D_

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

    You know, there might be an easier way but the first thing that pops to mind is:

    Declare @SumVal int;
    Select @SumVal=Sum(Amount) From Expense;
    Print @SumVal;
    

    You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

    git pull while not in a git directory

    For anyone like me that was trying to do this via a drush (Drupal shell) command on a remote server, you will not be able to use the solution that requires you to CD into the working directory:

    Instead you need to use the solution that breaks up the pull into a fetch & merge:

    drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH fetch origin
    drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH merge origin/branch