Programs & Examples On #Logfiles

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Sam's solution worked for me, but I didn't want to run as admin as a permanent solution.

This is how I solved it in my case:

  1. Run CMD as admin
  2. Type "netsh http show urlacl" and find the reserved url with the relevant port
  3. Type "netsh http delete urlacl url=YourReservedUrlHere"

After that I could run my app without the need for admin rights. But it did messed with the ability to browse to my app from an external computer. Close enough for me for now.

Java GC (Allocation Failure)

When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.

 -Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps 

Why is it that "No HTTP resource was found that matches the request URI" here?

Try this mate, you can chuck it in the body like so...

    [HttpPost]
    [Route("~/API/ChangeTheNameIfNeeded")]
    public bool SampleCall([FromBody]JObject data)
    {
        var firstName = data["firstName"].ToString();
        var lastName= data["lastName"].ToString();
        var email = data["email"].ToString();
        var obj= data["toLastName"].ToObject<SomeObject>();

        return _someService.DoYourBiz(firstName, lastName, email, obj);
    }

What is and how to fix System.TypeInitializationException error?

I experienced the System.TypeInitializationException due to a different error in my .NET framework 4 project's app.config. Thank you to pStan for getting me to look at the app.config. My configSections were properly defined. However, an undefined element within one of the sections caused the exception to be thrown.

Bottom line is that problems in the app.config can generated this very misleading TypeInitializationException.

A more meaningful ConfigurationErrorsException can be generated by the same error in the app.config by waiting to access the config values until you are within a method rather than at the class level of the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;

namespace ConfigTest
{
    class Program
    {
        public static string machinename;
        public static string hostname;
        public static NameValueCollection _AppSettings;

        static void Main(string[] args)
        {
            machinename = System.Net.Dns.GetHostName().ToLower();
            hostname = "abc.com";// System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName.ToLower().Replace(machinename + ".", "");
            _AppSettings = ConfigurationManager.GetSection("domain/" + hostname) as System.Collections.Specialized.NameValueCollection;
        }
    }
}

XAMPP - MySQL shutdown unexpectedly

STOP! Please do NOT delete ibdata1 file!

Deleting this file is like playing a Russian roulette with your databases, it could work and restablish everything, but also, probably could leave unusable every database you have.

Instead, first try using the MySQL backup folder which is included with XAMPP. So do the next:

  1. Rename the folder mysql/data to mysql/data_old (you can use any name)
  2. Create a new folder mysql/data
  3. Copy the content that resides in mysql/backup to the new mysql/data folder
  4. Copy all your database folders that are in mysql/data_old to mysql/data (skipping the mysql, performance_schema, and phpmyadmin folders from data_old)
  5. Finally copy the ibdata1 file from mysql/data_old and replace it inside mysql/data folder
  6. Start MySQL from XAMPP control panel

And, voilà!

Parsing huge logfiles in Node.js - read in line-by-line

The Node.js Documentation offers a very elegant example using the Readline module.

Example: Read File Stream Line-by-Line

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
    input: fs.createReadStream('sample.txt'),
    crlfDelay: Infinity
});

rl.on('line', (line) => {
    console.log(`Line from file: ${line}`);
});

Note: we use the crlfDelay option to recognize all instances of CR LF ('\r\n') as a single line break.

XAMPP - Error: MySQL shutdown unexpectedly

Well first thing ,, I know its late so I dont know if anyone will upvote it but oh well its okay,, secondly, uninstalling xampp might not do you any good because the process using the port 3306 (Mysql's default port) will still be running somewhere on your system. might be skype, but might not be skype.

so the best way would be to find out which process is using port 3306, and then terminate the process.

so to find out which process is using port 3306, open command prompt, and type

netstat -n -o -a

you will get a screen like this.

Then look for the address with port number 3306 and find out the PID corresponding to that.

Then simply open a command prompt as administrator and type

taskkill /F /PID 1234

replace 1234 with your respective PID. Then you can try starting mysql and it will work.


And now if you are lazy to do this step all over again when restarting the computer,,,

you can simply use the following batch script to terminate the process automatically and enjoy :)

@echo off
setlocal enableextensions
set "port=3306"
for /f "tokens=1,4,5" %%a in (
    'netstat -aon ^| findstr /r /c:"[TU][CD]P[^[]*\[::\]:%port%"'
) do if "%%a"=="UDP" (taskkill /F /PID %%b) else (taskkill /f /PID %%c)
endlocal
pause

save it as anything.bat and run it everytime you want to use mysql. :)


HTTP Error 503, the service is unavailable

I got this error with a .Net MVC application that uses Kentico as a satellite CMS. The issue was that it needed a proper license for the URL my app was on. It basically stopped the app and caused IIS to return nothing but this 503 - service not available message. I ended up finding the error details in Kentico's Event Log (as a warning). You can create a new license or find license details in Kentico's client portal - https://client.kentico.com/.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

This is old, but someone else may stumble on it as I did. When you connect to the DataCast, you are talking to a daemon that can access the database. It was intended that a customer would write some code to access the database and store the results somewhere. It just happens that telnet works to access data manually. netcat should also work. ssh obviously will not.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Error message "Forbidden You don't have permission to access / on this server"

Some configuration parameters have changed in Apache 2.4. I had a similar issue when I was setting up a Zend Framework 2 application. After some research, here is the solution:

Incorrect Configuration

<VirtualHost *:80>
    ServerName zf2-tutorial.localhost
    DocumentRoot /path/to/zf2-tutorial/public
    SetEnv APPLICATION_ENV "development"
    <Directory /path/to/zf2-tutorial/public>
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny #<-- 2.2 config
        Allow from all #<-- 2.2 config
    </Directory>
</VirtualHost>

Correct Configuration

<VirtualHost *:80>
    ServerName zf2-tutorial.localhost
    DocumentRoot /path/to/zf2-tutorial/public
    SetEnv APPLICATION_ENV "development"
    <Directory /path/to/zf2-tutorial/public>
        DirectoryIndex index.php
        AllowOverride All
        Require all granted #<-- 2.4 New configuration
    </Directory>
</VirtualHost>

If you are planning to migrate from Apache 2.2 to 2.4, here is a good reference: http://httpd.apache.org/docs/2.4/upgrading.html

SQL Server 2008: How to query all databases sizes?

with Total Database size ordered Desc

SELECT     
DB_NAME(db.database_id) DatabaseName,     
(CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,     
(CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB, 
(CAST(mfrows.RowSize AS FLOAT)*8)/1024/1024+(CAST(mflog.LogSize AS FLOAT)*8)/1024/1024 DBSizeG,
(CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,     
(CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB 
FROM sys.databases db     
LEFT JOIN (SELECT database_id, 
                  SUM(size) RowSize 
            FROM sys.master_files 
            WHERE type = 0 
            GROUP BY database_id, type) mfrows 
    ON mfrows.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) LogSize 
            FROM sys.master_files 
            WHERE type = 1 
            GROUP BY database_id, type) mflog 
    ON mflog.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) StreamSize 
                  FROM sys.master_files 
                  WHERE type = 2 
                  GROUP BY database_id, type) mfstream 
    ON mfstream.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) TextIndexSize 
                  FROM sys.master_files 
                  WHERE type = 4 
                  GROUP BY database_id, type) mftext 
    ON mftext.database_id = db.database_id 
       ORDER BY 4 DESC

Executing a command stored in a variable from PowerShell

Try invoking your command with Invoke-Expression:

Invoke-Expression $cmd1

Here is a working example on my machine:

$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd

iex is an alias for Invoke-Expression so you could do:

iex $cmd1

For a full list : Visit https://ss64.com/ps/ for more Powershell stuff.

Good Luck...

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Show a child form in the centre of Parent form in C#

On the SubLogin Form I would expose a SetLocation method so that you can set it from your parent form:

public class SubLogin : Form
{
   public void SetLocation(Point p)
   {
      this.Location = p;
   }
} 

Then, from your main form:

loginForm = new SubLogin();   
Point p = //do math to get point
loginForm.SetLocation(p);
loginForm.Show();

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

What's the equivalent of Java's Thread.sleep() in JavaScript?

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

How to timeout a thread

One thing that I've not seen mentioned is that killing threads is generally a Bad Idea. There are techniques for making threaded methods cleanly abortable, but that's different to just killing a thread after a timeout.

The risk with what you're suggesting is that you probably don't know what state the thread will be in when you kill it - so you risk introducing instability. A better solution is to make sure your threaded code either doesn't hang itself, or will respond nicely to an abort request.

Could not install packages due to an EnvironmentError: [Errno 13]

I got the same error when I was trying to install a package (flask-classful).
I made the mistake of installing anaconda as root. I changed the ownership of the installed anaconda folder and I could install the package successfully.

Use the command chown with option -R to recursively change ownership of the installed anaconda folder like so:

chown -R owner:group /path/to/anaconda

Here owner is your username and group is the group name.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.

var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Use the below command to solve your issue,

pip install mysql-python
apt-get install python3-mysqldb libmysqlclient-dev python-dev

Works on Debian

git: Switch branch and ignore any changes without committing

Follow,

$: git checkout -f

$: git checkout next_branch

Change the column label? e.g.: change column "A" to column "Name"

I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:

First, insert a new row at the beginning of the sheet. Within that row, define the names you need: new row

Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now: new top row

Now whenever you scroll down in the document, the first row will be "pinned" to the top: new behaviour

How does java do modulus calculations with negative numbers?

To overcome this, you could add 64 (or whatever your modulus base is) to the negative value until it is positive

int k = -13;
int modbase = 64;

while (k < 0) {
    k += modbase;
}

