Programs & Examples On #Ipod nano

Visual Studio Code Automatic Imports

Fill the include property in the first level of the JSON-object in the tsconfig.editor.json like here:

"include": [
  "src/**/*.ts"
]

It works for me well.

Also you can add another Typescript file extensions if it's needed, like here:

"include": [
  "src/**/*.ts",
  "src/**/*.spec.ts",
  "src/**/*.d.ts"
]

how can I enable PHP Extension intl?

After installing Laminas, I got the same error message

"Translator component requires the intl PHP extension"

while wanting to view the web application with the php web server:

php -S 0.0.0.0:8080 -t public public/index.php

As I'm usgin XAMPP, in

c:\xampp\php\php.ini

I had to enable the PHP extension intl in this line ;extension=php_intl.dll, remove the starting semicolon (;) and restart XAMPP. I hope this will help.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

how to overwrite css style

Using !important is not recommended but in this situation I think you should -

Write this in your internal CSS -

.flex-control-thumbs li {
  width: auto !important;
  float: none !important;
}

What is the proper way to re-attach detached objects in Hibernate?

Hibernate support reattach detached entity by serval ways, see Hibernate user guide.

How do I convert a pandas Series or index to a Numpy array?

If you are dealing with a multi-index dataframe, you may be interested in extracting only the column of one name of the multi-index. You can do this as

df.index.get_level_values('name_sub_index')

and of course name_sub_index must be an element of the FrozenList df.index.names

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

try using the Date property on the DateTime Object...

if(dtOne.Date == dtTwo.Date)
    ....

Error in file(file, "rt") : cannot open the connection

I had a same issue .I removed the extension from the file name.Example my file name was saved as xyz. csv. i saved it as xyz.

How do I get a list of installed CPAN modules?

I wrote a perl script just yesterday to do exactly this. The script returns the list of perl modules installed in @INC using the '::' as the separator. Call the script using -

perl perlmod.pl

OR

perl perlmod.pl <module name> #Case-insensitive(eg. perl perlmod.pl ftp)

As of now the script skips the current directory('.') since I was having problems with recursing soft-links but you can include it by changing the grep function in line 17 from

  grep { $_ !~ '^\.$' } @INC

to just,

@INC

The script can be found here.

Automatically scroll down chat div

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I add files and folders into GitHub repos?

If you want to add an empty folder you can add a '.keep' file in your folder.

This is because git does not care about folders.

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

The following is the un-installation for PostgreSQL 9.1 installed using the EnterpriseDB installer. You most probably have to replace folder /9.1/ with your version number. If /Library/Postgresql/ doesn't exist then you probably installed PostgreSQL with a different method like homebrew or Postgres.app.

To remove the EnterpriseDB One-Click install of PostgreSQL 9.1:

  1. Open a terminal window. Terminal is found in: Applications->Utilities->Terminal
  2. Run the uninstaller:

    sudo /Library/PostgreSQL/9.1/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
    

    If you installed with the Postgres Installer, you can do:

    open /Library/PostgreSQL/9.2/uninstall-postgresql.app
    

    It will ask for the administrator password and run the uninstaller.

  3. Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.

    sudo rm -rf /Library/PostgreSQL
    
  4. Remove the ini file:

    sudo rm /etc/postgres-reg.ini
    
  5. Remove the PostgreSQL user using System Preferences -> Users & Groups.

    1. Unlock the settings panel by clicking on the padlock and entering your password.
    2. Select the PostgreSQL user and click on the minus button.
  6. Restore your shared memory settings:

    sudo rm /etc/sysctl.conf
    

That should be all! The uninstall wizard would have removed all icons and start-up applications files so you don't have to worry about those.

How to change facet labels?

Both facet_wrap and facet_grid also accept input from ifelse as an argument. So if the variable used for faceting is logical, the solution is very simple:

facet_wrap(~ifelse(variable, "Label if true", "Label if false"))

If the variable has more categories, the ifelse statement needs to be nested.

As a side effect, this also allows the creation of the groups to be faceted within the ggplot call.

Using Regular Expressions to Extract a Value in Java

Look you can do it using StringTokenizer

String str = "as:"+123+"as:"+234+"as:"+345;
StringTokenizer st = new StringTokenizer(str,"as:");

while(st.hasMoreTokens())
{
  String k = st.nextToken();    // you will get first numeric data i.e 123
  int kk = Integer.parseInt(k);
  System.out.println("k string token in integer        " + kk);

  String k1 = st.nextToken();   //  you will get second numeric data i.e 234
  int kk1 = Integer.parseInt(k1);
  System.out.println("new string k1 token in integer   :" + kk1);

  String k2 = st.nextToken();   //  you will get third numeric data i.e 345
  int kk2 = Integer.parseInt(k2);
  System.out.println("k2 string token is in integer   : " + kk2);
}

Since we are taking these numeric data into three different variables we can use this data anywhere in the code (for further use)

matplotlib does not show my drawings although I call pyplot.show()

I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using

pip install matplotlib

To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you.

Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with. Even worse, it fails silently; that is, pip install matplotlib appears to install matplotlib successfully. But when you try to use it (e.g. pyplot.show()), no plot window will appear. I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get ImportError because it's trying to import some dependency that's missing). I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies.

The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib. That worked perfectly. Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version...

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

Change header background color of modal of twitter bootstrap

You can use the css below, put this in your custom css to override the bootstrap css.

.modal-header {
    padding:9px 15px;
    border-bottom:1px solid #eee;
    background-color: #0480be;
    -webkit-border-top-left-radius: 5px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
     border-top-left-radius: 5px;
     border-top-right-radius: 5px;
 }

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

What is parsing in terms that a new programmer would understand?

Simple explanation: Parsing is breaking a block of data into smaller pieces (tokens) by following a set of rules (using delimiters for example), so that this data could be processes piece by piece (managed, analysed, interpreted, transmitted, ets).

Examples: Many applications (like Spreadsheet programs) use CSV (Comma Separated Values) file format to import and export data. CSV format makes it possible for the applications to process this data with a help of a special parser. Web browsers have special parsers for HTML and CSS files. JSON parsers exist. All special file formats must have some parsers designed specifically for them.

How to change CSS using jQuery?

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $( document ).ready(function() {
         $('h1').css('color','#3498db');
      });
    </script>
    <style>
      .wrapper{
        height:450px;
        background:#ededed;
        text-align:center
      }
    </style>
  </head>
  <body>
    <div class="wrapper">
      <h1>Title</h1>
    </div>
  </body>
</html>

How to open .mov format video in HTML video Tag?

in the video source change the type to "video/quicktime"

<video width="400" controls Autoplay=autoplay>
  <source src="D:/mov1.mov" type="video/quicktime">
</video>

Difference between "@id/" and "@+id/" in Android

Difference between “@+id/” and “@id/” in Android

The first one is used for to create the ID of the particular ui component and the another one is used for to refer the particular component

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

I was getting the same error for a one to many relationships for below annotation.

@OneToMany(mappedBy="department", cascade = CascadeType.ALL)

Changed as below after adding fetch=FetchType.EAGER, it worked for me.

@OneToMany(mappedBy="department", cascade = CascadeType.ALL, fetch=FetchType.EAGER)

Making macOS Installer Packages which are Developer ID ready

Here is a build script which creates a signed installer package out of a build root.