int result = k % modbase;

The result will still be in the same equivalence class.

Remove all line breaks from a long string of text

You can try using string replace:

string = string.replace('\r', '').replace('\n', '')

The import android.support cannot be resolved

I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:

compile 'platforms:android:android-support-v4:23.1.1'

so I changed it to:

compile 'com.android.support:support-v4:23.1.1'

And it started working.

How to know the git username and email saved during configuration?

List all variables set in the config file, along with their values.

git config --list

If you are new to git then use the following commands to set a user name and email address.

Set user name

git config --global user.name "your Name"

Set user email

git config --global user.email "[email protected]"

Check user name

git config user.name

Check user email

git config user.email

Create File If File Does Not Exist

Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.

Make virtualenv inherit specific packages from your global site-packages

You can use virtualenv --clear. which won't install any packages, then install the ones you want.

Concatenating two std::vectors

If you want to be able to concatenate vectors concisely, you could overload the += operator.

template <typename T>
std::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {
    vector1.insert(vector1.end(), vector2.begin(), vector2.end());
    return vector1;
}

Then you can call it like this:

vector1 += vector2;

Difference in make_shared and normal shared_ptr in C++

I see one problem with std::make_shared, it doesn't support private/protected constructors

Adding items in a Listbox with multiple columns

By using the List property.

ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"

Android Studio Google JAR file causing GC overhead limit exceeded error

At some point a duplicate copy of apply plugin: 'com.android.application' got added to my build gradle. Removing the duplicate copy and making sure all my apply plugins were at the top fixed the issue for me.

Is System.nanoTime() completely useless?

I have seen a negative elapsed time reported from using System.nanoTime(). To be clear, the code in question is:

    long startNanos = System.nanoTime();

    Object returnValue = joinPoint.proceed();

    long elapsedNanos = System.nanoTime() - startNanos;

and variable 'elapsedNanos' had a negative value. (I'm positive that the intermediate call took less than 293 years as well, which is the overflow point for nanos stored in longs :)

This occurred using an IBM v1.5 JRE 64bit on IBM P690 (multi-core) hardware running AIX. I've only seen this error occur once, so it seems extremely rare. I do not know the cause - is it a hardware-specific issue, a JVM defect - I don't know. I also don't know the implications for the accuracy of nanoTime() in general.

To answer the original question, I don't think nanoTime is useless - it provides sub-millisecond timing, but there is an actual (not just theoretical) risk of it being inaccurate which you need to take into account.

deleted object would be re-saved by cascade (remove deleted object from associations)

I was able to resolve this by writing the code below. I used executeUpdate instead of .delete()

def publicSupport = caseObj?.client?.publicSupport
        if(publicSupport)
            PublicSupport.executeUpdate("delete PublicSupport c where c.id = :publicSupportId", [publicSupportId:publicSupport.id])
            //publicSupport.delete()

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

MySQL Results as comma separated list

Instead of using group concat() you can use just concat()

Select concat(Col1, ',', Col2) as Foo_Bar from Table1;

edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.

How to upgrade docker container after its image changed

Taking from http://blog.stefanxo.com/2014/08/update-all-docker-images-at-once/

You can update all your existing images using the following command pipeline:

docker images | awk '/^REPOSITORY|\<none\>/ {next} {print $1}' | xargs -n 1 docker pull

The requested operation cannot be performed on a file with a user-mapped section open

I encountered this error and it turned out the issue was FxCop was running against my project. I closed FxCop and then I could compile again.

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

How to download Google Play Services in an Android emulator?

This is how you make Android Google Maps API v2 work on your emulator.


Create a new emulator

  • for device choose "5.1'' WVGA (480 x 800: mdpi)"
  • for target choose "Android 4.1.2 - API level 16"
  • for "CPU/ABI" choose "ARM"
  • leave rest to defaults

these are the settings that are working for me. I don't know for different ones.


Start the emulator


install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command


The longer answer is on my blog post about this issue https://medium.com/nemanja-kovacevic/how-to-make-android-google-maps-v2-work-in-android-emulator-e384f5423723

Combine [NgStyle] With Condition (if..else)

To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :

<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">

MySQL Delete all rows from table and reset ID to zero

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

How to Enable ActiveX in Chrome?

I'm not an expert but it sounds to me that this is something you could only do if you built the browser yourself - ie, not something done in a web page. I'm not sure that the sources for Chrome are publicly available (I think they are though), but the sources are what you'd probably need to change for this.

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).

Please verify cell values either are null or do handle Exception and see.

Best, Shahid

Landscape printing from HTML

I tried Denis's answer and hit some problems (portrait pages didn't print properly after going after landscape pages), so here is my solution:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  background: #CCCCCC;_x000D_
}_x000D_
_x000D_
div.page {_x000D_
  margin: 10px auto;_x000D_
  border: solid 1px black;_x000D_
  display: block;_x000D_
  page-break-after: always;_x000D_
  width: 209mm;_x000D_
  height: 296mm;_x000D_
  overflow: hidden;_x000D_
  background: white;_x000D_
}_x000D_
_x000D_
div.landscape-parent {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.landscape {_x000D_
  width: 296mm;_x000D_
  height: 209mm;_x000D_
}_x000D_
_x000D_
div.content {_x000D_
  padding: 10mm;_x000D_
}_x000D_
_x000D_
body,_x000D_
div,_x000D_
td {_x000D_
  font-size: 13px;_x000D_
  font-family: Verdana;_x000D_
}_x000D_
_x000D_
@media print {_x000D_
  body {_x000D_
    background: none;_x000D_
  }_x000D_
  div.page {_x000D_
    width: 209mm;_x000D_
    height: 296mm;_x000D_
  }_x000D_
  div.landscape {_x000D_
    transform: rotate(270deg) translate(-296mm, 0);_x000D_
    transform-origin: 0 0;_x000D_
  }_x000D_
  div.portrait,_x000D_
  div.landscape,_x000D_
  div.page {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    border: none;_x000D_
    background: none;_x000D_
  }_x000D_
}
_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    First page in Portrait mode_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page landscape-parent">_x000D_
  <div class="landscape">_x000D_
    <div class="content">_x000D_
      Second page in Landscape mode (correctly shows horizontally in browser and prints rotated in printer)_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="page">_x000D_
  <div class="content">_x000D_
    Third page in Portrait mode_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

How do I limit the number of rows returned by an Oracle query after ordering?

Pagination queries with ordering are really tricky in Oracle.

Oracle provides a ROWNUM pseudocolumn that returns a number indicating the order in which the database selects the row from a table or set of joined views.

ROWNUM is a pseudocolumn that gets many people into trouble. A ROWNUM value is not permanently assigned to a row (this is a common misunderstanding). It may be confusing when a ROWNUM value is actually assigned. A ROWNUM value is assigned to a row after it passes filter predicates of the query but before query aggregation or sorting.

What is more, a ROWNUM value is incremented only after it is assigned.

This is why the followin query returns no rows:

 select * 
 from (select *
       from some_table
       order by some_column)
 where ROWNUM <= 4 and ROWNUM > 1; 

The first row of the query result does not pass ROWNUM > 1 predicate, so ROWNUM does not increment to 2. For this reason, no ROWNUM value gets greater than 1, consequently, the query returns no rows.

Correctly defined query should look like this:

select *
from (select *, ROWNUM rnum
      from (select *
            from skijump_results
            order by points)
      where ROWNUM <= 4)
where rnum > 1; 

Find out more about pagination queries in my articles on Vertabelo blog:

MySql Query Replace NULL with Empty String in Select

SELECT COALESCE(prereq, '') FROM test

Coalesce will return the first non-null argument passed to it from left to right. If all arguemnts are null, it'll return null, but we're forcing an empty string there, so no null values will be returned.

Also note that the COALESCE operator is supported in standard SQL. This is not the case of IFNULL. So it is a good practice to get use the former. Additionally, bear in mind that COALESCE supports more than 2 parameters and it will iterate over them until a non-null coincidence is found.

Slack clean all messages (~8K) in a channel

Option 1 You can set a Slack channel to automatically delete messages after 1 day, but it's a little hidden. First, you have to go to your Slack Workspace Settings, Message Retention & Deletion, and check "Let workspace members override these settings". After that, in the Slack client you can open a channel, click the gear, and click "Edit message retention..."

Option 2 The slack-cleaner command line tool that others have mentioned.

Option 3 Below is a little Python script that I use to clear Private channels. Can be a good starting point if you want more programmatic control of deletion. Unfortunately Slack has no bulk-delete API, and they rate-limit the individual delete to 50 per minute, so it unavoidably takes a long time.

# -*- coding: utf-8 -*-
"""
Requirement: pip install slackclient
"""
import multiprocessing.dummy, ctypes, time, traceback, datetime
from slackclient import SlackClient
legacy_token = raw_input("Enter token of an admin user. Get it from https://api.slack.com/custom-integrations/legacy-tokens >> ")
slack_client = SlackClient(legacy_token)


name_to_id = dict()
res = slack_client.api_call(
  "groups.list", # groups are private channels, conversations are public channels. Different API.
  exclude_members=True, 
  )
print ("Private channels:")
for c in res['groups']:
    print(c['name'])
    name_to_id[c['name']] = c['id']

channel = raw_input("Enter channel name to clear >> ").strip("#")
channel_id = name_to_id[channel]

pool=multiprocessing.dummy.Pool(4) #slack rate-limits the API, so not much benefit to more threads.
count = multiprocessing.dummy.Value(ctypes.c_int,0)
def _delete_message(message):
    try:
        success = False
        while not success:
            res= slack_client.api_call(
                  "chat.delete",
                  channel=channel_id,
                  ts=message['ts']
                )
            success = res['ok']
            if not success:
                if res.get('error')=='ratelimited':
#                    print res
                    time.sleep(float(res['headers']['Retry-After']))
                else:
                    raise Exception("got error: %s"%(str(res.get('error'))))
        count.value += 1
        if count.value % 50==0:
            print(count.value)
    except:
        traceback.print_exc()

retries = 3
hours_in_past = int(raw_input("How many hours in the past should messages be kept? Enter 0 to delete them all. >> "))
latest_timestamp = ((datetime.datetime.utcnow()-datetime.timedelta(hours=hours_in_past)) - datetime.datetime(1970,1,1)).total_seconds()
print("deleting messages...")
while retries > 0:
    #see https://api.slack.com/methods/conversations.history
    res = slack_client.api_call(
      "groups.history",
      channel=channel_id,
      count=1000,
      latest=latest_timestamp,)#important to do paging. Otherwise Slack returns a lot of already-deleted messages.
    if res['messages']:
        latest_timestamp = min(float(m['ts']) for m in res['messages'])
    print datetime.datetime.utcfromtimestamp(float(latest_timestamp)).strftime("%r %d-%b-%Y")

    pool.map(_delete_message, res['messages'])
    if not res["has_more"]: #Slack API seems to lie about this sometimes
        print ("No data. Sleeping...")
        time.sleep(1.0)
        retries -= 1
    else:
        retries=10

print("Done.")

Note, that script will need modification to list & clear public channels. The API methods for those are channels.* instead of groups.*

Fastest Convert from Collection to List<T>

Since 3.5, anything inherited from System.Collection.IEnumerable has the convenient extension method OfType available.

If your collection is from ICollection or IEnumerable, you can just do this:

List<ManagementObject> managementList = ManagementObjectCollection.OfType<ManagementObject>().ToList();

Can't find any way simpler. : )

How to get browser width using JavaScript code?

An adapted solution to modern JS of Travis' answer:

const getPageWidth = () => {
  const bodyMax = document.body
    ? Math.max(document.body.scrollWidth, document.body.offsetWidth)
    : 0;

  const docElementMax = document.documentElement
    ? Math.max(
        document.documentElement.scrollWidth,
        document.documentElement.offsetWidth,
        document.documentElement.clientWidth
      )
    : 0;

  return Math.max(bodyMax, docElementMax);
};

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

build-impl.xml:1031: The module has not been deployed

if you still getting this error try this.

  1. Go to Netbeans services
  2. Remove Apache Tomcat.
  3. Add Apache Tomcat again.
  4. Build Project.
  5. Deploy Project

enter image description here

How to switch text case in visual studio code

I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case

To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}




EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Set value to currency in <input type="number" />

In the end I made a jQuery plugin that will format the <input type="number" /> appropriately for me. I also noticed on some mobile devices the min and max attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:

_x000D_
_x000D_
(function($) {_x000D_
  $.fn.currencyInput = function() {_x000D_
    this.each(function() {_x000D_
      var wrapper = $("<div class='currency-input' />");_x000D_
      $(this).wrap(wrapper);_x000D_
      $(this).before("<span class='currency-symbol'>$</span>");_x000D_
      $(this).change(function() {_x000D_
        var min = parseFloat($(this).attr("min"));_x000D_
        var max = parseFloat($(this).attr("max"));_x000D_
        var value = this.valueAsNumber;_x000D_
        if(value < min)_x000D_
          value = min;_x000D_
        else if(value > max)_x000D_
          value = max;_x000D_
        $(this).val(value.toFixed(2)); _x000D_
      });_x000D_
    });_x000D_
  };_x000D_
})(jQuery);_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('input.currency').currencyInput();_x000D_
});
_x000D_
.currency {_x000D_
  padding-left:12px;_x000D_
}_x000D_
_x000D_
.currency-symbol {_x000D_
  position:absolute;_x000D_
  padding: 2px 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
_x000D_
_x000D_
_x000D_

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

Regular expression for first and last name

As macek said:

Don't forget about names like:

Mathias d'Arras

Martin Luther King, Jr.

Hector Sausage-Hausen

and to remove cases like:

..Mathias

Martin king, Jr.-

This will cover more cases:

^([a-z]+[,.]?[ ]?|[a-z]+['-]?)+$

disable all form elements inside div

Simply this line of code will disable all input elements

$('#yourdiv *').prop('disabled', true);

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

Accessing inventory host variable in Ansible playbook

Thanks a lot this note was very useful for me! Was able to send the variable defined under /group_var/vars in the ansible playbook as indicated below.

tasks:
- name: check service account password expiry
- command:

sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

how to display a div triggered by onclick event

If you have the ID of the div, try this:

  <input type='submit' onclick='$("#div_id").show()'>

How to save a dictionary to a file?

Save and load dict to file:

def save_dict_to_file(dic):
    f = open('dict.txt','w')
    f.write(str(dic))
    f.close()

def load_dict_from_file():
    f = open('dict.txt','r')
    data=f.read()
    f.close()
    return eval(data)

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

Border around each cell in a range

You only need a single line of code to set the border around every cell in the range:

Range("A1:F20").Borders.LineStyle = xlContinuous

It's also easy to apply multiple effects to the border around each cell.

For example:

Sub RedOutlineCells()
    Dim rng As Range

    Set rng = Range("A1:F20")

    With rng.Borders
        .LineStyle = xlContinuous
        .Color = vbRed
        .Weight = xlThin
    End With
End Sub

How to open warning/information/error dialog in Swing?

See How to Make Dialogs.

You can use:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.

Vue-router redirect on page not found (404)

This answer may come a bit late but I have found an acceptable solution. My approach is a bit similar to @Mani one but I think mine is a bit more easy to understand.

Putting it into global hook and into the component itself are not ideal, global hook checks every request so you will need to write a lot of conditions to check if it should be 404 and window.location.href in the component creation is too late as the request has gone into the component already and then you take it out.

What I did is to have a dedicated url for 404 pages and have a path * that for everything that not found.

{ path: '/:locale/404', name: 'notFound', component: () => import('pages/Error404.vue') },
{ path: '/:locale/*', 
  beforeEnter (to) {
    window.location = `/${to.params.locale}/404`
  }
}

You can ignore the :locale as my site is using i18n so that I can make sure the 404 page is using the right language.

On the side note, I want to make sure my 404 page is returning httpheader 404 status code instead of 200 when page is not found. The solution above would just send you to a 404 page but you are still getting 200 status code. To do this, I have my nginx rule to return 404 status code on location /:locale/404

server {
    listen                      80;
    server_name                 localhost;

    error_page  404 /index.html;
    location ~ ^/.*/404$ {
      root   /usr/share/nginx/html;
      internal;
    }

    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
      rewrite ^(.+)$ /index.html last;
    }

    location = /50x.html {
      root   /usr/share/nginx/html;
    }
}

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

For this particular case looks like using a directive to dynamically create the component would be a better option. Example:

In the HTML where you want to create the component

<ng-container dynamicComponentDirective [someConfig]="someConfig"></ng-container>

I would approach and design the directive in the following way.

const components: {[type: string]: Type<YourConfig>} = {
    text : TextEditorComponent,
    numeric: NumericComponent,
    string: StringEditorComponent,
    date: DateComponent,
    ........
    .........
};

@Directive({
    selector: '[dynamicComponentDirective]'
})
export class DynamicComponentDirective implements YourConfig, OnChanges, OnInit {
    @Input() yourConfig: Define your config here //;
    component: ComponentRef<YourConfig>;

    constructor(
        private resolver: ComponentFactoryResolver,
        private container: ViewContainerRef
    ) {}

    ngOnChanges() {
        if (this.component) {
            this.component.instance.config = this.config;
            // config is your config, what evermeta data you want to pass to the component created.
        }
    }

    ngOnInit() {
        if (!components[this.config.type]) {
            const supportedTypes = Object.keys(components).join(', ');
            console.error(`Trying to use an unsupported type ${this.config.type} Supported types: ${supportedTypes}`);
        }

        const component = this.resolver.resolveComponentFactory<yourConfig>(components[this.config.type]);
        this.component = this.container.createComponent(component);
        this.component.instance.config = this.config;
    }
}

So in your components text, string, date, whatever - whatever the config you have been passing in the HTML in the ng-container element would be available.

The config, yourConfig, can be the same and define your metadata.

Depending on your config or input type the directive should act accordingly and from the supported types, it would render the appropriate component. If not it will log an error.

How do I configure PyCharm to run py.test tests?

PyCharm 2017.3

  1. Preference -> Tools -> Python integrated Tools - Choose py.test as Default test runner.
  2. If you use Django Preference -> Languages&Frameworks -> Django - Set tick on Do not use Django Test runner
  3. Clear all previously existing test configurations from Run/Debug configuration, otherwise tests will be run with those older configurations.
  4. To set some default additional arguments update py.test default configuration. Run/Debug Configuration -> Defaults -> Python tests -> py.test -> Additional Arguments

T-SQL STOP or ABORT command in SQL Server

Despite its very explicit and forceful description, RETURN did not work for me inside a stored procedure (to skip further execution). I had to modify the condition logic. Happens on both SQL 2008, 2008 R2:

create proc dbo.prSess_Ins
(
    @sSessID    varchar( 32 )
,   @idSess     int out
)
as
begin
    set nocount on

    select  @id=    idSess
        from    tbSess
        where   sSessID = @sSessID

    if  @idSess > 0 return  -- exit sproc here

    begin   tran
        insert  tbSess  ( sSessID ) values  ( @sSessID )
        select  @idSess=    scope_identity( )
    commit
end

had to be changed into:

    if  @idSess is null
    begin
        begin   tran
            insert  tbSess  ( sSessID ) values  ( @sSessID )
            select  @idSess=    scope_identity( )
        commit
    end

Discovered as a result of finding duplicated rows. Debugging PRINTs confirmed that @idSess had value greater than zero in the IF check - RETURN did not break execution!

Wrap a text within only two lines inside div

CSS only

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

Check the current number of connections to MongoDb

In OS X, too see the connections directly on the network interface, just do:

$ lsof -n -i4TCP:27017

mongod     2191 inanc    7u  IPv4 0xab6d9f844e21142f  0t0  TCP 127.0.0.1:27017 (LISTEN)
mongod     2191 inanc   33u  IPv4 0xab6d9f84604cd757  0t0  TCP 127.0.0.1:27017->127.0.0.1:56078 (ESTABLISHED)
stores.te 18704 inanc    6u  IPv4 0xab6d9f84604d404f  0t0  TCP 127.0.0.1:56078->127.0.0.1:27017 (ESTABLISHED)
  • No need to use grep etc, just use the lsof's arguments.

  • Too see the connections on MongoDb's CLI, see @milan's answer (which I just edited).

How to get the nvidia driver version from the command line?

If you need to get that in a program with Python on a Linux system for reproducibility:

with open('/proc/driver/nvidia/version') as f:
    version = f.read().strip()
print(version)

gives:

NVRM version: NVIDIA UNIX x86_64 Kernel Module  384.90  Tue Sep 19 19:17:35 PDT 2017
GCC version:  gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5) 

regex.test V.S. string.match to know if a string matches a regular expression

This is my benchmark results benchmark results

test 4,267,740 ops/sec ±1.32% (60 runs sampled)

exec 3,649,719 ops/sec ±2.51% (60 runs sampled)

match 3,623,125 ops/sec ±1.85% (62 runs sampled)

indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)

test method is faster than the match method, but the fastest method is the indexOf

HTML5 validation when the input type is not "submit"

2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.

The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

Updated solution snippet:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.reportValidity()) {
    f.submit();
  }
}

How to display count of notifications in app launcher icon

It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

Check if string contains a value in array

You can concatenate the array values with implode and a separator of | and then use preg_match to search for the value.

Here is the solution I came up with ...

$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}

What is the difference between a HashMap and a TreeMap?

You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

async/await - when to return a Task vs void?

The problem with calling async void is that

you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing

Here are the three ways to call an async function:

async Task<T> SomethingAsync() { ... return t; }
async Task SomethingAsync() { ... }
async void SomethingAsync() { ... }

In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.

In the first case, the function returns a task that eventually produces the t.

In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.

The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.

The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.

How can I get a count of the total number of digits in a number?

Using recursion (sometimes asked on interviews)

public int CountDigits(int number)
{
    // In case of negative numbers
    number = Math.Abs(number);

    if (number >= 10)
        return CountDigits(number / 10) + 1;
    return 1;
 }

When to use React "componentDidUpdate" method?

A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):

export default class Task extends React.Component {
  
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country
    });
  }

  render() {
    let {name, age, country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

So whenever the component has a state change it will autosave the data. There are other ways to implement it too. The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed.

The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.

I made a demo on this fiddle as well to demonstrate.


For more info, refer to the official docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Is it possible to see more than 65536 rows in Excel 2007?

Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.

Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.

How do I redirect with JavaScript?

window.location.replace('http://sidanmor.com');

It's better than using window.location.href = 'http://sidanmor.com';

Using replace() is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use window.location.href

If you want to simulate an HTTP redirect, use window.location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");

// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";

Taken from here: How to redirect to another page in jQuery?

Linux: Which process is causing "device busy" when doing umount?

Filesystems mounted on the filesystem you're trying to unmount can cause the target is busy error in addition to any files that are in use. (For example when you mount -o bind /dev /mnt/yourmount/dev in order to use chroot there.)

To find which file systems are mounted on the filesystem run the following:

mount | grep '/mnt/yourmount'

To find which files are in use the advice already suggested by others here:

lsof | grep '/mnt/yourmount'

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

FORCE INDEX goes right after the table reference:

SELECT * FROM (
    SELECT owner_id,
           product_id,
           start_time,
           price,
           currency,
           name,
           closed,
           active,
           approved,
           deleted,
           creation_in_progress
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND resultstable.active = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC

WARNING:

If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

Get each line from textarea

For a <br> on each line, use

<textarea wrap="physical"></textarea>

You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.

Hope this helps

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

This error occurs when your project references out of date schemas. Use Visual Studio to generate new ones.

In Visual Studio, do the following:

  1. Open your app.config or web.config file.
  2. Go to the XML menu and select Create Schema.

This will trigger app#.xsd (Windows app) or web#.xsd (Website) file(s) to generate.

  1. Save the newly generated xsd file(s) to the root of the project.
    • Open up your App.config or web.config file, right-click in the text-editor and select properties and click the ... button next to the value for Schemas.
    • Add the newly generated xsd file(s) using the Add button.
    • Click OK

The Could not find schema information for the attribute/element error(s) should now be resolved.

Android Reading from an Input stream efficiently

To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the BufferedReader return null which means there's no more data to read. Each line will appended to a StringBuilder and returned as String.

 public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}`

And finally from any class where you want to convert call the function

String dataString = Utils.convertStreamToString(in);

complete

The imported project "C:\Microsoft.CSharp.targets" was not found

Sometimes the problem might be with hardcoded VS version in .csproj file. If you have in your csproj something like this:

[...]\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets"

You should check if the number is correct (the reason it's wrong can be the project was created with another version of Visual Studio). If it's wrong, replace it with your current version of build tools OR use the VS variable:

[...]\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets"

What causes "Unable to access jarfile" error?

In my issue to access directory from Command line (in windows) this error

"unnable to access ..."

because wrong file extension

file.jar.jar

! , so change it to correct one

file.jar

:) good luck

Spring Data JPA and Exists query

You can just return a Boolean like this:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;

@QueryHints(@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_FETCH_SIZE, value = "1"))
@Query(value = "SELECT (1=1) FROM MyEntity WHERE ...... :id ....")
Boolean existsIfBlaBla(@Param("id") String id);

Boolean.TRUE.equals(existsIfBlaBla("0815")) could be a solution

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

DataTable, How to conditionally delete rows

Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:

someDataTable.Rows.Cast<DataRow>().Where(
    r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete());

Adding integers to an int array

You cannot use the add method on an array in Java.

To add things to the array do it like this

public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
    int neki = Integer.parseInt(s);
    num[i] = neki;

}

If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.

ArrayList Example

public static void main(String[] args) {
    ArrayList<Integer> num = new ArrayList<Integer>();
    for (String s : args){
        Integer neki = new Integer(Integer.parseInt(s));
        num.add(s);
}

Ajax - 500 Internal Server Error

I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:

Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');

and then I put it like this:

Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');

HTTP POST Returns Error: 417 "Expectation Failed."

Solution from proxy side, I faced some problems in the SSL handshake process and I had to force my proxy server to send requests using HTTP/1.0 to solve the problem by setting this argument in the httpd.conf SetEnv force-proxy-request-1.0 1 SetEnv proxy-nokeepalive 1 after that I faced the 417 error as my clients application was using HTTP/1.1 and the proxy was forced to use HTTP/1.0, the problem was solved by setting this parameter in the httpd.conf on the proxy side RequestHeader unset Expect early without the need to change anything in the client side, hope this helps.

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

Symbolicating iPhone App Crash Reports

I found out most of proposed alternatives did not work in latest XCode (tested with Xcode 10). For example, I had no luck drag-dropping .crash logs in Xcode -> Organizer -> Device logs -view.

I recommend using Symbolicator tool https://github.com/agentsim/Symbolicator

  • Git clone Symbolicator repository and compile and run with Xcode
  • Copy .crash file (ascii file, with stack trace in begging of file) and .xarchive of crashing release to same temporarly folder
  • Drag and drop .crash file to Symbolicator icon in Dock
  • In 5-30 secs symbolicated crash file is produced in same folder as .crash and .xarchive are

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

Regex - how to match everything except a particular pattern

notnot, resurrecting this ancient question because it had a simple solution that wasn't mentioned. (Found your question while doing some research for a regex bounty quest.)

I'm faced with a situation where I have to match an (A and ~B) pattern.

The basic regex for this is frighteningly simple: B|(A)

You just ignore the overall matches and examine the Group 1 captures, which will contain A.

An example (with all the disclaimers about parsing html in regex): A is digits, B is digits within <a tag

The regex: <a.*?<\/a>|(\d+)

Demo (look at Group 1 in the lower right pane)

Reference

How to match pattern except in situations s1, s2, s3

How to match a pattern unless...

Inherit CSS class

Something like this:

.base {
    width:100px;
}

div.child {
    background-color:red;
    color:blue;
}

.child {
    background-color:yellow;
}

<div class="base child">
    hello world
</div>

The background here will be red, as the css selector is more specific, as we've said it must belong to a div element too!

see it in action here: jsFiddle

Serializing to JSON in jQuery

The best way is to include the polyfill for JSON object.

But if you insist create a method for serializing an object to JSON notation (valid values for JSON) inside the jQuery namespace, you can do something like this:

Implementation

// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
  var _PRIMITIVE, _OPEN, _CLOSE;
  if (window.JSON && typeof JSON.stringify === "function")
    return JSON.stringify;

  _PRIMITIVE = /string|number|boolean|null/;

  _OPEN = {
    object: "{",
    array: "["
  };

  _CLOSE = {
    object: "}",
    array: "]"
  };

  //actions to execute in each iteration
  function action(key, value) {
    var type = $.type(value),
      prop = "";

    //key is not an array index
    if (typeof key !== "number") {
      prop = '"' + key + '":';
    }
    if (type === "string") {
      prop += '"' + value + '"';
    } else if (_PRIMITIVE.test(type)) {
      prop += value;
    } else if (type === "array" || type === "object") {
      prop += toJson(value, type);
    } else return;
    this.push(prop);
  }

  //iterates over an object or array
  function each(obj, callback, thisArg) {
    for (var key in obj) {
      if (obj instanceof Array) key = +key;
      callback.call(thisArg, key, obj[key]);
    }
  }

  //generates the json
  function toJson(obj, type) {
    var items = [];
    each(obj, action, items);
    return _OPEN[type] + items.join(",") + _CLOSE[type];
  }

  //exported function that generates the json
  return function stringify(obj) {
    if (!arguments.length) return "";
    var type = $.type(obj);
    if (_PRIMITIVE.test(type))
      return (obj === null ? type : obj.toString());
    //obj is array or object
    return toJson(obj, type);
  }
}(jQuery));

Usage

var myObject = {
    "0": null,
    "total-items": 10,
    "undefined-prop": void(0),
    sorted: true,
    images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
    position: { //nested object literal
        "x": 40,
        "y": 300,
        offset: [{ top: 23 }]
    },
    onChange: function() { return !0 },
    pattern: /^bg-.+\.(?:png|jpe?g)$/i
};

var json = jQuery.stringify(myObject);
console.log(json);

How can I delete a newline if it is the last character in a file?

POSIX SED:

'${/^$/d}'

$ - match last line


{ COMMANDS } - A group of commands may be enclosed between { and } characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match.

.gitignore all the .DS_Store files in every folder and subfolder

I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.

You have to manually remove the .DS_Store files that were added to your repository. You can use

git rm --cached .DS_Store

Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store. Don't forget the period!

git rm --cached .DS_Store

removes only .DS_Store from the current directory. You can use

find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

to remove all .DS_Stores from the repository.

Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g.

echo .DS_Store >> ~/.gitignore_global

Now tell git to use it for all repositories:

git config --global core.excludesfile ~/.gitignore_global

This page helped me answer your question.

CSS background image to fit width, height should auto-scale in proportion

There is a CSS3 property for this, namely background-size (compatibility check). While one can set length values, it's usually used with the special values contain and cover. In your specific case, you should use cover:

body {
    background-image:    url(images/background.svg);
    background-size:     cover;                      /* <------ */
    background-repeat:   no-repeat;
    background-position: center center;              /* optional, center the image */
}

Eggsplanation for contain and cover

Sorry for the bad pun, but I'm going to use the picture of the day by Biswarup Ganguly for demonstration. Lets say that this is your screen, and the gray area is outside of your visible screen. For demonstration, I'm going to assume a 16x9 ratio.

screen

We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for some reason. We could set the background-size property to some fixed length, but we will focus on contain and cover. Note that I also assume that we didn't mangle the width and/or height of body.

contain

contain

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

This makes sure that the background image is always completely contained in the background positioning area, however, there could be some empty space filled with your background-color in this case:

contain

cover

cover

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

This makes sure that the background image is covering everything. There will be no visible background-color, however depending on the screen's ratio a great part of your image could be cut off:

cover

Demonstration with actual code

_x000D_
_x000D_
div > div {_x000D_
  background-image: url(http://i.stack.imgur.com/r5CAq.jpg);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  background-color: #ccc;_x000D_
  border: 1px solid;_x000D_
  width: 20em;_x000D_
  height: 10em;_x000D_
}_x000D_
div.contain {_x000D_
  background-size: contain;_x000D_
}_x000D_
div.cover {_x000D_
  background-size: cover;_x000D_
}_x000D_
/********************************************_x000D_
 Additional styles for the explanation boxes _x000D_
*********************************************/_x000D_
_x000D_
div > div {_x000D_
  margin: 0 1ex 1ex 0;_x000D_
  float: left;_x000D_
}_x000D_
div + div {_x000D_
  clear: both;_x000D_
  border-top: 1px dashed silver;_x000D_
  padding-top:1ex;_x000D_
}_x000D_
div > div::after {_x000D_
  background-color: #000;_x000D_
  color: #fefefe;_x000D_
  margin: 1ex;_x000D_
  padding: 1ex;_x000D_
  opacity: 0.8;_x000D_
  display: block;_x000D_
  width: 10ex;_x000D_
  font-size: 0.7em;_x000D_
  content: attr(class);_x000D_
}
_x000D_
<div>_x000D_
  <div class="contain"></div>_x000D_
  <p>Note the grey background. The image does not cover the whole region, but it's fully <em>contained</em>._x000D_
  </p>_x000D_
</div>_x000D_
<div>_x000D_
  <div class="cover"></div>_x000D_
  <p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don't see the complete image anymore, but neither do you see any background color; the image <em>covers</em> all of the <code>&lt;div&gt;</code>.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to parse string into date?

You can use:

SELECT CONVERT(datetime, '24.04.2012', 103) AS Date

Reference: CAST and CONVERT (Transact-SQL)

How to make canvas responsive

You can have a responsive canvas in 3 short and simple steps:

  1. Remove the width and height attributes from your <canvas>.

    <canvas id="responsive-canvas"></canvas>
    
  2. Using CSS, set the width of your canvas to 100%.

    #responsive-canvas {
      width: 100%;
    }
    
  3. Using JavaScript, set the height to some ratio of the width.

    var canvas = document.getElementById('responsive-canvas');
    var heightRatio = 1.5;
    canvas.height = canvas.width * heightRatio;
    

How to hide keyboard in swift on pressing return key?

Swift 4.2 - No Delegate Needed

You can create an action outlet from the UITextField for the "Primary Action Triggered" and resign first responder on the sender parameter passed in:

Create Action Outlet

@IBAction func done(_ sender: UITextField) {
    sender.resignFirstResponder()
}

Super simple.

(Thanks to Scott Smith's 60-second video for tipping me off about this: https://youtu.be/v6GrnVQy7iA)

Anaconda vs. miniconda

Anaconda is a very large installation ~ 2 GB and is most useful for those users who are not familiar with installing modules or packages with other package managers.

Anaconda seems to be promoting itself as the official package manager of Jupyter. It's not. Anaconda bundles Jupyter, R, python, and many packages with its installation.

Anaconda is not necessary for installing Jupyter Lab or the R kernel. There is plenty of information available elsewhere for installing Jupyter Lab or Notebooks. There is also plenty of information elsewhere for installing R studio. The following shows how to install the R kernel directly from R Studio:

To install the R kernel, without Anaconda, start R Studio. In the R terminal window enter these three commands:

install.packages("devtools")
devtools::install_github("IRkernel/IRkernel")
IRkernel::installspec()

Done. Next time Jupyter is opened, the R kernel will be available.

Get DOM content of cross-domain iframe

You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.

EDIT

Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)

multiple packages in context:component-scan, spring config

Another general Annotation approach:

@ComponentScan(basePackages = {"x.y.z"})

PostgreSQL how to see which queries have run

PostgreSql is very advanced when related to logging techniques

Logs are stored in Installationfolder/data/pg_log folder. While log settings are placed in postgresql.conf file.

Log format is usually set as stderr. But CSV log format is recommended. In order to enable CSV format change in

log_destination = 'stderr,csvlog'   
logging_collector = on

In order to log all queries, very usefull for new installations, set min. execution time for a query

log_min_duration_statement = 0

In order to view active Queries on your database, use

SELECT * FROM pg_stat_activity

To log specific queries set query type

log_statement = 'all'           # none, ddl, mod, all

For more information on Logging queries see PostgreSql Log.

Python reshape list to ndim array

Step by step:

# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T 

#check the result
reshaped_array
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])

How to use format() on a moment.js duration?

You can use numeral.js to format your duration:

numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss

When to use static classes in C#

This is another old but very hot question since OOP kicked in. There are many reasons to use(or not) a static class, of course and most of them have been covered in the multitude of answers.

I will just add my 2 cents to this, saying that, I make a class static, when this class is something that would be unique in the system and that would really make no sense to have any instances of it in the program. However, I reserve this usage for big classes. I never declare such small classes as in the MSDN example as "static" and, certainly, not classes that are going to be members of other classes.

I also like to note that static methods and static classes are two different things to consider. The main disadvantages mentioned in the accepted answer are for static methods. static classes offer the same flexibility as normal classes(where properties and parameters are concerned), and all methods used in them should be relevant to the purpose of the existence of the class.

A good example, in my opinion, of a candidate for a static class is a "FileProcessing" class, that would contain all methods and properties relevant for the program's various objects to perform complex FileProcessing operations. It hardly has any meaning to have more than one instance of this class and being static will make it readily available to everything in your program.

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

What is the best way to measure execution time of a function?

Use a Profiler

Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.

The advantages they have is:

  • You can even get a statement level breakup
  • No changes required in your codebase
  • Instrumentions generally have very less overhead, hence very accurate results can be obtained.

There are many available open-source as well.

How to add an element at the end of an array?

You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :

public static void main(String[] args) {
    int[] array = new int[] {1, 2, 3};
    System.out.println(Arrays.toString(array));
    array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
    array[array.length - 1] = 4;
    System.out.println(Arrays.toString(array));
}

I would still recommend to drop working with an array and use a List.

adding multiple event listeners to one element

Semi-related, but this is for initializing one unique event listener specific per element.

You can use the slider to show the values in realtime, or check the console. On the <input> element I have a attr tag called data-whatever, so you can customize that data if you want to.

_x000D_
_x000D_
sliders = document.querySelectorAll("input");_x000D_
sliders.forEach(item=> {_x000D_
  item.addEventListener('input', (e) => {_x000D_
    console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);_x000D_
    item.nextElementSibling.textContent = e.target.value;_x000D_
  });_x000D_
})
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
}_x000D_
span {_x000D_
  padding-right: 30px;_x000D_
  margin-left: 5px;_x000D_
}_x000D_
* {_x000D_
  font-size: 12px_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">_x000D_
  <em>50</em>_x000D_
  <span>Size</span>_x000D_
  <br>_x000D_
  <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">_x000D_
  <em>50</em>_x000D_
  <span>OriginY</span>_x000D_
  <br>_x000D_
  <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">_x000D_
  <em>50</em>_x000D_
  <span>OriginX</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Open file dialog box in JavaScript

Simple answer .

(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"

(2) Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this- onclick="document.getElementById('myid').click()"

That is all.

Node.js - use of module.exports as a constructor

In my opinion, some of the node.js examples are quite contrived.

You might expect to see something more like this in the real world

// square.js
function Square(width) {

  if (!(this instanceof Square)) {
    return new Square(width);
  }

  this.width = width;
};

Square.prototype.area = function area() {
  return Math.pow(this.width, 2);
};

module.exports = Square;

Usage

var Square = require("./square");

// you can use `new` keyword
var s = new Square(5);
s.area(); // 25

// or you can skip it!
var s2 = Square(10);
s2.area(); // 100

For the ES6 people

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return Math.pow(this.width, 2);
  }
}

export default Square;

Using it in ES6

import Square from "./square";
// ...

When using a class, you must use the new keyword to instatiate it. Everything else stays the same.

How to Specify "Vary: Accept-Encoding" header in .htaccess

if anyone needs this for NGINX configuration file here is the snippet:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}

jQuery UI Tabs - How to Get Currently Selected Tab Index

If you're using JQuery UI version 1.9.0 or above, you can access ui.newTab.index() inside your function and get what you need.

For earlier versions use ui.index.

Replace whitespace with a comma in a text file in Linux

Try something like:

sed 's/[:space:]+/,/g' orig.txt > modified.txt

The character class [:space:] will match all whitespace (spaces, tabs, etc.). If you just want to replace a single character, eg. just space, use that only.

EDIT: Actually [:space:] includes carriage return, so this may not do what you want. The following will replace tabs and spaces.

sed 's/[:blank:]+/,/g' orig.txt > modified.txt

as will

sed 's/[\t ]+/,/g' orig.txt > modified.txt

In all of this, you need to be careful that the items in your file that are separated by whitespace don't contain their own whitespace that you want to keep, eg. two words.

What is the purpose of using -pedantic in GCC/G++ compiler?

Pedantic makes it so that the gcc compiler rejects all GNU C extensions not just the ones that make it ANSI compatible.

In Javascript/jQuery what does (e) mean?

DISCLAIMER: This is a very late response to this particular post but as I've been reading through various responses to this question, it struck me that most of the answers use terminology that can only be understood by experienced coders. This answer is an attempt to address the original question with a novice audience in mind.

Intro

The little '(e)' thing is actually part of broader scope of something in Javascript called an event handling function. Every event handling function receives an event object. For the purpose of this discussion, think of an object as a "thing" that holds a bunch of properties (variables) and methods (functions), much like objects in other languages. The handle, the 'e' inside the little (e) thing, is like a variable that allows you to interact with the object (and I use the term variable VERY loosely).

Consider the following jQuery examples:

$("#someLink").on("click", function(e){ // My preferred method
    e.preventDefault();
});

$("#someLink").click(function(e){ // Some use this method too
    e.preventDefault();
});

Explanation

  • "#someLink" is your element selector (which HTML tag will trigger this).
  • "click" is an event (when the selected element is clicked).
  • "function(e)" is the event handling function (on event, object is created).
  • "e" is the object handler (object is made accessible).
  • "preventDefault()" is a method (function) provided by the object.

What's happening?
When a user clicks on the element with the id "#someLink" (probably an anchor tag), call an anonymous function, "function(e)", and assign the resulting object to a handler, "e". Now take that handler and call one of its methods, "e.preventDefault()", which should prevent the browser from performing the default action for that element.

Note: The handle can pretty much be named anything you want (i.e. 'function(billybob)'). The 'e' stands for 'event', which seems to be pretty standard for this type of function.

Although 'e.preventDefault()' is probably the most common use of the event handler, the object itself contains many properties and methods that can be accessed via the event handler.

Some really good information on this topic can be found at jQuery's learning site, http://learn.jquery.com. Pay special attention to the Using jQuery Core and Events sections.

Why does printf not flush after the call unless a newline is in the format string?

There are generally 2 levels of buffering-

1. Kernel buffer Cache (makes read/write faster)

2. Buffering in I/O library (reduces no. of system calls)

Let's take example of fprintf and write().

When you call fprintf(), it doesn't wirte directly to the file. It first goes to stdio buffer in the program's memory. From there it is written to the kernel buffer cache by using write system call. So one way to skip I/O buffer is directly using write(). Other ways are by using setbuff(stream,NULL). This sets the buffering mode to no buffering and data is directly written to kernel buffer. To forcefully make the data to be shifted to kernel buffer, we can use "\n", which in case of default buffering mode of 'line buffering', will flush I/O buffer. Or we can use fflush(FILE *stream).

Now we are in kernel buffer. Kernel(/OS) wants to minimise disk access time and hence it reads/writes only blocks of disk. So when a read() is issued, which is a system call and can be invoked directly or through fscanf(), kernel reads the disk block from disk and stores it in a buffer. After that data is copied from here to user space.

Similarly that fprintf() data recieved from I/O buffer is written to the disk by the kernel. This makes read() write() faster.

Now to force the kernel to initiate a write(), after which data transfer is controlled by hardware controllers, there are also some ways. We can use O_SYNC or similar flags during write calls. Or we could use other functions like fsync(),fdatasync(),sync() to make the kernel initiate writes as soon as data is available in the kernel buffer.

CMD what does /im (taskkill)?

See the doc : it will close all running tasks using the executable file something.exe, more or less like linux' killall

How to empty the content of a div

If by saying without destroying it, you mean to a keep a reference to the children, you can do:

var oldChildren = [];

while(element.hasChildNodes()) {
    oldChildren.push(element.removeChild(element.firstChild));
}

Regarding the original tagging (html css) of your question:

You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:

#someID > * {
    display: none;
}

This doesn't work in IE6 though (but you could use #someID *).

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

How to make an installer for my C# application?

Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.

If you want something which is much more simpler, go with InnoSetup.

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

You can just turn on Github Pages. ^_^

Click on "Settings", than go to "GitHub Pages" and click on dropdown under "Source" and choose branch which you want to public (where main html file is located) aaaand vualaa. ^_^

How to embed fonts in CSS?

Try this link1,link2

@font-face {
        font-family: 'RieslingRegular';
        src: url('fonts/riesling.eot');
        src: local('Riesling Regular'), local('Riesling'), url('fonts/riesling.ttf')                       format('truetype');
    }

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Moment js date time comparison

Jsfiddle: http://jsfiddle.net/guhokemk/1/

 function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;
}

alert(compare("11/07/2015", "10/07/2015"));

The method returns 1 if dateTimeA is greater than dateTimeB

The method returns 0 if dateTimeA equals dateTimeB

The method returns -1 if dateTimeA is less than dateTimeB

JQuery Validate Dropdown list

$(document).ready(function(){
$("#HoursEntry").change(function(){
var HoursEntry = $(#HoursEntry option:selected).val();
if(HoursEntry == "")
{
$("#HoursEntry").html("Please select");
return false;
}
});
});

Finding the index of elements based on a condition using python list comprehension

For me it works well:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1, 2, 3])
>>> np.where(a > 2)[0]
[2 5]

Origin is not allowed by Access-Control-Allow-Origin

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Handling ExecuteScalar() when no results are returned

Always have a check before reading row.

if (SqlCommand.ExecuteScalar() == null)
{ 

}

opening a window form from another form programmatically

This might also help:

void ButtQuitClick(object sender, EventArgs e)
{
    QuitWin form = new QuitWin();
    form.Show();
}

Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.

When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.

Running shell command and capturing the output

just wrote a small bash script to do this using curl

https://gist.github.com/harish2704/bfb8abece94893c53ce344548ead8ba5

#!/usr/bin/env bash

# Usage: gdrive_dl.sh <url>

urlBase='https://drive.google.com'
fCookie=tmpcookies

curl="curl -L -b $fCookie -c $fCookie"
confirm(){
    $curl "$1" | grep jfk-button-action | sed -e 's/.*jfk-button-action" href="\(\S*\)".*/\1/' -e 's/\&amp;/\&/g'
}

$curl -O -J "${urlBase}$(confirm $1)"

Move div to new line

Try this

#movie_item {
    display: block;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
    background: red;
}

#movie_item_content {
    float: left;
    background: gold;
}

.movie_item_content_title {
    display: block;
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
    display: block;

}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

In Html

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
            <div class="movie_item_content_year">(1890-)</div>
        <div class="movie_item_content_title">title my film is a long word</div>
        <div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

I change position div year.

How to lose margin/padding in UITextView?

For SwiftUI

If you are making your own TextView using UIViewRepresentable and want to control the padding, in your makeUIView function, simply do:

uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)

or whatever you want.

PHP Fatal error: Cannot access empty property

As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps

How to store Java Date to Mysql datetime with JPA

java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());    
preparedStatement.setObject(param);

How to delete files recursively from an S3 bucket

With s3cmd package installed on a Linux machine, you can do this

s3cmd rm s3://foo/bar --recursive

How to add a string to a string[] array? There's no .Add function

Eazy

// Create list
var myList = new List<string>();

// Add items to the list
myList.Add("item1");
myList.Add("item2");

// Convert to array
var myArray = myList.ToArray();

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

ADB error: cannot connect to daemon

I had a couple of things open that prevented ADB from properly running. Specifically, I had BlueStacks Tweaker (to kill BlueStacks which runs in the background) and another program. Both use their own bundled adb.exe version for issuing commands. I was then also using my system's adb.exe. I had to close the other two programs in order to solve the problem. Restarting my computer would've also solved the problem (by closing those programs for me lol).

Angular and debounce

I solved this by writing a debounce decorator. The problem described could be solved by applying the @debounceAccessor to the property's set accessor.

I've also supplied an additional debounce decorator for methods, which can be useful for other occasions.

This makes it very easy to debounce a property or a method. The parameter is the number of milliseconds the debounce should last, 100 ms in the example below.

@debounceAccessor(100)
set myProperty(value) {
  this._myProperty = value;
}


@debounceMethod(100)
myMethod (a, b, c) {
  let d = a + b + c;
  return d;
}

And here's the code for the decorators:

function debounceMethod(ms: number, applyAfterDebounceDelay = false) {

  let timeoutId;

  return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
    let originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      if (timeoutId) return;
      timeoutId = window.setTimeout(() => {
        if (applyAfterDebounceDelay) {
          originalMethod.apply(this, args);
        }
        timeoutId = null;
      }, ms);

      if (!applyAfterDebounceDelay) {
        return originalMethod.apply(this, args);
      }
    }
  }
}

function debounceAccessor (ms: number) {

  let timeoutId;

  return function (target: Object, propName: string, descriptor: TypedPropertyDescriptor<any>) {
    let originalSetter = descriptor.set;
    descriptor.set = function (...args: any[]) {
      if (timeoutId) return;
      timeoutId = window.setTimeout(() => {
        timeoutId = null;
      }, ms);
      return originalSetter.apply(this, args);
    }
  }
}

I added an additional parameter for the method decorator which let's you trigger the method AFTER the debounce delay. I did that so I could for instance use it when coupled with mouseover or resize events, where I wanted the capturing to occur at the end of the event stream. In this case however, the method won't return a value.

Difference between Return and Break statements

In this code i is iterated till 3 then the loop ends;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         break;
      }
    }
}

In this code i is iterated till 3 but with an output;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         return i;
      }
    }
}

Node.js fs.readdir recursive directory search

Here is a simple synchronous recursive solution

const fs = require('fs')

const getFiles = path => {
    const files = []
    for (const file of fs.readdirSync(path)) {
        const fullPath = path + '/' + file
        if(fs.lstatSync(fullPath).isDirectory())
            getFiles(fullPath).forEach(x => files.push(file + '/' + x))
        else files.push(file)
    }
    return files
}

Usage:

const files = getFiles(process.cwd())

console.log(files)

You could write it asynchronously, but there is no need. Just make sure that the input directory exists and is accessible.

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

Match multiline text using regular expression

First, you're using the modifiers under an incorrect assumption.

Pattern.MULTILINE or (?m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).

Pattern.DOTALL or (?s) tells Java to allow the dot to match newline characters, too.

Second, in your case, the regex fails because you're using the matches() method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)* have matched.

So if you're simply looking for a string that starts with User Comments:, use the regex

^\s*User Comments:\s*(.*)

with the Pattern.DOTALL option:

Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
} 

ResultString will then contain the text after User Comments:

Start an activity from a fragment

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

Creating a UITableView Programmatically

- (void)viewDidLoad {
     [super viewDidLoad];
     arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
     tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];   
     tableview.delegate = self;
     tableview.dataSource = self;
     [self.view addSubview:tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    }

    cell.textLabel.text=[arr objectAtIndex:indexPath.row];

    return cell;
}

Why do I always get the same sequence of random numbers with rand()?

call srand(sameSeed) before calling rand(). More details here.

Why can't I have "public static const string S = "stuff"; in my Class?

C#'s const is the exact same thing as Java's final, except it's absolutely always static. In my opinion, it's not really necessary for a const variable to be non-static, but if you need to access a const variable non-static-ly, you can do:

class MyClass
{    
    private const int myLowercase_Private_Const_Int = 0;
    public const int MyUppercase_Public_Const_Int = 0;

    /*        
      You can have the `private const int` lowercase 
      and the `public int` Uppercase:
    */
    public int MyLowercase_Private_Const_Int
    {
        get
        {
            return MyClass.myLowercase_Private_Const_Int;
        }
    }  

    /*
      Or you can have the `public const int` uppercase 
      and the `public int` slighly altered
      (i.e. an underscore preceding the name):
    */
    public int _MyUppercase_Public_Const_Int
    {
        get
        {
            return MyClass.MyUppercase_Public_Const_Int;
        }
    } 

    /*
      Or you can have the `public const int` uppercase 
      and get the `public int` with a 'Get' method:
    */
    public int Get_MyUppercase_Public_Const_Int()
    {
        return MyClass.MyUppercase_Public_Const_Int;
    }    
}

Well, now I realize this question was asked 4 years ago, but since I put around 2 hours of work, consisting of trying all sorts of different ways of answering and code formatting, into this answer, I'm still posting it. :)

But, for the record, I still feel kinda silly.

How to input automatically when running a shell over SSH?

ssh-key with passphrase, with keychain

keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.

To enable keychain, install it and add something like the following to ~/.bash_profile:

eval keychain --agents ssh --eval id_rsa From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.

Got this info from;

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Hope this helps

I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)

  1. edit the bashrc file to add this script;

    Check if the SSH agent is awake

    if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi

    Above line will start the expect script upon terminal launch.

    ./ssh.exp

here's the content of this expect script

#!/usr/bin/expect

set timeout 20

set passphrase "test"

spawn "./keyadding.sh"

expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"

send "$passphrase\r";

interact

Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)

#!/bin/bash

ssh-add /the/path/of/yourkey_id_rsa

exit 0

I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp) and also a chmod +x script.sh to make it executable. A chmod +r term_boot.exp would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.

Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

Will certainly change my method for this one when I'll have the time.

Immutable vs Mutable types

Mutable means that it can change/mutate. Immutable the opposite.

Some Python data types are mutable, others not.

Let's find what are the types that fit in each category and see some examples.


Mutable

In Python there are various mutable types:

  • lists

  • dict

  • set

Let's see the following example for lists.

list = [1, 2, 3, 4, 5]

If I do the following to change the first element

list[0] = '!'
#['!', '2', '3', '4', '5']

It works just fine, as lists are mutable.

If we consider that list, that was changed, and assign a variable to it

y = list

And if we change an element from the list such as

list[0] = 'Hello'
#['Hello', '2', '3', '4', '5']

And if one prints y it will give

['Hello', '2', '3', '4', '5']

As both list and y are referring to the same list, and we have changed the list.


Immutable

In some programming languages one can define a constant such as the following

const a = 10

And if one calls, it would give an error

a = 20

However, that doesn't exist in Python.

In Python, however, there are various immutable types:

  • None

  • bool

  • int

  • float

  • str

  • tuple

Let's see the following example for strings.

Taking the string a

a = 'abcd'

We can get the first element with

a[0]
#'a'

If one tries to assign a new value to the element in the first position

a[0] = '!'

It will give an error

'str' object does not support item assignment

When one says += to a string, such as

a += 'e'
#'abcde'

It doesn't give an error, because it is pointing a to a different string.

It would be the same as the following

a = a + 'f'

And not changing the string.

Some Pros and Cons of being immutable

• The space in memory is known from the start. It would not require extra space.

• Usually, it makes things more efficiently. Finding, for example, the len() of a string is much faster, as it is part of the string object.

What does the following Oracle error mean: invalid column index

It sounds like you're trying to SELECT a column that doesn't exist.

Perhaps you're trying to ORDER BY a column that doesn't exist?

Any typos in your SQL statement?

Run .php file in Windows Command Prompt (cmd)

You should declare Environment Variable for PHP in path, so you could use like this:

C:\Path\to\somewhere>php cli.php

You can do it like this

How do I use StringUtils in Java?

java.lang does not contain a class called StringUtils. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.

Database design for a survey

As a general rule, modifying schema based on something that a user could change (such as adding a question to a survey) should be considered fairly smelly. There's cases where it can be appropriate, particularly when dealing with large amounts of data, but know what you're getting into before you dive in. Having just a "responses" table for each survey means that adding or removing questions is potentially very costly, and it's very difficult to do analytics in a question-agnostic way.

I think your second approach is best, but if you're certain you're going to have a lot of scale concerns, one thing that has worked for me in the past is a hybrid approach:

  1. Create detailed response tables to store per-question responses as you've described in 2. This data would generally not be directly queried from your application, but would be used for generating summary data for reporting tables. You'd probably also want to implement some form of archiving or expunging for this data.
  2. Also create the responses table from 1 if necessary. This can be used whenever users want to see a simple table for results.
  3. For any analytics that need to be done for reporting purposes, schedule jobs to create additional summary data based on the data from 1.

This is absolutely a lot more work to implement, so I really wouldn't advise this unless you know for certain that this table is going to run into massive scale concerns.

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Is a Java hashmap search really O(1)?

I know this is an old question, but there's actually a new answer to it.

You're right that a hash map isn't really O(1), strictly speaking, because as the number of elements gets arbitrarily large, eventually you will not be able to search in constant time (and O-notation is defined in terms of numbers that can get arbitrarily large).

But it doesn't follow that the real time complexity is O(n)--because there's no rule that says that the buckets have to be implemented as a linear list.

In fact, Java 8 implements the buckets as TreeMaps once they exceed a threshold, which makes the actual time O(log n).

%Like% Query in spring JpaRepository

answer exactly will be

-->` @Query("select u from Category u where u.categoryName like %:input%")
     List findAllByInput(@Param("input") String input);

How can I check if given int exists in array?

I think you are looking for std::any_of, which will return a true/false answer to detect if an element is in a container (array, vector, deque, etc.)

int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
    return i == val;
});