#!/bin/bash
# TRIMCheck build script
# Copyright Doug Richardson 2015
# Usage: build.sh
#
# The result is a disk image that contains the TRIMCheck installer.
#

DSTROOT=/tmp/trimcheck.dst
SRCROOT=/tmp/trimcheck.src

INSTALLER_PATH=/tmp/trimcheck
INSTALLER_PKG="TRIMCheck.pkg"
INSTALLER="$INSTALLER_PATH/$INSTALLER_PKG"

#
# Clean out anything that doesn't belong.
#
echo Going to clean out build directories
rm -rf build $DSTROOT $SRCROOT $INSTALLER_PATH
echo Build directories cleaned out


#
# Build
#
echo ------------------
echo Installing Sources
echo ------------------
xcodebuild -project TRIMCheck.xcodeproj installsrc SRCROOT=$SRCROOT || exit 1

echo ----------------
echo Building Project
echo ----------------
pushd $SRCROOT
xcodebuild -project TRIMCheck.xcodeproj -target trimcheck -configuration Release install || exit 1
popd

echo ------------------
echo Building Installer
echo ------------------
mkdir -p "$INSTALLER_PATH" || exit 1

echo "Runing pkgbuild. Note you must be connected to Internet for this to work as it"
echo "has to contact a time server in order to generate a trusted timestamp. See"
echo "man pkgbuild for more info under SIGNED PACKAGES."
pkgbuild --identifier "com.delicioussafari.TRIMCheck" \
    --sign "Developer ID Installer: Douglas Richardson (4L84QT8KA9)" \
    --root "$DSTROOT" \
    "$INSTALLER" || exit 1


echo Successfully built TRIMCheck
open "$INSTALLER_PATH"

exit 0

Sequence Permission in Oracle

Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:

    select * from dba_tab_privs where table_name = 'sequence_name';

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

This worked for me! You can convert to datatype you want be it a date or string

to_char(TO_DATE(TO_CHAR(end_date),'MM-DD-YYYY'),'YYYY-MM-DD') AS end_date

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

How to show changed file name only with git log?

Now I use the following to get the list of changed files my current branch has, comparing it to master (the compare-to branch is easily changed):

git log --oneline --pretty="format:" --name-only master.. | awk 'NF' | sort -u

Before, I used to rely on this:

git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort -k 2,2 -u

which outputs a list of files only and their state (added, modified, deleted):

A   foo/bar/xyz/foo.txt
M   foo/bor/bar.txt
...

The -k2,2 option for sort, makes it sort by file path instead of the type of change (A, M, D,).

How to cast Object to its actual type?

Casting to actual type is easy:

void MyMethod(Object obj) {
    ActualType actualyType = (ActualType)obj;
}

When should I use mmap for file access?

In addition to other nice answers, a quote from Linux system programming written by Google's expert Robert Love:

Advantages of mmap( )

Manipulating files via mmap( ) has a handful of advantages over the standard read( ) and write( ) system calls. Among them are:

  • Reading from and writing to a memory-mapped file avoids the extraneous copy that occurs when using the read( ) or write( ) system calls, where the data must be copied to and from a user-space buffer.

  • Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory.

  • When multiple processes map the same object into memory, the data is shared among all the processes. Read-only and shared writable mappings are shared in their entirety; private writable mappings have their not-yet-COW (copy-on-write) pages shared.

  • Seeking around the mapping involves trivial pointer manipulations. There is no need for the lseek( ) system call.

For these reasons, mmap( ) is a smart choice for many applications.

Disadvantages of mmap( )

There are a few points to keep in mind when using mmap( ):

  • Memory mappings are always an integer number of pages in size. Thus, the difference between the size of the backing file and an integer number of pages is "wasted" as slack space. For small files, a significant percentage of the mapping may be wasted. For example, with 4 KB pages, a 7 byte mapping wastes 4,089 bytes.

  • The memory mappings must fit into the process' address space. With a 32-bit address space, a very large number of various-sized mappings can result in fragmentation of the address space, making it hard to find large free contiguous regions. This problem, of course, is much less apparent with a 64-bit address space.

  • There is overhead in creating and maintaining the memory mappings and associated data structures inside the kernel. This overhead is generally obviated by the elimination of the double copy mentioned in the previous section, particularly for larger and frequently accessed files.

For these reasons, the benefits of mmap( ) are most greatly realized when the mapped file is large (and thus any wasted space is a small percentage of the total mapping), or when the total size of the mapped file is evenly divisible by the page size (and thus there is no wasted space).

How to upper case every first letter of word in a string?

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

Combining two expressions (Expression<Func<T, bool>>)

I think this works fine, isn't it ?

Func<T, bool> expr1 = (x => x.Att1 == "a");
Func<T, bool> expr2 = (x => x.Att2 == "b");
Func<T, bool> expr1ANDexpr2 = (x => expr1(x) && expr2(x));
Func<T, bool> expr1ORexpr2 = (x => expr1(x) || expr2(x));
Func<T, bool> NOTexpr1 = (x => !expr1(x));

How to trim a string after a specific character in java

There are many good answers, but I would use StringUtils from commons-lang. I find StringUtils.substringBefore() more readable than the alternatives:

String result = StringUtils.substringBefore("34.1 -118.33\n<!--ABCDEFG-->", "\n");

How to use adb command to push a file on device without sd card

Certain versions of android do not fire proper tasks for updating the state of file system. You could trigger an explicit intent for updating the status of the file system. (I just tested after being in the same OP's situation)

adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///

(You could pass a specific filepath instead of file:/// like file:///sdcard )

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

Eclipse gives “Java was started but returned exit code 13”

It would be the 32 bit version of eclipse , for instance if you are running the 32 bit version of eclipse in 64 bit JVM, this error will be the result.

To confirm this check for log in your configuration folder of the eclipse. Log will be as following java.lang.UnsatisfiedLinkError: Cannot load 32-bit SWT libraries on 64-bit JVM ...

try installing the either 64 bit eclipse or run in 32 bit jvm

UITableViewCell, show delete button on swipe

Below UITableViewDataSource will help you for swipe delete

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [arrYears removeObjectAtIndex:indexPath.row];
        [tableView reloadData];
    }
}

arrYears is a NSMutableArray and then reload the tableView

Swift

 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
            return true
        }

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyleDelete {
        arrYears.removeObjectAtIndex(indexPath.row)
        tableView.reloadData()
    }
}

Programmatically register a broadcast receiver

In your onCreate method you can register a receiver like this:

private BroadcastReceiver receiver;

@Override
public void onCreate(Bundle savedInstanceState){

  // your oncreate code should be

  IntentFilter filter = new IntentFilter();
  filter.addAction("SOME_ACTION");
  filter.addAction("SOME_OTHER_ACTION");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //do something based on the intent's action
    }
  };
     registerReceiver(receiver, filter);
}

Remember to run this in the onDestroy method:

 @Override
 protected void onDestroy() {
  if (receiver != null) {
   unregisterReceiver(receiver);
   receiver = null;
  }
  super.onDestroy();
 }

Spring Boot Remove Whitelabel Error Page

This depends on your spring boot version:

When SpringBootVersion <= 1.2 then use error.whitelabel.enabled = false

When SpringBootVersion >= 1.3 then use server.error.whitelabel.enabled = false

Difference between session affinity and sticky session?

I've seen those terms used interchangeably, but there are different ways of implementing it:

  1. Send a cookie on the first response and then look for it on subsequent ones. The cookie says which real server to send to.
    Bad if you have to support cookie-less browsers
  2. Partition based on the requester's IP address.
    Bad if it isn't static or if many come in through the same proxy.
  3. If you authenticate users, partition based on user name (it has to be an HTTP supported authentication mode to do this).
  4. Don't require state.
    Let clients hit any server (send state to the client and have them send it back)
    This is not a sticky session, it's a way to avoid having to do it.

I would suspect that sticky might refer to the cookie way, and that affinity might refer to #2 and #3 in some contexts, but that's not how I have seen it used (or use it myself)

What is the difference between HTTP status code 200 (cache) vs status code 304?

This threw me for a long time too. The first thing I'd verify is that you're not reloading the page by clicking the refresh button, that will always issue a conditional request for resources and will return 304s for many of the page elements. Instead go up to the url bar select the page and hit enter as if you had just typed in the same URL again, that will give you a better indicator of what's being cached properly. This article does a great job explaining the difference between conditional and unconditional requests and how the refresh button affects them: http://blogs.msdn.com/b/ieinternals/archive/2010/07/08/technical-information-about-conditional-http-requests-and-the-refresh-button.aspx

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I know, I am a little late to the party ... what happen a lot, you just use default settings in your app pool in IIS. In IIS Administration utility, go to app pools->select pool-->advanced settings->Process Model/Identity and select a user identity which has right permissions. By default it is set to ApplicationPoolIdentity. If you're developer, you most likely admin on your machine, so you can select your account to run app pool. On the deployment servers, let admins to deal with it.

Command CompileSwift failed with a nonzero exit code in Xcode 10

I have the same issue and my solution is change a little thing in Build Settings

SWIFT_COMPILATION_MODE = singlefile;
SWIFT_OPTIMIZATION_LEVEL = "-O";

List<Object> and List<?>

List is an interface so you can't instanciate it. Use any of its implementatons instead e.g.

List<Object> object = new List<Object>();

About List : you can use any object as a generic param for it instance:

List<?> list = new ArrayList<String>();

or

List<?> list = new ArrayList<Integer>();

While using List<Object> this declaration is invalid because it will be type missmatch.

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

How to use mongoimport to import csv

First you should come out of the mongo shell and then execute the mongoimport command like this:

Manojs-MacBook-Air:bin Aditya$ mongoimport -d marketdata -c minibars 
--type csv 
--headerline
--file '/Users/Aditya/Downloads/mstf.csv'

2017-05-13T20:00:41.989+0800    connected to: localhost
2017-05-13T20:00:44.123+0800    imported 97609 documents
Manojs-MacBook-Air:bin Aditya$

HTML 5 video or audio playlist

Yep, you can simply point your src tag to a .m3u playlist file. A .m3u file is easy to construct -

#hosted mp3's need absolute paths but file system links can use relative paths
http://servername.com/path/to/mp3.mp3
http://servername.com/path/to/anothermp3.mp3
/path/to/local-mp3.mp3

-----UPDATE-----

Well, it turns out playlist m3u files are supported on the iPhone, but not on much else including Safari 5 which is kind of sad. I'm not sure about Android phones but I doubt they support it either since Chrome doesn't. Sorry for the misinformation.

Move_uploaded_file() function is not working

This answer is late but it might help someone like it helped me

Just ensure you have given the user permission for the destination file

sudo chown -R www-data:www-data /Users/George/Desktop/uploads/

Android RelativeLayout programmatically Set "centerInParent"

Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:

    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

How to initialize std::vector from C-style array?

You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.

If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:

Foo::Foo(double* w, int len) : w_(w, w + len) { }

Otherwise use assign as previously suggested:

void set_data(double* w, int len)
{
    w_.assign(w, w + len);
}

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

What can I use for good quality code coverage for C#/.NET?

TestMatrix is a unit test runner and code coverage tool.

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

How to initialise a string from NSData in Swift

This is the implemented code needed:

in Swift 3.0:

var dataString = String(data: fooData, encoding: String.Encoding.utf8)

or just

var dataString = String(data: fooData, encoding: .utf8)

Older swift version:

in Swift 2.0:

import Foundation

var dataString = String(data: fooData, encoding: NSUTF8StringEncoding)

in Swift 1.0:

var dataString = NSString(data: fooData, encoding:NSUTF8StringEncoding)

Why use getters and setters/accessors?

In a pure object-oriented world getters and setters is a terrible anti-pattern. Read this article: Getters/Setters. Evil. Period. In a nutshell, they encourage programmers to think about objects as of data structures, and this type of thinking is pure procedural (like in COBOL or C). In an object-oriented language there are no data structures, but only objects that expose behavior (not attributes/properties!)

You may find more about them in Section 3.5 of Elegant Objects (my book about object-oriented programming).

how to add key value pair in the JSON object already declared

You can add more key value pair in the same object without replacing old ones in following way:

var obj = {};

obj = {
"1": "aa",
"2": "bb"
};

obj["3"] = "cc";

Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:

var obj = {
    "1": "aa",
    "2": "bb"
};

var noOfItems = Object.keys(obj).length;

$('#btnAddProperty').on('click', function() {
    noOfItems++;
    obj[noOfItems] = $.trim($('#txtName').val());
    console.log(obj);
});

https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/

Given URL is not allowed by the Application configuration Facebook application error

For Android Developers,

Make sure you have enabled Facebook Login inside the Products list inside Dashboard of your Facebook project app and have added all the required details as you go through the whole flow.

The login should work without giving the same error.

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

How to remove folders with a certain name

This also works - it will remove all the folders called "a" and their contents:

rm -rf `find -type d -name a`

Function pointer to member function

int (*x)() is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;.

Perl regular expression (using a variable as a search string with Perl operator characters included)

You can use quotemeta (\Q \E) if your Perl is version 5.16 or later, but if below you can simply avoid using a regular expression at all.

For example, by using the index command:

if (index($text_to_search, $search_string) > -1) {
    print "wee";
}

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

Need a good hex editor for Linux

I am a VIMer. I can do some rare Hex edits with:

  • :%!xxd to switch into hex mode

  • :%!xxd -r to exit from hex mode

But I strongly recommend ht

apt-cache show ht

Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>

Homepage: http://hte.sourceforge.net/

Note: The package is called ht, whereas the executable is named hte after the package was installed.

  1. Supported file formats
    • common object file format (COFF/XCOFF32)
    • executable and linkable format (ELF)
    • linear executables (LE)
    • standard DO$ executables (MZ)
    • new executables (NE)
    • portable executables (PE32/PE64)
    • java class files (CLASS)
    • Mach exe/link format (MachO)
    • X-Box executable (XBE)
    • Flat (FLT)
    • PowerPC executable format (PEF)
  2. Code & Data Analyser
    • finds branch sources and destinations recursively
    • finds procedure entries
    • creates labels based on this information
    • creates xref information
    • allows to interactively analyse unexplored code
    • allows to create/rename/delete labels
    • allows to create/edit comments
    • supports x86, ia64, alpha, ppc and java code
  3. Target systems
    • DJGPP
    • GNU/Linux
    • FreeBSD
    • OpenBSD
    • Win32

Bash array with spaces in elements

If you aren't stuck on using bash, different handling of spaces in file names is one of the benefits of the fish shell. Consider a directory which contains two files: "a b.txt" and "b c.txt". Here's a reasonable guess at processing a list of files generated from another command with bash, but it fails due to spaces in file names you experienced:

# bash
$ for f in $(ls *.txt); { echo $f; }
a
b.txt
b
c.txt

With fish, the syntax is nearly identical, but the result is what you'd expect:

# fish
for f in (ls *.txt); echo $f; end
a b.txt
b c.txt

It works differently because fish splits the output of commands on newlines, not spaces.

If you have a case where you do want to split on spaces instead of newlines, fish has a very readable syntax for that:

for f in (ls *.txt | string split " "); echo $f; end

allowing only alphabets in text box using java script

just use onkeypress event like below:

<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month! e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.

Call one constructor from another

I am improving upon supercat's answer. I guess the following can also be done:

class Sample
{
    private readonly int _intField;
    public int IntProperty
    {
        get { return _intField; }
    }

    void setupStuff(ref int intField, int newValue)
    {
        //Do some stuff here based upon the necessary initialized variables.
        intField = newValue;
    }

    public Sample(string theIntAsString, bool? doStuff = true)
    {
        //Initialization of some necessary variables.
        //==========================================
        int i = int.Parse(theIntAsString);
        // ................
        // .......................
        //==========================================

        if (!doStuff.HasValue || doStuff.Value == true)
           setupStuff(ref _intField,i);
    }

    public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
    {
        setupStuff(ref _intField, theInt);
    }
}

Multiple IF AND statements excel

Try the following:

=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)

Python: Select subset from list based on index set

Use the built in function zip

property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]

EDIT

Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.

http://docs.python.org/library/itertools.html#itertools.compress

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

How to get screen dimensions as pixels in Android

There are times when you need to know the precise dimensions of the available space for a layout when in an activity's onCreate. After some thought I worked out this way of doing it.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startActivityForResult(new Intent(this, Measure.class), 1);
        // Return without setting the layout, that will be done in onActivityResult.
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        // Probably can never happen, but just in case.
        if (resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
        int width = data.getIntExtra("Width", -1);
        // Width is now set to the precise available width, and a layout can now be created.            ...
    }
}

public final class Measure extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       // Create a LinearLayout with a MeasureFrameLayout in it.
        // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way.
        LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this);
        measureFrameLayout.setLayoutParams(matchParent);
        linearLayout.addView(measureFrameLayout);
        this.addContentView(linearLayout, matchParent);
        // measureFrameLayout will now request this second activity to finish, sending back the width.
    }

    class MeasureFrameLayout extends FrameLayout {
        boolean finished = false;
        public MeasureFrameLayout(Context context) {
            super(context);
        }

        @SuppressLint("DrawAllocation")
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (finished) {
                return;
            }
            finished = true;
            // Send the width back as the result.
            Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec));
            Measure.this.setResult(Activity.RESULT_OK, data);
            // Tell this activity to finish, so the result is passed back.
            Measure.this.finish();
        }
    }
}

If for some reason you don't want to add another activity to the Android manifest, you can do it this way:

public class MainActivity extends Activity {
    static Activity measuringActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            extras = new Bundle();
        }
        int width = extras.getInt("Width", -2);
        if (width == -2) {
            // First time in, just start another copy of this activity.
            extras.putInt("Width", -1);
            startActivityForResult(new Intent(this, MainActivity.class).putExtras(extras), 1);
            // Return without setting the layout, that will be done in onActivityResult.
            return;
        }
        if (width == -1) {
            // Second time in, here is where the measurement takes place.
            // Create a LinearLayout with a MeasureFrameLayout in it.
            // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way.
            LinearLayout linearLayout = new LinearLayout(measuringActivity = this);
            LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this);
            measureFrameLayout.setLayoutParams(matchParent);
            linearLayout.addView(measureFrameLayout);
            this.addContentView(linearLayout, matchParent);
            // measureFrameLayout will now request this second activity to finish, sending back the width.
        }
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        // Probably can never happen, but just in case.
        if (resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
        int width = data.getIntExtra("Width", -3);
        // Width is now set to the precise available width, and a layout can now be created. 
        ...
    }

class MeasureFrameLayout extends FrameLayout {
    boolean finished = false;
    public MeasureFrameLayout(Context context) {
        super(context);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (finished) {
            return;
        }
        finished = true;
        // Send the width back as the result.
        Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec));
        MainActivity.measuringActivity.setResult(Activity.RESULT_OK, data);
        // Tell the (second) activity to finish.
        MainActivity.measuringActivity.finish();
    }
}    

PHP import Excel into database (xls & xlsx)

This is best plugin with proper documentation and examples

https://github.com/PHPOffice/PHPExcel

Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

Remove blank attributes from an Object in Javascript

You can loop through the object:

_x000D_
_x000D_
var test = {
  test1: null,
  test2: 'somestring',
  test3: 3,
}

function clean(obj) {
  for (var propName in obj) {
    if (obj[propName] === null || obj[propName] === undefined) {
      delete obj[propName];
    }
  }
  return obj
}

console.log(test);
console.log(clean(test));
_x000D_
_x000D_
_x000D_

If you're concerned about this property removal not running up object's proptype chain, you can also:

function clean(obj) {
  var propNames = Object.getOwnPropertyNames(obj);
  for (var i = 0; i < propNames.length; i++) {
    var propName = propNames[i];
    if (obj[propName] === null || obj[propName] === undefined) {
      delete obj[propName];
    }
  }
}

A few notes on null vs undefined:

test.test1 === null; // true
test.test1 == null; // true

test.notaprop === null; // false
test.notaprop == null; // true

test.notaprop === undefined; // true
test.notaprop == undefined; // true

Validating an XML against referenced XSD in C#

A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);

XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
    msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);

See the MSDN documentation for more assistance.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

I just ran into this issue myself, in the context of ASP.NET make sure your Web.config looks like this:

  <system.webServer>
<modules>
  <remove name="FormsAuthentication" />
</modules>

<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <!--<remove name="OPTIONSVerbHandler"/>-->
  <remove name="TRACEVerbHandler" />
  <!--
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  -->
</handlers>

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

Notice the Authorization value for the Access-Control-Allow-Headers key. I was missing the Authorization value, this config solves my issue.

Remove non-ASCII characters from CSV

I tried all the solutions and nothing worked. The following, however, does:

tr -cd '\11\12\15\40-\176'

Which I found here:

https://alvinalexander.com/blog/post/linux-unix/how-remove-non-printable-ascii-characters-file-unix

My problem needed it in a series of piped programs, not directly from a file, so modify as needed.

How does database indexing work?

Why is it needed?

When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.

Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses.

Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.

What is indexing?

Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.

The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.

How does it work?

Firstly, let’s outline a sample database table schema;

Field name       Data type      Size on disk
id (Primary key) Unsigned INT   4 bytes
firstName        Char(50)       50 bytes
lastName         Char(50)       50 bytes
emailAddress     Char(100)      100 bytes

Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field).

Example 1 - sorted vs unsorted fields

Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks.

A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement.

Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct.

Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below;

Field name       Data type      Size on disk
firstName        Char(50)       50 bytes
(record pointer) Special        4 bytes

Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.

Example 2 - indexing

Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks.

Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table.

When should it be used?

Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.

Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

PHP - remove <img> tag from string

I would suggest using the strip_tags method.

How to convert a String to a Date using SimpleDateFormat?

you can solve the problem much simple like First convert the the given string to the date object eg:

java.util.Date date1 = new Date("11/19/2015"); 
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy HH:mma");
String format = formatter.format(date);
System.out.println(format);

The property 'Id' is part of the object's key information and cannot be modified

In my case, I want to duplicate the object, but change the id, so I use this

Common.DataContext.Detach(object);

Work like a charm

Bootstrap 3 - set height of modal window according to screen size

To expand on Ryand's answer, if you're using Bootstrap.ui, this on your modal-instance will do the trick:

    modalInstance.rendered.then(function (result) {
        $('.modal .modal-body').css('overflow-y', 'auto'); 
        $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
        $('.modal .modal-body').css('height', $(window).height() * 0.7);
    });

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Just in case someone checked this thread and had the same issue as mine...

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I'm using NHibernate, I receive same error, during creating an object...

I was passing the key manually, and also specified a GUID generator in mapping, so hibernate generate same exact error for me, so once I removed the GUID, and left the field empty, everything went just fine.

this answer may not help you, but will help someone like me, who just your thread becasue of same error

A table name as a variable

Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)

SET @C_Tables = CURSOR FOR
        select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
    SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'

WHILE ( @fs_e <> -1)
    BEGIN
        exec('Select * from ' + @Table)
        FETCH @C_Tables INTO @Table
        SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
    END

Where is NuGet.Config file located in Visual Studio project?

Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.

You can also place the file at %appdata%\NuGet\NuGet.Config and it will be used everywhere.

https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file

windows batch file rename

I found this solution via PowerShell :

dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}

This will rename parts of all the files in the current folder.

How do I save JSON to local text file

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json" and format to .json

how to assign a block of html code to a javascript variable

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

var code = '<div class="my-class"> \
        <h1>The Header</h1> \
        <p>The paragraph of text</p> \
        <div class="my-quote"> \
            <p>The quote I\'d like to put in a div</p> \
        </div> \
    </div>';

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

Getting session value in javascript

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>  

Batch file include external file for variables

Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)

For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:

@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=

rem Go to the label with the parameter you selected
goto :config_%1

REM This next line is just to go to end of file 
REM in case that the parameter %1 is not set
goto :end

REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1


:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end

:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end


:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end


:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end


:end

After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.

Example test.bat

@echo off

rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"

call config.bat size

echo My birthday present had a width of %width% and a height of %height%

call config.bat family
call config.bat animals

echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%

rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%

call config.bat color

echo His lucky color is %first_color% even if %second_color% is also nice.

echo.
pause

Hope it helps the way others help me in here with their answers.

A short version of the above:

config.bat

@echo off
set config_all_selected=
goto :config_%1
goto :end

:config_all
set config_all_selected=1

:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end

:end

test.bat

@echo off

call config.bat size
echo My birthday present had a width of %width% and a height of %height%

call config.bat family
echo %father% and %mother% have a daughter named %daughter%

echo.
pause

Good day.

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

This was totally my bad.

I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.

Simply, I was trying to send a http request to https.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

Git error on git pull (unable to update local ref)

My team and I ran into this error, unable to update local ref, when doing a pull in SourceTree.

Update 2020: Per @Edward Yang's answer below, @bryan's comment on this answer, and this question/answer you may need to run both git gc --prune=now and git remote prune origin. Running only the former has always worked for me but based on ppl's responses I think both are necessary to address different causes of the error.

We used:

git gc --prune=now

This removes any duplicate reference objects which should fix the issue.

Here are a few links where you can learn more about git references and pruning :

git tip of the week

git-prune documentation

git references

Request exceeded the limit of 10 internal redirects due to probable configuration error

I just found a solution to the problem here:

http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/

The .htaccess file in webroot should look like:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

instead of this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /projectname
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

how to select first N rows from a table in T-SQL?

select top(@count) * from users

If @count is a constant, you can drop the parentheses:

select top 42 * from users

(the latter works on SQL Server 2000 too, while the former requires at least 2005)

Removing all script tags from html with JS Regular Expression

/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with

Easiest way to use SVG in Android?

Try the SVG2VectorDrawable Plugin. Go to Preferences->Plugins->Browse Plugins and install SVG2VectorDrawable. Great for converting sag files to vector drawable. Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.

not None test in Python

Either of the latter two, since val could potentially be of a type that defines __eq__() to return true when passed None.

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

asp.net mvc3 return raw html to view

What was working for me (ASP.NET Core), was to set return type ContentResult, then wrap the HMTL into it and set the ContentType to "text/html; charset=UTF-8". That is important, because, otherwise it will not be interpreted as HTML and the HTML language would be displayed as text.

Here's the example, part of a Controller class:

/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
    var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
      + "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
      + " to view API.</h2></head><body/></html>");
    result.ContentType = "text/html; charset=UTF-8";
    return result;
}

Getting next element while cycling through a list

You can use a pairwise cyclic iterator:

from itertools import izip, cycle, tee

def pairwise(seq):
    a, b = tee(seq)
    next(b)
    return izip(a, b)

for elem, next_elem in pairwise(cycle(li)):
    ...

Determine if running on a rooted device

Indeed it is interesting question and so far nobody has deserved award. I use the following code:

  boolean isRooted() {
      try {
                ServerSocket ss = new ServerSocket(81);
                ss.close();
                                    return true;
            } catch (Exception e) {
                // not sure
            }
    return false;
  }

The code is certainly not bulletproof, because network can be not available so you get an exception. If this method returns true then 99% you can be sure, otherwise just 50% that not. Networking permission can also spoil the solution.

A CSS selector to get last visible div

It is not possible with CSS, however you could do this with jQuery.

JSFIDDLE DEMO

jQuery:

$('li').not(':hidden').last().addClass("red");

HTML:

<ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="hideme">Item 4</li>    
</ul>

CSS:

.hideme {
    display:none;
}

.red {
    color: red;
}

jQuery (previous solution):

var $items = $($("li").get().reverse());

$items.each(function() {

    if ($(this).css("display") != "none") {
        $(this).addClass("red");
        return false;
    }

});

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

adb shell su works but adb root does not

I have a rooted Samsung Galaxy Trend Plus (GT-S7580).

Running 'adb root' gives me the same 'adbd cannot run as root in production builds' error.

For devices that have Developer Options -> Root access, choose "ADB only" to provide adb root access to the device (as suggested by NgaNguyenDuy).

Then try to run the command as per the solution at Launch a script as root through ADB. In my case, I just wanted to run the 'netcfg rndis0 dhcp' command, and I did it this way:

adb shell "su -c netcfg rndis0 dhcp"

Please check whether you are making any mistakes while running it this way.

If it still does not work, check whether you rooted the device correctly. If still no luck, try installing a custom ROM such as Cyanogen Mod in order for 'adb root' to work.

What is VanillaJS?

This is a joke for those who are excited about the JavaScript frameworks and do not know the pure Javascript.

So VanillaJS is the same as pure Javascript.

Vanilla in slang means:

unexciting, normal, conventional, boring

Here is a nice presentation on YouTube about VanillaJS: What is Vanilla JS?

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

You can set the value of the element to blank

document.getElementById('elementId').value='';

How to get files in a relative path in C#