If you want to know where the element is, std::find will return an iterator to the first element matching whatever criteria you provide (or a predicate you give it).

int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
    // not found
}
else
{
    // found
}

How do I view cookies in Internet Explorer 11 using Developer Tools

Update 2018 for Microsoft Edge Developer Tools

The Dev Tools in Edge finally added support for managing and browsing cookies.

Note: Even if you are testing and supporting IE targets, you mine as well do the heavy lifting of your browser compatibility testing by leveraging the new tooling in Edge, and defer checking in IE 11 (etc) for the last leg.

Debugger Panel > Cookies Manager

Debugger Tab

Network Panel > Request Details > Cookies

Network Tab

The benefit, of course, to the debugger tab is you don't have to hunt and peck for individual cookies across multiple different and historical requests.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Apache is downloading php files instead of displaying them

When i upgraded from PHP 7.2 to PHP 7.4, i also got same issue. Worked by doing following:-

  1. In [domain].conf file, commented following:

    php_admin_value engine Off
    

    And Added:

    AddType  application/x-httpd-php-source  .phps
    AddType text/html .php
    
  2. Disable mod 7.2 and enable 7.4 by following:

    a2dismod php7.2
    a2enmod php7.4
    
  3. In /etc/apache2/mods-enabled/php7.4.conf file, comment following:

    SetHandler application/x-httpd-php
    php_admin_flag engine Off
    