As others have said, you can/should prepend the string with @ (though you could also just escape the backslashes), but what they glossed over (that is, didn't bring it up despite making a change related to it) was the fact that, as I recently discovered, using \ at the beginning of a pathname, without . to represent the current directory, refers to the root of the current directory tree.

C:\foo\bar>cd \
C:\>

versus

C:\foo\bar>cd .\
C:\foo\bar>

(Using . by itself has the same effect as using .\ by itself, from my experience. I don't know if there are any specific cases where they somehow would not mean the same thing.)

You could also just leave off the leading .\ , if you want.

C:\foo>cd bar
C:\foo\bar>

In fact, if you really wanted to, you don't even need to use backslashes. Forwardslashes work perfectly well! (Though a single / doesn't alias to the current drive root as \ does.)

C:\>cd foo/bar
C:\foo\bar>

You could even alternate them.

C:\>cd foo/bar\baz
C:\foo\bar\baz>

...I've really gone off-topic here, though, so feel free to ignore all this if you aren't interested.

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

Adding <script> to WordPress in <head> element

Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.

In your functions.php file, add

$inject_required_scripts = array();

/**
 * Call this function before calling get_header() to request custom js code to be injected on head.
 *
 * @param code the javascript code to be injected.
 */
function require_script($code) {
  global $inject_required_scripts;
  $inject_required_scripts[] = $code; // store code snippet for later injection
}

function inject_required_scripts() {
  global $inject_required_scripts;
  foreach($inject_required_scripts as $script)
    // inject all code snippets, if any
    echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');

And then in your page or template, use it like

<?php
/* Template Name: coolstuff */

require_script(<<<JS
  jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);

require_script(<<<JS
  jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);

get_header();
[...]

I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.

How to parseInt in Angular.js

Perform the operation inside the scope itself.

<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;


  $scope.total = $scope.num1 + $scope.num2;

 });
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{total}}

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Mismatched anonymous define() module

I was also seeing the same error on browser console for a project based out of require.js. As stated under MISMATCHED ANONYMOUS DEFINE() MODULES at https://requirejs.org/docs/errors.html, this error has multiple causes, the interesting one in my case being: If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer. As it turns out, Google Closure compiler was getting used to merge/minify the Javascript code during build. Solution was to remove the Google closure compiler, and instead use require.js's optimizer (r.js) to merge the js files.

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

PHP form send email to multiple recipients

If you need to add emails as CC or BCC, add the following part in the variable you use as for your header :

$headers .= "CC: [email protected]".PHP_EOL;
$headers .= "BCC: [email protected]".PHP_EOL;

Regards

Eclipse not recognizing JVM 1.8

OK, so I don't really know what the problem was, but I simply fixed it by navigating to here http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!

edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)

What is an .inc and why use it?

In my opinion, these were used as a way to quickly find include files when developing. Really these have been made obsolete with conventions and framework designs.

Spring Data JPA findOne() change to Optional how to use this?

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Now, findOne() has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository interface as:

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is the one defined in the QueryByExampleExecutor interface as:

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want that as a replacement.

In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional, which is not so bad to prevent NullPointerException.

So, the actual method to invoke is now Optional<T> findById(ID id).

How to use that?
Learning Optional usage. Here's important information about its specification:

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).


Some hints on how to use Optional with Optional<T> findById(ID id).

Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.

Here are three classical usage examples.

  1. Suppose that if the entity is found you want to get it otherwise you want to get a default value.

You could write :

Foo foo = repository.findById(id)
                    .orElse(new Foo());

or get a null default value if it makes sense (same behavior as before the API change) :

Foo foo = repository.findById(id)
                    .orElse(null);
  1. Suppose that if the entity is found you want to return it, else you want to throw an exception.

You could write :

return repository.findById(id)
        .orElseThrow(() -> new EntityNotFoundException(id));
  1. Suppose you want to apply a different processing according to if the entity is found or not (without necessarily throwing an exception).

You could write :

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
    Foo foo = fooOptional.get();
    // processing with foo ...
} else {
    // alternative processing....
}

NULL values inside NOT IN clause

also this might be of use to know the logical difference between join, exists and in http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx

Restrict varchar() column to specific values?

You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
    CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

PHP server on local machine?

PHP 5.4 and later have a built-in web server these days.

You simply run the command from the terminal:

cd path/to/your/app
php -S 127.0.0.1:8000

Then in your browser go to http://127.0.0.1:8000 and boom, your system should be up and running. (There must be an index.php or index.html file for this to work.)

You could also add a simple Router

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    require_once('resolver.php');
}
?>

And then run the command

php -S 127.0.0.1:8000 router.php

References:

Image inside div has extra space below the image

I used line-height:0 and it works fine for me.

EditText, clear focus on touch outside

I really think it's a more robust way to use getLocationOnScreen than getGlobalVisibleRect. Because I meet a problem. There is a Listview which contain some Edittext and and set ajustpan in the activity. I find getGlobalVisibleRect return a value that looks like including the scrollY in it, but the event.getRawY is always by the screen. The below code works well.

public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            if (!isPointInsideView(event.getRawX(), event.getRawY(), v)) {
                Log.i(TAG, "!isPointInsideView");

                Log.i(TAG, "dispatchTouchEvent clearFocus");
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent( event );
}

/**
 * Determines if given points are inside view
 * @param x - x coordinate of point
 * @param y - y coordinate of point
 * @param view - view object to compare
 * @return true if the points are within view bounds, false otherwise
 */
private boolean isPointInsideView(float x, float y, View view) {
    int location[] = new int[2];
    view.getLocationOnScreen(location);
    int viewX = location[0];
    int viewY = location[1];

    Log.i(TAG, "location x: " + location[0] + ", y: " + location[1]);

    Log.i(TAG, "location xWidth: " + (viewX + view.getWidth()) + ", yHeight: " + (viewY + view.getHeight()));

    // point is inside view bounds
    return ((x > viewX && x < (viewX + view.getWidth())) &&
            (y > viewY && y < (viewY + view.getHeight())));
}

How do I convert NSInteger to NSString datatype?

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

What causes a SIGSEGV

using an invalid/null pointer? Overrunning the bounds of an array? Kindof hard to be specific without any sample code.

Essentially, you are attempting to access memory that doesn't belong to your program, so the OS kills it.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

How to print to stderr in Python?

This will mimic the standard print function but output on stderr

def print_err(*args):
    sys.stderr.write(' '.join(map(str,args)) + '\n')

How do I unlock a SQLite database?

If a process has a lock on an SQLite DB and crashes, the DB stays locked permanently. That's the problem. It's not that some other process has a lock.

Assigning a variable NaN in python without numpy

A more consistent (and less opaque) way to generate inf and -inf is to again use float():

>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('-inf')
>> negative_inf
-inf

Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.

import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
               max_exp=1024, max_10_exp=308,
               min=2.2250738585072014e-308, min_exp=-1021,
               min_10_exp=-307, dig=15, mant_dig=53,
               epsilon=2.220446049250313e-16, radix=2, rounds=1)

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Unable to copy ~/.ssh/id_rsa.pub

add by user root this command : ssh user_to_acces@hostName -X

user_to_acces = user hostName = hostname machine

Removing u in list

The u means the strings are unicode. Translate all the strings to ascii to get rid of it:

a.encode('ascii', 'ignore')

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

How can I display a tooltip on an HTML "option" tag?

At least on firefox, you can set a "title" attribute on the option tag:

<option value="" title="Tooltip">Some option</option>

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

How to avoid "StaleElementReferenceException" in Selenium?

Try this

while (true) { // loops forever until break
    try { // checks code for exceptions
        WebElement ele=
        (WebElement)wait.until(ExpectedConditions.elementToBeClickable((By.xpath(Xpath))));  
        break; // if no exceptions breaks out of loop
    } 
    catch (org.openqa.selenium.StaleElementReferenceException e1) { 
        Thread.sleep(3000); // you can set your value here maybe 2 secs
        continue; // continues to loop if exception is found
    }
}

How do you make a HTTP request with C++?

libCURL is a pretty good option for you. Depending on what you need to do, the tutorial should tell you what you want, specifically for the easy handle. But, basically, you could do this just to see the source of a page:

CURL* c;
c = curl_easy_init();
curl_easy_setopt( c, CURL_URL, "www.google.com" );
curl_easy_perform( c );
curl_easy_cleanup( c );

I believe this will cause the result to be printed to stdout. If you want to handle it instead -- which, I assume, you do -- you need to set the CURL_WRITEFUNCTION. All of that is covered in the curl tutorial linked above.

Selecting the last value of a column

function lastRow(column){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var lastRow = sheet.getLastRow();
  var lastRowRange=sheet.getRange(column+startRow);
  return lastRowRange.getValue();
}

no hard coding.

Android - running a method periodically using postDelayed() call

Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what==0){
            // do stuff
            h.removeMessages(0);  // clear the handler for those messages with what = 0
            h.sendEmptyMessageDelayed(0, 2000); 
        }
    }
};


 h.sendEmptyMessage(0);  

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

How do I parse command line arguments in Java?

I want to show you my implementation: ReadyCLI

Advantages:

  • for lazy programmers: a very small number of classes to learn, just see the two small examples on the README in the repository and you are already at 90% of learning; just start coding your CLI/Parser without any other knowledge; ReadyCLI allows coding CLIs in the most natural way;
  • it is designed with Developer Experience in mind; it largely uses the Builder design pattern and functional interfaces for Lambda Expressions, to allow a very quick coding;
  • it supports Options, Flags and Sub-Commands;
  • it allows to parse arguments from command-line and to build more complex and interactive CLIs;
  • a CLI can be started on Standard I/O just as easily as on any other I/O interface, such as sockets;
  • it gives great support for documentation of commands.

I developed this project as I needed new features (options, flag, sub-commands) and that could be used in the simplest possible way in my projects.

memory error in python

A memory error means that your program has ran out of memory. This means that your program somehow creates too many objects.

In your example, you have to look for parts of your algorithm that could be consuming a lot of memory. I suspect that your program is given very long strings as inputs. Therefore, s[i:j+1] could be the culprit, since it creates a new list. The first time you use it though, it is not necessary because you don't use the created list. You could try to see if the following helps:

if  j + 1 < a:
    sub_strings.append(s[i:j+1])

To replace the second list creation, you should definitely use a buffer object, as suggested by glglgl.

Also note that since you use if j >= i:, you don't need to start your xrange at 0. You can have:

for i in xrange(0, a):
    for j in xrange(i, a):
        # No need for if j >= i

A more radical alternative would be to try to rework your algorithm so that you don't pre-compute all possible sub-strings. Instead, you could simply compute the substring that are asked.

Which terminal command to get just IP address and nothing else?

Use the following command:

/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '

jQuery’s .bind() vs. .on()

Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.

However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

scp via java

Here is an example to upload a file using JSch:

ScpUploader.java:

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.ByteArrayInputStream;
import java.util.Properties;

public final class ScpUploader
{
    public static ScpUploader newInstance()
    {
        return new ScpUploader();
    }

    private volatile Session session;
    private volatile ChannelSftp channel;

    private ScpUploader(){}

    public synchronized void connect(String host, int port, String username, String password) throws JSchException
    {
        JSch jsch = new JSch();

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session = jsch.getSession(username, host, port);
        session.setPassword(password);
        session.setConfig(config);
        session.setInputStream(System.in);
        session.connect();

        channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
    }

    public synchronized void uploadFile(String directoryPath, String fileName, byte[] fileBytes, boolean overwrite) throws SftpException
    {
        if(session == null || channel == null)
        {
            System.err.println("No open session!");
            return;
        }

        // a workaround to check if the directory exists. Otherwise, create it
        channel.cd("/");
        String[] directories = directoryPath.split("/");
        for(String directory : directories)
        {
            if(directory.length() > 0)
            {
                try
                {
                    channel.cd(directory);
                }
                catch(SftpException e)
                {
                    // swallowed exception

                    System.out.println("The directory (" + directory + ") seems to be not exist. We will try to create it.");

                    try
                    {
                        channel.mkdir(directory);
                        channel.cd(directory);
                        System.out.println("The directory (" + directory + ") is created successfully!");
                    }
                    catch(SftpException e1)
                    {
                        System.err.println("The directory (" + directory + ") is failed to be created!");
                        e1.printStackTrace();
                        return;
                    }

                }
            }
        }

        channel.put(new ByteArrayInputStream(fileBytes), directoryPath + "/" + fileName, overwrite ? ChannelSftp.OVERWRITE : ChannelSftp.RESUME);
    }

    public synchronized void disconnect()
    {
        if(session == null || channel == null)
        {
            System.err.println("No open session!");
            return;
        }

        channel.exit();
        channel.disconnect();
        session.disconnect();

        channel = null;
        session = null;
    }
}

AppEntryPoint.java:

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public final class AppEntryPoint
{
    private static final String HOST = "192.168.1.1";
    private static final int PORT = 22;
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) throws IOException
    {
        ScpUploader scpUploader = ScpUploader.newInstance();

        try
        {
            scpUploader.connect(HOST, PORT, USERNAME, PASSWORD);
        }
        catch(JSchException e)
        {
            System.err.println("Failed to connect the server!");
            e.printStackTrace();
            return;
        }

        System.out.println("Successfully connected to the server!");

        byte[] fileBytes = Files.readAllBytes(Paths.get("C:/file.zip"));

        try
        {
            scpUploader.uploadFile("/test/files", "file.zip", fileBytes, true); // if overwrite == false, it won't throw exception if the file exists
            System.out.println("Successfully uploaded the file!");
        }
        catch(SftpException e)
        {
            System.err.println("Failed to upload the file!");
            e.printStackTrace();
        }

        scpUploader.disconnect();
    }
}

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

Casting a number to a string in TypeScript

window.location.hash is a string, so do this:

var page_number: number = 3;
window.location.hash = String(page_number); 

Pass connection string to code-first DbContext

For anyone who came here trying find out how to set connection string dinamicaly, and got trouble with the solutions above (like "Format of the initialization string does not conform to specification starting at index 0.") when setting up the connection string in the constructor. This is how to fix it:

public static string ConnectionString
{
    get {
        if (ConfigurationManager.AppSettings["DevelopmentEnvironment"] == "true")
            return ConfigurationManager.ConnectionStrings["LocalDb"].ConnectionString;
        else
            return ConfigurationManager.ConnectionStrings["ExternalDb"].ConnectionString;
    }
}

public ApplicationDbContext() : base(ConnectionString)
{
}

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

Python: For each list element apply a function across the list

If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.

from __future__ import division

import numpy

data = numpy.asarray([1,2,3,4,5])
dists = data.reshape((1,5)) / data.reshape((5,1))

print dists