Run JavaScript in Visual Studio Code

Another option is to use the developer tools console within Visual Studio Code. Simply select "Toggle Developer Tools" from the help menu and then select the "Console" tab in the developer tools that pop up. From there you have the same dev tools REPL that you get in Chrome.

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

This is another way to shuffle the data.frame using package dplyr:

row-wise:

df2 <- slice(df1, sample(1:n()))

or

df2 <- sample_frac(df1, 1L)

column-wise:

df2 <- select(df1, one_of(sample(names(df1)))) 

How to disable text selection using jQuery?

If you use jQuery UI, there is a method for that, but it can only handle mouse selection (i.e. CTRL+A is still working):

$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9

The code is realy simple, if you don't want to use jQuery UI :

$(el).attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', /* you could also put this in a class */
           '-webkit-user-select':'none',/* and add the CSS class here instead */
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

The request was rejected because no multipart boundary was found in springboot

The problem is that you are setting the Content-Type by yourself, let it be blank. Google Chrome will do it for you. The multipart Content-Type needs to know the file boundary, and when you remove the Content-Type, Postman will do it automagically for you.

NGINX to reverse proxy websockets AND enable SSL (wss://)?

Just to note that nginx has now support for Websockets on the release 1.3.13. Example of use:

location /websocket/ {

    proxy_pass ?http://backend_host;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;

}

You can also check the nginx changelog and the WebSocket proxying documentation.

IOError: [Errno 32] Broken pipe: Python

Closes should be done in reverse order of the opens.

How to set a default entity property value with Hibernate

You can use @PrePersist anotation and set the default value in pre-persist stage.

Something like that:

//... some code
private String myProperty;
//... some code

@PrePersist
public void prePersist() {
    if(myProperty == null) //We set default value in case if the value is not set yet.
        myProperty = "Default value";
}

// property methods
@Column(nullable = false) //restricting Null value on database level.
public String getMyProperty() {
    return myProperty;
}

public void setMyProperty(String myProperty) {
    this.myProperty= myProperty;
}

This method is not depend on database type/version underneath the Hibernate. Default value is set before persisting the mapping object.

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

MySQL Orderby a number, Nulls last

You can coalesce your NULLs in the ORDER BY statement:

select * from tablename
where <conditions>
order by
    coalesce(position, 0) ASC, 
    id DESC

If you want the NULLs to sort on the bottom, try coalesce(position, 100000). (Make the second number bigger than all of the other position's in the db.)

Converting java.util.Properties to HashMap<String,String>

this is only because the constructor of HashMap requires an arg of Map generic type and Properties implements Map.

This will work, though with a warning

    Properties properties = new Properties();
    Map<String, String> map = new HashMap(properties);

What is the point of WORKDIR on Dockerfile?

Be careful where you set WORKDIR because it can affect the continuous integration flow. For example, setting it to /home/circleci/project will cause error something like .ssh or whatever is the remote circleci is doing at setup time.

Pandas: Convert Timestamp to datetime.date

You can convert a datetime.date object into a pandas Timestamp like this:

#!/usr/bin/env python3
# coding: utf-8

import pandas as pd
import datetime

# create a datetime data object
d_time = datetime.date(2010, 11, 12)

# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')

# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)

# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)

# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)

Using app.config in .Net Core

To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.

protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");

To use the EF core SqlServer provider and compile the above code install the EF SqlServer package

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After compilation before running the code do the following for the first time

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

To run the code

dotnet run

"No such file or directory" error when executing a binary

You get this error when you try to run a 32-bit build on your 64-bit Linux.

Also contrast what file had to say on the binary you tried (ie: 32-bit) with what you get for your /bin/gzip:

$ file /bin/gzip
/bin/gzip: ELF 64-bit LSB executable, x64-64, version 1 (SYSV), \
dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

which is what I get on Ubuntu 9.10 for amd64 aka x86_64.

Edit: Your expanded post shows that as the readelf output also reflects a 32-bit build.

How to sort a List of objects by their date (java collections, List<Object>)

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

Persistent invalid graphics state error when using ggplot2

The solution is to simply reinstall ggplot2. Maybe there is an incompatibility between the R version you are using, and your installed version of ggplot2. Alternatively, something might have gone wrong while installing ggplot2 earlier, causing the issue you see.

Call external javascript functions from java code

Use ScriptEngine.eval(java.io.Reader) to read the script

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

'too many values to unpack', iterating over a dict. key=>string, value=>list

In Python3 iteritems() is no longer supported

Use .items

for field, possible_values in fields.items():
    print(field, possible_values)

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

When is layoutSubviews called?

Some of the points in BadPirate's answer are only partially true:

  1. For addSubView point

    addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.

    It depends on the view's (target view) autoresize mask. If it has autoresize mask ON, layoutSubview will be called on each addSubview. If it has no autoresize mask then layoutSubview will be called only when the view's (target View) frame size changes.

    Example: if you created UIView programmatically (it has no autoresize mask by default), LayoutSubview will be called only when UIView frame changes not on every addSubview.

    It is through this technique that the performance of the application also increases.

  2. For the device rotation point

    Rotating a device only calls layoutSubview on the parent view (the responding viewController's primary view)

    This can be true only when your VC is in the VC hierarchy (root at window.rootViewController), well this is most common case. In iOS 5, if you create a VC, but it is not added into any another VC, then this VC would not get any noticed when device rotate. Therefore its view would not get noticed by calling layoutSubviews.

python NameError: global name '__file__' is not defined

I think you can do this which get your local file path

if not os.path.isdir(f_dir):
    os.mkdirs(f_dir)

try:
    approot = os.path.dirname(os.path.abspath(__file__))
except NameError:
    approot = os.path.dirname(os.path.abspath(sys.argv[1]))
    my_dir= os.path.join(approot, 'f_dir')

C# find highest array value and index

If you know max index accessing the max value is immediate. So all you need is max index.

int max=0;

for(int i = 1; i < arr.Length; i++)
    if (arr[i] > arr[max]) max = i;

Add shadow to custom shape on Android

9 patch to the rescue, nice shadow could be achieved easily especially with this awesome tool -

Android 9-patch shadow generator

PS: if project won't be able to compile you will need to move black lines in android studio editor a little bit

Send data from a textbox into Flask?

This worked for me.

def parse_data():
    if request.method == "POST":
        data = request.get_json()
        print(data['answers'])
        return render_template('output.html', data=data)
$.ajax({
      type: 'POST',
      url: "/parse_data",
      data: JSON.stringify({values}),
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      success: function(data){
        // do something with the received data
      }
    });

How can I get the source directory of a Bash script from within the script itself?

One advantage of this method is that it doesn't involve anything outside Bash itself and does not fork any subshell neither.

First, use pattern substitution to replace anything not starting with / (i.e., a relative path) with $PWD/. Since we use a substitution to match the first character of $0, we also have to append it back (${0:0:1} in the substitution).

Now we have a full path to the script; we can get the directory by removing the last / and anything the follows (i.e., the script name). That directory can then be used in cd or as a prefix to other paths relative to your script.

#!/bin/bash

BIN=${0/#[!\/]/"$PWD/${0:0:1}"}
DIR=${BIN%/*}

cd "$DIR"

If your script may be sourced rather than executed, you can of course replace $0 with ${BASH_SOURCE[0]}, such as:

BIN=${BASH_SOURCE[0]/#[!\/]/"$PWD/${BASH_SOURCE[0]:0:1}"}

This will work for executable scripts too. It's longer, but more polyvalent.