which = dists.argmin()
(r,c) = (which // 5, which % 5) # assumes C ordering

# pick whichever is most appropriate for you...
minval = dists[r,c]
minval = dists.min()
minval = dists.ravel()[which]

Windows Scheduled task succeeds but returns result 0x1

On our servers it was a problem with the system path. After upgrading PHP runtime (using installation directory whose name includes version number) and updating the path in system variable PATH we were getting status 0x1. System restart corrected the issue. Restarting Task Manager service might have done it, too.

Javascript: open new page in same window

I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)

$(function() {
    $('a[href$="url="]')    // all links whose href ends in "url="
        .each(function(i, el) {
            this.href += escape(document.location.href);
        })
    ;
});

and write your HTML like this:

<a href="http://example.com/submit.php?url=">...</a>

the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.

All this said, it looks like you're using PHP... why not add it in server-side?

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Working on .Net Core 2.2 and 3.0 as of now.

To get the projects root directory within a Controller:

  • Create a property for the hosting environment

    private readonly IHostingEnvironment _hostingEnvironment;
    
  • Add Microsoft.AspNetCore.Hosting to your controller

    using Microsoft.AspNetCore.Hosting;
    
  • Register the service in the constructor

    public HomeController(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }
    
  • Now, to get the projects root path

    string projectRootPath = _hostingEnvironment.ContentRootPath;
    

To get the "wwwroot" path, use

_hostingEnvironment.WebRootPath

What is the difference between String and string in C#?

String (capital S) is a class in the .NET framework in the System namespace. The fully qualified name is System.String. Whereas, the lower case string is an alias of System.String.

string str1= "Hello";
String str2 = "World!";
            
Console.WriteLine(str1.GetType().FullName); // System.String
Console.WriteLine(str2.GetType().FullName); // System.String

What are the best practices for SQLite on Android?

The Database is very flexible with multi-threading. My apps hit their DBs from many different threads simultaneously and it does just fine. In some cases I have multiple processes hitting the DB simultaneously and that works fine too.

Your async tasks - use the same connection when you can, but if you have to, its OK to access the DB from different tasks.

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 
  value1.getValue().equals(value.getValue())))).findAny().isPresent();   


System.out.println("comparison  "+b);

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.

Remove Elements from a HashSet while Iterating

Like timber said - "Java 8 Collection has a nice method called removeIf that makes things easier and safer"

Here is the code that solve your problem:

set.removeIf((Integer element) -> {
    return (element % 2 == 0);
});

Now your set contains only odd values.

How can I use a carriage return in a HTML tooltip?

I have tried with " " to display title text in new line and it's work like a charm

PHP Call to undefined function

This was a developer mistake - a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long - problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the "undefined function". That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

How to find text in a column and saving the row number where it is first found - Excel VBA

Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:

Sub find()
    Dim i As Integer
    Dim firstTime As Integer
    Dim bNotFound As Boolean

    i = 1
    bNotFound = True

      Do While bNotFound
        If Cells(i, 2).Value = "ProjTemp" Then
            firstTime = i
            bNotFound = false
        End If
        i = i + 1
    Loop
End Sub

Waiting until the task finishes

In Swift 3, there is no need for completion handler when DispatchQueue finishes one task. Furthermore you can achieve your goal in different ways

One way is this:

    var a: Int?

    let queue = DispatchQueue(label: "com.app.queue")
    queue.sync {

        for  i in 0..<10 {

            print("??" , i)
            a = i
        }
    }

    print("After Queue \(a)")

It will wait until the loop finishes but in this case your main thread will block.

You can also do the same thing like this:

    let myGroup = DispatchGroup()
    myGroup.enter()
    //// Do your task

    myGroup.leave() //// When your task completes
     myGroup.notify(queue: DispatchQueue.main) {

        ////// do your remaining work
    }

One last thing: If you want to use completionHandler when your task completes using DispatchQueue, you can use DispatchWorkItem.

Here is an example how to use DispatchWorkItem:

let workItem = DispatchWorkItem {
    // Do something
}

let queue = DispatchQueue.global()
queue.async {
    workItem.perform()
}
workItem.notify(queue: DispatchQueue.main) {
    // Here you can notify you Main thread
}

Android design support library for API 28 (P) not working

I cross that situation by replacing all androidx.* to appropiate package name.

change your line

implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'

to

implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'

androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

NOTED

  • remove tools:replace="android:appComponentFactory" from AndroidManifest

Checking if any elements in one list are in another

There are different ways. If you just want to check if one list contains any element from the other list, you can do this..

not set(list1).isdisjoint(list2)

I believe using isdisjoint is better than intersection for Python 2.6 and above.

NGINX - No input file specified. - php Fast/CGI

This is likely because with the trailing slash, NGinx tries to find the default index file which is probably index.html without configuration. Without the trailing slash it tries to match the file testservice which he can't find. Either this and/or you don't have any default index file in the testservice folder.

Try adding this line to your server configuration :

index  index.php index.html index.htm; // Or in the correct priority order for you

Hope this helps!

Edit

My answer is not very clear, see this example to understand what I mean

listen 80;

    server_name glo4000.mydomain.com www.glo4000.mydomain.com;


    access_log  /var/log/nginx/glo-4000.access.log;
    error_log /var/log/nginx/glo-4000.error_log;

    location / {
        root   /home/ul/glo-4000/;
        index  index.php index.html index.htm;
    }

    location ~ \.php$ {

        include fastcgi_params;
        fastcgi_pass   unix:/tmp/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME /home/ul/glo-4000/$fastcgi_script_name;
    }
}

change cursor from block or rectangle to line?

please Press fn +ins key together

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

How to open/run .jar file (double-click not working)?

You must create a manifest file and specify your class that has the main method. you can build your jar file with manifest file as a parameter.

jar cfm MyJar.jar Manifest.txt MyPackage/*.class

Manifest-Version: 1.0

Archiver-Version: Plexus Archiver

Created-By: Apache Maven

Built-By: Cakes

Build-Jdk: 1.6.0_04

Main-Class: com.foo.App

- java.lang.NullPointerException - setText on null object reference

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);
}

If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.

More reading on null pointers: What is a NullPointerException, and how do I fix it?

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to read and write to a text file in C++?

Header files needed:

#include <iostream>
#include <fstream>

declare input file stream:

ifstream in("in.txt");

declare output file stream:

ofstream out("out.txt");

if you want to use variable for a file name, instead of hardcoding it, use this:

string file_name = "my_file.txt";
ifstream in2(file_name.c_str());

reading from file into variables (assume file has 2 int variables in):

int num1,num2;
in >> num1 >> num2;

or, reading a line a time from file:

string line;
while(getline(in,line)){
//do something with the line
}

write variables back to the file:

out << num1 << num2;

close the files:

in.close();
out.close();

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I've faced this error, That was because the value you want to filter in the _id field is not in an ID format, one "if" should solve your error.

const mongoose = require('mongoose');

console.log(mongoose.Types.ObjectId.isValid('53cb6b9b4f4ddef1ad47f943'));
// true
console.log(mongoose.Types.ObjectId.isValid('whatever'));
// false

To solve it, always validate if the criteria value for search is a valid ObjectId

const criteria = {};
criteria.$or = [];

if(params.q) {
  if(mongoose.Types.ObjectId.isValid(params.id)) {
    criteria.$or.push({ _id: params.q })
  }
  criteria.$or.push({ name: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ email: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ password: { $regex: params.q, $options: 'i' }})
}

return UserModule.find(criteria).exec(() => {
  // do stuff
})