Programs & Examples On #Finger tree

Apply function to each element of a list

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place

How can I return pivot table output in MySQL?

A stardard-SQL version using boolean logic:

SELECT company_name
     , COUNT(action = 'EMAIL' OR NULL) AS "Email"
     , COUNT(action = 'PRINT' AND pagecount = 1 OR NULL) AS "Print 1 pages"
     , COUNT(action = 'PRINT' AND pagecount = 2 OR NULL) AS "Print 2 pages"
     , COUNT(action = 'PRINT' AND pagecount = 3 OR NULL) AS "Print 3 pages"
FROM   tbl
GROUP  BY company_name;

SQL Fiddle.

How?

TRUE OR NULL yields TRUE.
FALSE OR NULL yields NULL.
NULL OR NULL yields NULL.
And COUNT only counts non-null values. Voilá.

calculate the mean for each column of a matrix in R

You can try this:

mean(as.matrix(cluster1))

Creating a mock HttpServletRequest out of a url string?

for those looking for a way to mock POST HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream from the HttpServletRequest

@Mock
private lateinit var request: HttpServletRequest

@Mock
private lateinit var response: HttpServletResponse

@Mock
private lateinit var chain: FilterChain

@InjectMocks
private lateinit var filter: ValidationFilter


@Test
fun `continue filter chain with valid json payload`() {
    val payload = """{
      "firstName":"aB",
      "middleName":"asdadsa",
      "lastName":"asdsada",
      "dob":null,
      "gender":"male"
    }""".trimMargin()

    whenever(request.requestURL).
        thenReturn(StringBuffer("/profile/personal-details"))
    whenever(request.method).
        thenReturn("PUT")
    whenever(request.inputStream).
        thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))

    filter.doFilter(request, response, chain)

    verify(chain).doFilter(request, response)
}

How do I set up Android Studio to work completely offline?

I'm using Android Studio 0.5.4 (Mavericks).

Preferences ? Gradle ? Global Gradle Settings ? Offline work

How do I convert a long to a string in C++?

You can use std::to_string in C++11

long val = 12345;
std::string my_val = std::to_string(val);

Adding :default => true to boolean in existing Rails column

If you just made a migration, you can rollback and then make your migration again.

To rollback you can do as many steps as you want:

rake db:rollback STEP=1

Or, if you are using Rails 5.2 or newer:

rails db:rollback STEP=1

Then, you can just make the migration again:

def change
  add_column :profiles, :show_attribute, :boolean, default: true
end

Don't forget to rake db:migrate and if you are using heroku heroku run rake db:migrate

Git merge error "commit is not possible because you have unmerged files"

So from the error above. All you have to do to fix this issue is to revert your code. (git revert HEAD) then git pull and then redo your changes, then git pull again and was able to commit or merge with no errors.

How to get the GL library/headers?

Some of the answers above, in regards to linux, are either incomplete, or flat out wrong.

For example, /usr/include/GL/gl.h is not part of mesa-common-dev or has not been for many years.

At any rate, for a more current answer, these two packages are important:

https://mesa.freedesktop.org/archive/mesa-20.1.2.tar.xz

ftp://ftp.freedesktop.org/pub/mesa/glu/glu-9.0.1.tar.xz

The glu.h is part of glu itself:

GL/glu.h
GL/glu_mangle.h

Mesa is evidently significantly larger. Its headers are a bit variable, I suppose, depending on the flags given to meson, but should include these typically:

KHR/khrplatform.h                                                                                                         
EGL/eglplatform.h                                                                                                         
EGL/eglext.h                                                                                                              
EGL/eglextchromium.h                                                                                                      
EGL/eglmesaext.h                                                                                                          
EGL/egl.h                                                                                                                 
vulkan/vulkan_intel.h
gbm.h
GLES3/gl31.h
GLES3/gl3ext.h
GLES3/gl3.h
GLES3/gl32.h
GLES3/gl3platform.h
xa_composite.h
xa_tracker.h
xa_context.h
GLES2/gl2.h
GLES2/gl2platform.h
GLES2/gl2ext.h
GLES/gl.h
GLES/glplatform.h
GLES/glext.h
GLES/egl.h
GL/gl.h
GL/glx.h
GL/osmesa.h
GL/internal
GL/internal/dri_interface.h
GL/glcorearb.h
GL/glxext.h
GL/glext.h

Hope that helps anyone finding an answer this question in the future; compiling dosbox needs this, for instance, due to SDL opengl.

What is the difference between new/delete and malloc/free?

also,

the global new and delete can be overridden, malloc/free cannot.

further more new and delete can be overridden per type.

Using classes with the Arduino

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:

By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.

Code:

#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); } 
void operator delete(void* ptr) { free(ptr); }

This let's you create objects, e.g.

C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory

Regards, tamberg

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

How to assign a NULL value to a pointer in python?

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

how to run two commands in sudo?

An alternative using eval so avoiding use of a subshell:

sudo -s eval 'whoami; whoami'

Note: The other answers using sudo -s fail because the quotes are being passed on to bash and run as a single command so need to strip quotes with eval. eval is better explained is this SO answer

Quoting within the commands is easier too:

$ sudo -s eval 'whoami; whoami; echo "end;"'
root
root
end;

And if the commands need to stop running if one fails use double-ampersands instead of semi-colons:

$ sudo -s eval 'whoami && whoamit && echo "end;"'
root
/bin/bash: whoamit: command not found

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

Count elements with jQuery

Yes, there is.

$('.MyClass').size()

Getting unique values in Excel by using formulas only

Drew Sherman's solution is very good, but the list must be contiguous (he suggests manually sorting, and that is not acceptable for me). Guitarthrower's solution is kinda slow if the number of items is large and don't respects the order of the original list: it outputs a sorted list regardless.

I wanted the original order of the items (that were sorted by the date in another column), and additionally I wanted to exclude an item from the final list not only if it was duplicated, but also for a variety of other reasons.

My solution is an improvement on Drew Sherman's solution. Likewise, this solution uses 2 columns for intermediate calculations:

Column A:

The list with duplicates and maybe blanks that you want to filter. I will position it in the A11:A1100 interval as an example, because I had trouble moving the Drew Sherman's solution to situations where it didn't start in the first line.

Column B:

This formula will output 0 if the value in this line is valid (contains a non-duplicated value). Note that you can add any other exclusion conditions that you want in the first IF, or as yet another outer IF.

=IF(ISBLANK(A11);1;IF(COUNTIF($A$11:A11;A11)=1;0;COUNTIF($A11:A$1100;A11)))

Use smart copy to populate the column.

Column C:

In the first line we will find the first valid line:

=MATCH(0;B11:B1100;0)

From that position, we search for the next valid value with the following formula:

=C11+MATCH(0;OFFSET($B$11:$B$1100;C11;0);0)

Put it in the second line and use smart copy to fill the rest of the column. This formula will output #N/D error when there is no more unique itens to point. We will take advantage of this in the next column.

Column D:

Now we just have to get the values pointed by column C:

=IFERROR(INDEX($A$11:$A$1100; C11); "")

Use smart copy to populate the column. This is the output unique list.

Google Android USB Driver and ADB

Can you give us a better description and an example of what you are doing? Because all i have to do is put the line in there for the device and then save the file. Now just reconnect the device and it works.

I usually use something similar to this line:

;
;some name for the phone (this seems to be arbitrary)
%CompositeAdbInterface%     = USB_Install, THE_HARDWARE_ID

What i do, is:

  1. plug the device into the computer.
  2. Go to your device manager.
  3. Right click on the device that you plugged up.
  4. Go to properties. Then select Hardware Ids.
  5. Then get that value that is listed there.
  6. Now add it to the line you created in the android_winusb.inf.
  7. Unplug the device and plug back in
  8. Go back to the device manager
  9. Right click on the device and click update or install driver
  10. Select search your computer for the driver
  11. Select the directory Your_Android_SDK_Directory/extras/google/usb_driver/
  12. Press ok

That seems to always work for me, is that what you are doing? Or does this even help?

How to determine the screen width in terms of dp or dip at runtime in Android?

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

FirstOrDefault: Default value other than null

You can also do this

    Band[] objects = { new Band { Name = "Iron Maiden" } };
    first = objects.Where(o => o.Name == "Slayer")
        .DefaultIfEmpty(new Band { Name = "Black Sabbath" })
        .FirstOrDefault();   // returns "Black Sabbath" 

This uses only linq - yipee!

How to run a PowerShell script

Pretty easy. Right click the .ps1 file in Windows and in the shell menu click on Run with PowerShell.

How do I order my SQLITE database in descending order, for an android app?

We have one more option to do order by

public Cursor getlistbyrank(String rank) {
        try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
        } catch (SQLException sqle) {
            Log.e("Exception on query:-", "" + sqle.getMessage());
            return null;
        }
    }

You can use this two method for order

How do I make a relative reference to another workbook in Excel?

I had a similar problem that I solved by using the following sequence:

  1. use the CELL("filename") function to get the full path to the current sheet of the current file.

  2. use the SEARCH() function to find the start of the [FileName]SheetName string of your current excel file and the sheet.

  3. use the LEFT function to extract the full path name of the directory that contains your current file.

  4. Concatenate the directory path name found in step #3 with the name of the file, the name of the worksheet, and the cell reference that you want to access.

  5. use the INDIRECT() function to access the CellPathName that you created in step #4.

Note: these same steps can also be used to access cells in files whose names are created dynamically. In step #4, use a text string that is dynamically created from the contents of cells, the current date or time, etc. etc.

A cell reference example (with each piece assembled separately) that includes all of these steps is:

=INDIRECT("'" & LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "[" & "OtherFileName" & "]" & "OtherSheetName" & "'!" & "$OtherColumn$OtherRow" & "'")

Note that LibreOffice uses a slightly different CellPatnName syntax, as in the following example:

=INDIRECT(LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "OtherFileName" & "'#$" & "OtherSheetName" & "." & "$OtherColumn$OtherRow")

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Angular ui-grid dynamically calculate height of the grid

following @tony's approach, changed the getTableHeight() function to

<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>

getTableHeight() {
    var offsetValue = 365;
    return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}

the grid would have a dynamic height with regards to window height as well.

How to change background Opacity when bootstrap modal is open

The problem with overriding using !important is that you will loose the fade in effect.

So the actual best trick to change the modal-backdrop opacity without breaking the fadeIn effect and without having to use the shameless !important is to use this :

.modal-backdrop{
  opacity:0; transition:opacity .2s;
}
.modal-backdrop.in{
  opacity:.7;
}

@sass

.modal-backdrop{
  opacity:0; transition:opacity .2s;
  &.in{opacity:.7;}
}

Simple and clean.

Manually type in a value in a "Select" / Drop-down HTML list?

Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.

Example: http://jsfiddle.net/c258Q/

HTML code:

Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
    <option value="apple">Apple</option>
    <option value="orange">Apricot </option>
    <option value="melon">Peach</option>
    <option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>

JavaScript:

function DropDownChanged(oDDL) {
    var oTextbox = oDDL.form.elements["fruit_txt"];
    if (oTextbox) {
        oTextbox.style.display = (oDDL.value == "") ? "" : "none";
        if (oDDL.value == "")
            oTextbox.focus();
    }
}

function FormSubmit(oForm) {
    var oHidden = oForm.elements["fruit"];
    var oDDL = oForm.elements["fruit_ddl"];
    var oTextbox = oForm.elements["fruit_txt"];
    if (oHidden && oDDL && oTextbox)
        oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}

And in the server side, read the value of "fruit" from the Request.

Send data from activity to fragment in Android

I´ve found a lot of answers here @ stackoverflow.com but definitely this is the correct answer of:

"Sending data from activity to fragment in android".

Activity:

        Bundle bundle = new Bundle();
        String myMessage = "Stackoverflow is cool!";
        bundle.putString("message", myMessage );
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

Fragment:

Reading the value in the fragment

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
        ...
        ...
        ...
        }

or just

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }

could not access the package manager. is the system running while installing android application

Facing Same issues following Link helped solving the problem. The above solutions were not helpful for me. deployment-failed-could-not-access-the-package-manager-is-the-system-running

By restarting server using CMD application was back to work. Open cmd (Run as administrator), open this

cd C:\Program Files (x86)\Android\android-sdk\platform-tools

(this path must specify your android-sdk installation folder )

Now, first write, adb kill-server and then adb start-server.

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

I had this issue while running MySQL on Minikube (Ubuntu box) and I solved it with:

sudo ln -s /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/
sudo apparmor_parser -R /etc/apparmor.d/usr.sbin.mysqld

libpng warning: iCCP: known incorrect sRGB profile

Thanks to the fantastic answer from Glenn, I used ImageMagik's "mogrify *.png" functionality. However, I had images buried in sub-folders, so I used this simple Python script to apply this to all images in all sub-folders and thought it might help others:

import os
import subprocess

def system_call(args, cwd="."):
    print("Running '{}' in '{}'".format(str(args), cwd))
    subprocess.call(args, cwd=cwd)
    pass

def fix_image_files(root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        # sys.stdout.write('.')
        for dir in dirs:
            system_call("mogrify *.png", "{}".format(os.path.join(path, dir)))


fix_image_files(os.curdir)

How to run a command in the background on Windows?

I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:

  • Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).

  • Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run("C:\yourbatch.bat"), 0, True
    

    You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.

  • Worst: Start the command using the startup folder. This runs when a user logs into the computer

Hope that helps some!

How to remove a class from elements in pure JavaScript?

It's 2021... keep it simple.

Times have changed and now the cleanest and most readable way to do this is:

Array.from(document.querySelectorAll('widget hover')).forEach((el) => el.classList.remove('hover'));

If you can't support arrow functions then just convert it like this:

Array.from(document.querySelectorAll('widget hover')).forEach(function(el) { 
    el.classList.remove('hover');
});

Additionally if you need to support extremely old browsers then use a polyfil for the forEach and Array.from and move on with your life.

How to insert a newline in front of a pattern?

sed -e 's/regexp/\0\n/g'

\0 is the null, so your expression is replaced with null (nothing) and then...
\n is the new line

On some flavors of Unix doesn't work, but I think it's the solution to your problem.

echo "Hello" | sed -e 's/Hello/\0\ntmow/g'
Hello
tmow

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}

Is there any way to kill a Thread?

Just to build up on @SCB's idea (which was exactly what I needed) to create a KillableThread subclass with a customized function:

from threading import Thread, Event

class KillableThread(Thread):
    def __init__(self, sleep_interval=1, target=None, name=None, args=(), kwargs={}):
        super().__init__(None, target, name, args, kwargs)
        self._kill = Event()
        self._interval = sleep_interval
        print(self._target)

    def run(self):
        while True:
            # Call custom function with arguments
            self._target(*self._args)

            # If no kill signal is set, sleep for the interval,
            # If kill signal comes in while sleeping, immediately
            #  wake up and handle
            is_killed = self._kill.wait(self._interval)
            if is_killed:
                break

        print("Killing Thread")

    def kill(self):
        self._kill.set()

if __name__ == '__main__':

    def print_msg(msg):
        print(msg)

    t = KillableThread(10, print_msg, args=("hello world"))
    t.start()
    time.sleep(6)
    print("About to kill thread")
    t.kill()

Naturally, like with @SBC, the thread doesn't wait to run a new loop to stop. In this example, you would see the "Killing Thread" message printed right after the "About to kill thread" instead of waiting for 4 more seconds for the thread to complete (since we have slept for 6 seconds already).

Second argument in KillableThread constructor is your custom function (print_msg here). Args argument are the arguments that will be used when calling the function (("hello world")) here.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I have same issue while implementing a tutorial for beginners of MVC. I got various suggestion to modify the @RenderSection in your layout.cshtml file but I havn't use it.

I have search a lot and then I found that the script tag generated in a (View/Edit.cshtml) and other cshtml file is not rendering

**@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

}**

So I removed those lines and application start running smoothly.

Peak memory usage of a linux/unix process

Valgrind one-liner:

valgrind --tool=massif --pages-as-heap=yes --massif-out-file=massif.out ./test.sh; grep mem_heap_B massif.out | sed -e 's/mem_heap_B=\(.*\)/\1/' | sort -g | tail -n 1

Note use of --pages-as-heap to measure all memory in a process. More info here: http://valgrind.org/docs/manual/ms-manual.html

This will slow down your command significantly.

Ruby send JSON request

HTTParty makes this a bit easier I think (and works with nested json etc, which didn't seem to work in other examples I've seen.

require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: '[email protected]', password: 'secret'}}).body

Get user's current location

MaxMind GeoIP is a good service. They also have a free city-level lookup service.

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

ToggleButton in C# WinForms

You can always code your own button with custom graphics and a PictureBox, though it won't necessarily match the Windows theme of your users.

What is the size of column of int(11) in mysql in bytes?

According to here, int(11) will take 4 bytes of space that is 32 bits of space with 2^(31) = 2147483648 max value and -2147483648min value. One bit is for sign.

How to get just the parent directory name of a specific file

In Java 7 you have the new Paths api. The modern and cleanest solution is:

Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();

Result would be:

C:/aaa/bbb/ccc/ddd

Impersonate tag in Web.Config

You had the identity node as a child of authentication node. That was the issue. As in the example above, authentication and identity nodes must be children of the system.web node

How to change fontFamily of TextView in Android

Android doesn't allow you to set custom fonts from the XML layout. Instead, you must bundle the specific font file in your app's assets folder, and set it programmatically. Something like:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

Note that you can only run this code after setContentView() has been called. Also, only some fonts are supported by Android, and should be in a .ttf (TrueType) or .otf (OpenType) format. Even then, some fonts may not work.

This is a font that definitely works on Android, and you can use this to confirm that your code is working in case your font file isn't supported by Android.

Android O Update: This is now possible with XML in Android O, based on Roger's comment.

Message Queue vs. Web Services?

Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.

Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.

Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.

Java Package Does Not Exist Error

I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!

What REALLY happens when you don't free after malloc?

You are correct, memory is automatically freed when the process exits. Some people strive not to do extensive cleanup when the process is terminated, since it will all be relinquished to the operating system. However, while your program is running you should free unused memory. If you don't, you may eventually run out or cause excessive paging if your working set gets too big.

How to use Apple's new San Francisco font on a webpage

Apple's new system font is not publicly exposed. Apple has started abstracting system font names:

The motivation for this abstraction is so the operating system can make better choices on which face to use at a given weight. Apple is also working on font features, such as selectable “6" and “9" glyphs or non-monospaced numbers. It’s my guess that they’d like to bring these features to the web, as well.

Safari and Firefox use SF for -apple-system; Chrome recognizes BlinkMacSystemFont:

body {
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

There are also other variations:

font-family: -apple-system-body
font-family: -apple-system-headline
font-family: -apple-system-subheadline
font-family: -apple-system-caption1
font-family: -apple-system-caption2
font-family: -apple-system-footnote
font-family: -apple-system-short-body
font-family: -apple-system-short-headline
font-family: -apple-system-short-subheadline
font-family: -apple-system-short-caption1
font-family: -apple-system-short-footnote
font-family: -apple-system-tall-body

You can demo these at the following fiddle; most are not supported yet: http://jsfiddle.net/v94gw9nx/

I got my info from Craig Hockenberry's article which has a lot of great info about using the font: http://furbo.org/2015/07/09/i-left-my-system-fonts-in-san-francisco/

Also, some great info on the Surfin' Safari blog about using abstracted system fonts: https://www.webkit.org/blog/3709/using-the-system-font-in-web-content/

And apparently Apple is working with the W3C to standardize using a generic "system" font name in CSS. https://lists.w3.org/Archives/Public/www-style/2015Jul/0169.html

Download the SF font .otf files for your own personal use: https://developer.apple.com/fonts/

Get Selected value from dropdown using JavaScript

The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );

You should also try and clean up your if statement by declaring a variable for the answer separately.

function answers() {

var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;

    if(answer == "To measure time"){
        alert("Thats correct"); 
    }

}

http://jsfiddle.net/zpdEp/

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

Cookies vs. sessions

I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

in Xcode 8 use:

DispatchQueue.global(qos: .userInitiated).async { }

Why do we use __init__ in Python classes?

Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).

When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__.

Basically __init__ sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits).

Capturing a form submit with jquery and .submit

try this:

Use ´return false´ for to cut the flow of the event:

$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

Edit

corroborate if the form element with the 'length' of jQuery:

alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
    var data = $("#login_form :input").serializeArray();
    alert('Handler for .submit() called.');
    return false;  // <- cancel event
});

OR:

it waits for the DOM is ready:

jQuery(function() {

    alert($('#login_form').length) // if is == 0, not found form
    $('#login_form').submit(function() {
        var data = $("#login_form :input").serializeArray();
        alert('Handler for .submit() called.');
        return false;  // <- cancel event
    });

});

Do you put your code inside the event "ready" the document or after the DOM is ready?

Unable to auto-detect email address

it's pretty simple but tricky at the first time.
For example:
If my email is [email protected] type:

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

OR

If my username is mrsuicidesheep type:

git config user.name mrsuicidesheep

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

Invalid application path

Problem was installing iis manager after .net framework aspnet_regiis had run. Run run aspnet_regiis from x64 .net framework directory

aspnet_regiis -iru // From x64 .net framework directory

IIS Manager can't configure .NET Compilation on .NET 4 Applications

Can an Android NFC phone act as an NFC tag?

Read here: http://groups.google.com/group/android-developers/browse_thread/thread/d5fc35a9f16aa467/dec4843abd73d9e9%3Flnk%3Dgst%26q%3Dsecure%2Belement%2Bdiff%2527s%23dec4843abd73d9e9?pli=1

I've not verified that myself but it looks like people managed to include the hidden code into Android again. They seem to be able to emulate a Mifare Classic card (iso-14443). I'll soon test this myself, it looks very interesting.

If you want to do it for a commercial/free app you'll have a hard time, your users won't like to change their kernel to support your app.

Update: There would be a simple trick to make your phone emulate a ticket:
You can get a NFC-sticker and put it in or on the phone. This way you are able to read and write it at all times and other devices can also read and write it.
It's just an idea I had, never seen that used anywhere of course ;)

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Unexpected end of file error

I encountered that error when I forgot to uncheck the Precompiled header from the additional options in the wizard after naming a new Win32 console application.

Because I don't need stdafx.h library, I removed it by going to Project menu, then click Properties or [name of our project] Properties or simply press Alt + F7. On the dropdownlist beside configuration, select All Configurations. Below that, is a tree node, click Configuration Properties, then C/C++. On the right pane, select Create/Use Precompiled Header, and choose Not using Precompiled Header.

Best data type to store money values in MySQL

Since money needs an exact representation don't use data types that are only approximate like float. You can use a fixed-point numeric data type for that like

decimal(15,2)
  • 15 is the precision (total length of value including decimal places)
  • 2 is the number of digits after decimal point

See MySQL Numeric Types:

These types are used when it is important to preserve exact precision, for example with monetary data.

How do I check for null values in JavaScript?

You can check if some value is null as follows

[pass,cpass,email,cemail,user].some(x=> x===null) 

_x000D_
_x000D_
let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;

if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {     
    alert("fill all columns");
    //return false;  
}   
_x000D_
_x000D_
_x000D_

BONUS: Why === is more clear than == (source)

a == b

Enter image description here

a === b

Enter image description here

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

Step 1

My computer > properties > Advance system settings

Step 2

environment variables > click New button under user variables > Enter variable name as 'PATH'

Copy the location of java bin (e.g:C:\Program Files\Java\jdk1.8.0_121\bin) and paste it in Variable value and click OK Now open the eclipse.

In C# check that filename is *possibly* valid (not that it exists)

This will get you the drives on the machine:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();

How to run a single test with Mocha?

For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.

describe('My Test Description', () => {
  it('test case 1', () => {
    // My test code
  })
  it('test case 2', () => {
  // My test code
  })
})

then run

yarn test -g "My Test Description"

or

npm run test -g "My Test Description"

Manually Triggering Form Validation using jQuery

_x000D_
_x000D_
var field = $("#field")_x000D_
field.keyup(function(ev){_x000D_
    if(field[0].value.length < 10) {_x000D_
        field[0].setCustomValidity("characters less than 10")_x000D_
        _x000D_
    }else if (field[0].value.length === 10) {_x000D_
        field[0].setCustomValidity("characters equal to 10")_x000D_
        _x000D_
    }else if (field[0].value.length > 10 && field[0].value.length < 20) {_x000D_
        field[0].setCustomValidity("characters greater than 10 and less than 20")_x000D_
        _x000D_
    }else if(field[0].validity.typeMismatch) {_x000D_
     field[0].setCustomValidity("wrong email message")_x000D_
        _x000D_
    }else {_x000D_
     field[0].setCustomValidity("") // no more errors_x000D_
        _x000D_
    }_x000D_
    field[0].reportValidity()_x000D_
    _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="email" id="field">
_x000D_
_x000D_
_x000D_

How to create <input type=“text”/> dynamically

With JavaScript:

var input = document.createElement("input");
input.type = "text";
input.className = "css-class-name"; // set the CSS class
container.appendChild(input); // put it into the DOM

Java: Instanceof and Generics

The runtime type of the object is a relatively arbitrary condition to filter on. I suggest keeping such muckiness away from your collection. This is simply achieved by having your collection delegate to a filter passed in a construction.

public interface FilterObject {
     boolean isAllowed(Object obj);
}

public class FilterOptimizedList<E> implements List<E> {
     private final FilterObject filter;
     ...
     public FilterOptimizedList(FilterObject filter) {
         if (filter == null) {
             throw NullPointerException();
         }
         this.filter = filter;
     }
     ...
     public int indexOf(Object obj) {
         if (!filter.isAllows(obj)) {
              return -1;
         }
         ...
     }
     ...
}

     final List<String> longStrs = new FilterOptimizedList<String>(
         new FilterObject() { public boolean isAllowed(Object obj) {
             if (obj == null) {
                 return true;
             } else if (obj instanceof String) {
                 String str = (String)str;
                 return str.length() > = 4;
             } else {
                 return false;
             }
         }}
     );

Array inside a JavaScript Object?

// define
var foo = {
  bar: ['foo', 'bar', 'baz']
};

// access
foo.bar[2]; // will give you 'baz'

Set Session variable using javascript in PHP

You can't directly manipulate a session value from Javascript - they only exist on the server.

You could let your Javascript get and set values in the session by using AJAX calls though.

See also

Why doesn't wireshark detect my interface?

On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:

sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly.

The system cannot find the file specified. in Visual Studio

I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

How to compile C programming in Windows 7?

You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".

default select option as blank

Maybe this will be helpful

<select>
    <option disabled selected value> -- select an option -- </option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

-- select an option -- Will be displayed by default. But if you choose an option,you will not be able select it back.

You can also hide it using by adding an empty option

<option style="display:none">

so it won't show up in the list anymore.

Option 2

If you don't want to write CSS and expect the same behaviour of the solution above, just use:

<option hidden disabled selected value> -- select an option -- </option>

What is console.log in jQuery?

jQuery and console.log are unrelated entities, although useful when used together.

If you use a browser's built-in dev tools, console.log will log information about the object being passed to the log function.

If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:

if (window.console) console.log('foo');

The shortcut form of this might be seen instead:

window.console&&console.log('foo');

There are other useful debugging functions as well, such as debug, dir and error. Firebug's wiki lists the available functions in the console api.

Get characters after last / in url

Two one liners - I suspect the first one is faster but second one is prettier and unlike end() and array_pop(), you can pass the result of a function directly to current() without generating any notice or warning since it doesn't move the pointer or alter the array.

$var = 'http://www.vimeo.com/1234567';

// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0));

// VERSION 2 - explode, reverse the array, get the first index.
echo current(array_reverse(explode('/',$var)));

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();

What is the difference between a data flow diagram and a flow chart?

A DFD shows how the data moves through a system, a flowchart is closer to the operations that system does.

In the classic make a cup of tea example, a DFD would show where the water, tea, milk, sugar were going, whereas the flowchart shows the process.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check:

Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect.

You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in Control Panel > ODBC Drivers > New

batch file to copy files to another location?

Two approaches:

  • When you login: you can to create a copy_my_files.bat file into your All Programs > Startup folder with this content (its a plain text document):

    • xcopy c:\folder\*.* d:\another_folder\.

    Use xcopy c:\folder\*.* d:\another_folder\. /Y to overwrite the file without any prompt.

  • Everytime a folder changes: if you can to use C#, you can to create a program using FileSystemWatcher

How to Insert Double or Single Quotes

Easier steps:

  1. Highlight the cells you want to add the quotes.
  2. Go to Format–>Cells–>Custom
  3. Copy/Paste the following into the Type field: \"@\" or \'@\'
  4. Done!

Why compile Python code?

Yep, performance is the main reason and, as far as I know, the only reason.

If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

My favorite no-conflict-friendly construct:

jQuery(function($) {
  // ...
});

Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

Or as we say in coffeescript:

jQuery ($) ->
  # code here

Trim a string in C

/* iMode 0:ALL, 1:Left, 2:Right*/
char* Trim(char* szStr,const char ch, int iMode)
{
    if (szStr == NULL)
        return NULL;
    char szTmp[1024*10] = { 0x00 };
    strcpy(szTmp, szStr);
    int iLen = strlen(szTmp);
    char* pStart = szTmp;
    char* pEnd = szTmp+iLen;
    int i;
    for(i = 0;i < iLen;i++){
        if (szTmp[i] == ch && pStart == szTmp+i && iMode != 2)
            ++pStart;
        if (szTmp[iLen-i-1] == ch && pEnd == szTmp+iLen-i && iMode != 1)
            *(--pEnd) = '\0';
    }
    strcpy(szStr, pStart);
    return szStr;
}

Java 8 lambda get and remove element from list

To Remove element from the list

objectA.removeIf(x -> conditions);

eg:

objectA.removeIf(x -> blockedWorkerIds.contains(x));

List<String> str1 = new ArrayList<String>();
str1.add("A");
str1.add("B");
str1.add("C");
str1.add("D");

List<String> str2 = new ArrayList<String>();
str2.add("D");
str2.add("E");

str1.removeIf(x -> str2.contains(x)); 

str1.forEach(System.out::println);

OUTPUT: A B C

Who is listening on a given TCP port on Mac OS X?

on OS X you can use the -v option for netstat to give the associated pid.

type:

netstat -anv | grep [.]PORT

the output will look like this:

tcp46      0      0  *.8080                 *.*                    LISTEN      131072 131072   3105      0

The PID is the number before the last column, 3105 for this case

How do I convert a datetime to date?

import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
    print datetime.datetime.fromtimestamp(dt).date()

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

How to wait for all threads to finish, using ExecutorService?

Follow one of below approaches.

  1. Iterate through all Future tasks, returned from submit on ExecutorService and check the status with blocking call get() on Future object as suggested by Kiran
  2. Use invokeAll() on ExecutorService
  3. CountDownLatch
  4. ForkJoinPool or Executors.html#newWorkStealingPool
  5. Use shutdown, awaitTermination, shutdownNow APIs of ThreadPoolExecutor in proper sequence

Related SE questions:

How is CountDownLatch used in Java Multithreading?

How to properly shutdown java ExecutorService

How to use OKHTTP to make a post request?

You can make it like this:

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

            Log.e("HttpService", "onFailure() Request was: " + request);

            e.printStackTrace();
        }

        @Override
        public void onResponse(Response r) throws IOException {

            response = r.body().string();

            Log.e("response ", "onResponse(): " + response );

        }
    });

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    

HTML5 image icon to input placeholder

`CSS:

input#search{
 background-image: url(bg.jpg);
 background-repeat: no-repeat;
 text-indent: 20px;
}

input#search:focus{
 background-image:none;
}

HTML:

<input type="text" id="search" name="search" value="search" />`

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

How can I pass an argument to a PowerShell script?

Call the script from a batch file (*.bat) or CMD

PowerShell Core

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

PowerShell

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

Call from PowerShell

PowerShell Core or Windows PowerShell

& path-to-script/Script.ps1 -Param1 Hello -Param2 World
& ./Script.ps1 -Param1 Hello -Param2 World

Script.ps1 - Script Code

param(
    [Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
    [System.String]
    $Param1,

    [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
    [System.String]
    $Param2
)

Write-Host $Param1
Write-Host $Param2

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Recheck the package declarations in all your classes!

This behaviour has been observed in NetBeans, when the package declaration in one of the classes of the package refers to a non-existent or wrong package. NetBeans normally detects and highlights this error but has been known to fail and misleadingly report the package as free of errors when this is not the case.

Can table columns with a Foreign Key be NULL?

I found that when inserting, the null column values had to be specifically declared as NULL, otherwise I would get a constraint violation error (as opposed to an empty string).

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}

Regex lookahead, lookbehind and atomic groups

Examples

Given the string foobarbarfoo:

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)

You can also combine them:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

  • (foo|foot)s applied to foots will:

    1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
    2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

Some resources

Online testers

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

I changed the installation directory on re-install, and it worked.

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

How to force cp to overwrite without confirmation

I simply used unalias to remove the "cp -i" alias, then do the copy, then set back the alias. :

unalias cp  
cp -f foo foo.copy  
alias cp="cp -i"  

Not the most beautiful code, but easy to set and efficient. I also check the alias is already set back with a simple

alias |grep cp

Array vs ArrayList in performance

Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance.

Sorting a DropDownList? - C#, ASP.NET

If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.

editing PATH variable on mac

You could try this:

  1. Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
  2. Type the following: echo 'export PATH=YOURPATHHERE:$PATH' >> ~/.profile, replacing "YOURPATHHERE" with the name of the directory you want to add. Make certain that you use ">>" instead of one ">".
  3. Hit Enter.
  4. Close the Terminal and reopen. Your new Terminal session should now use the new PATH.

-> http://keito.me/tutorials/macosx_path

White space showing up on right side of page when background image should extend full length of page

This question has been hanging around for a while, but none of the fixes I could find worked for me (having the same issue with ipad), but I managed my own solution which should work for most people I imagine.

Here's my code:

html {
   background: url("../images/blahblah.jpg") repeat-y;
   min-width: 100%;
   background-size: contain;
}

Enjoy!

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

How to set back button text in Swift

The back button belongs to the previous view controller, not the one currently presented on screen. To modify the back button you should update it before pushing, add viewdidload :

Swift 4:

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)

Commenting multiple lines in DOS batch file

If you want to add REM at the beginning of each line instead of using GOTO, you can use Notepad++ to do this easily following these steps:

  1. Select the block of lines
  2. hit Ctrl-Q

Repeat steps to uncomment

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

How to set Navigation Drawer to be opened from right to left

SOLUTION


your_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="end">

    <include layout="@layout/app_bar_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:fitsSystemWindows="true"
        app:itemTextColor="@color/black"
        app:menu="@menu/activity_root_drawer" />

</android.support.v4.widget.DrawerLayout>

YourActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
//...
toolbar = (Toolbar) findViewById(R.id.toolbar);

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (drawer.isDrawerOpen(Gravity.RIGHT)) {
                drawer.closeDrawer(Gravity.RIGHT);
            } else {
                drawer.openDrawer(Gravity.RIGHT);
            }
        }
    });
//...
}

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

I had an issue where both debug and release build won't install on devices I used for debugging. The same msg would appear when trying to install the new version. The only workaround was to uninstall the current version and install the new one.

It looks like Android studio marks the apk it installs so that installation using the package managers would distinguish between version installed for debugging and versions downloaded from Google play or other external sources (this never happened to me when using eclipse).

Checking for Undefined In React

You can try adding a question mark as below. This worked for me.

 componentWillReceiveProps(nextProps) {
    this.setState({
        title: nextProps?.blog?.title,
        body: nextProps?.blog?.content
     })
    }

jQuery: how to change title of document during .ready()?

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

JavaScript: changing the value of onclick with or without jQuery

Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>

Hope this helps

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Log4j: How to configure simplest possible file logging?

Here is a log4j.properties file that I've used with great success.

logDir=/var/log/myapp

log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true

The DailyRollingFileAppender will create new files each day with file names that look like this:

myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log  <-- today's log

Each entry in the log file will will have this format:

01/30/2017 12:59:47 AM|INFO |Component1   | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2   | count=1 > 0, calling fooBar()

Set the location of the above file by using -Dlog4j.configuration, as mentioned in this posting:

java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp

In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.

private static final Logger LOGGER = Logger.getLogger("Component1");

public static void log(org.apache.log4j.Logger logger, String message) {

    logger.info(message);
    System.out.printf("%s\n", message);
}

public static String stackTraceToString(Exception ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    return sw.toString();
}

And then call it like so:

LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));

How to pass an array into a SQL Server stored procedure

Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;' in-which 123, 434 and 365 are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.

CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees  @List AS varchar(max)
AS
BEGIN
  SELECT EmployeeID 
  FROM EmployeesTable
  -- inner join AnotherTable on ...
  where @List like '%;'+cast(employeeID as varchar(20))+';%'
END
GO

Root element is missing

Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.

XDocument xDoc = XDocument.Load(xmlStream);  

Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!

if (xmlStream.Position > 0)
{
    xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream); 

Best Practice: Software Versioning

I would use x.y.z kind of versioning

x - major release
y - minor release
z - build number

How to minify php page html output?

You can use a well tested Java minifier like HTMLCompressor by invoking it using passthru (exec).
Remember to redirect console using 2>&1

This however may not be useful, if speed is a concern. I use it for static php output

jQuery ajax success callback function definition

I would write :

var handleData = function (data) {
    alert(data);
    //do some stuff
}


function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

the System.Web.SessionState.SessionStateBehavior enum has the following values:

  • Default
  • Disabled
  • ReadOnly
  • Required

How to restore the permissions of files and directories within git if they have been modified?

git diff -p used in muhqu's answer may not show all discrepancies.

  • saw this in Cygwin for files I didn't own
  • mode changes are ignored completely if core.filemode is false (which is the default for MSysGit)

This code reads the metadata directly instead:

(set -o errexit pipefail nounset;
git ls-tree HEAD -z | while read -r -d $'\0' mask type blob path
do
    if [ "$type" != "blob" ]; then continue; fi;
    case "$mask" in
    #do not touch other bits
    100644) chmod a-x "$path";;
    100755) chmod a+x "$path";;
    *) echo "invalid: $mask $type $blob\t$path" >&2; false;;
    esac
done)

A non-production-grade one-liner (replaces masks entirely):

git ls-tree HEAD | perl -ne '/^10(0\d{3}) blob \S+\t(.+)$/ && { system "chmod",$1,$2 || die }'

(Credit for "$'\0'" goes to http://transnum.blogspot.ru/2008/11/bashs-read-built-in-supports-0-as.html)

How to create a sticky navigation bar that becomes fixed to the top after scrolling

//in html

<nav class="navbar navbar-default" id="mainnav">
<nav>

// add in jquery

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  console.log(navpos.top);
    $(window).bind('scroll', function() {
      if ($(window).scrollTop() > navpos.top) {
       $('#mainnav').addClass('navbar-fixed-top');
       }
       else {
         $('#mainnav').removeClass('navbar-fixed-top');
       }
    });
});

Here is the jsfiddle to play around : -http://jsfiddle.net/shubhampatwa/46ovg69z/

EDIT: if you want to apply this code only for mobile devices the you can use:

   var newWindowWidth = $(window).width();
    if (newWindowWidth < 481) {
        //Place code inside it...
       }

How to perform an SQLite query within an Android application?

This will return you the required cursor

Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw"}, 
                "title_raw like " + "'%Smith%'", null, null, null, null);

How to use radio on change event?

$(document).ready(function () {
    $('#allot').click(function () {
        if ($(this).is(':checked')) {
            alert("Allot Thai Gayo Bhai");
        }
    });

    $('#transfer').click(function () {
        if ($(this).is(':checked')) {
            alert("Transfer Thai Gayo");
        }
    });
});

JS Fiddle

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The select statement in the cost part of your select is returning more than one value. You need to add more where clauses, or use an aggregation.

delete_all vs destroy_all?

To avoid the fact that destroy_all instantiates all the records and destroys them one at a time, you can use it directly from the model class.

So instead of :

u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all

You can do :

u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"

The result is one query to destroy all the associated records

Adding Table rows Dynamically in Android

Activity
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/mytable"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </TableLayout>
    </HorizontalScrollView>

Your Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testtable);
    table = (TableLayout)findViewById(R.id.mytable);
    showTableLayout();
}


public  void showTableLayout(){
    Date date = new Date();
    int rows = 80;
    int colums  = 10;
    table.setStretchAllColumns(true);
    table.bringToFront();

    for(int i = 0; i < rows; i++){

        TableRow tr =  new TableRow(this);
        for(int j = 0; j < colums; j++)
        {
            TextView txtGeneric = new TextView(this);
            txtGeneric.setTextSize(18);
            txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
            tr.addView(txtGeneric);
            /*txtGeneric.setHeight(30); txtGeneric.setWidth(50);   txtGeneric.setTextColor(Color.BLUE);*/
        }
        table.addView(tr);
    }
}

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

What to do with "Unexpected indent" in python?

There is a trick that always worked for me:

If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.

It happened to me when used vim, gedit or editors like that.

Try to use only 1 editor for your code.

Android Dialog: Removing title bar

use below code before setcontentview :-

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
dialog.setContentView(R.layout.custom_dialog);

Note:- above code must have to use above dialog.setContentView(R.layout.custom_dialog);

In XML use a theme

android:theme="@android:style/Theme.NoTitleBar"

also styles.xml:

<style name="hidetitle" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

And then:

Dialog dialog_hidetitle_example = new Dialog(context, R.style.hidetitle);

Forcing label to flow inline with input that they label

put them both inside a div with nowrap.

<div style="white-space:nowrap">
    <label for="id1">label1:</label>
    <input type="text" id="id1"/>
</div>

Converting a Pandas GroupBy output from Series to DataFrame

I found this worked for me.

import numpy as np
import pandas as pd

df1 = pd.DataFrame({ 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})

df1['City_count'] = 1
df1['Name_count'] = 1

df1.groupby(['Name', 'City'], as_index=False).count()

Blade if(isset) is not working Laravel

Use ?? , 'or' not supported in updated version.

{{ $usersType or '' }}  ?
{{ $usersType ?? '' }} ?

String.contains in Java

I will answer your question using a math analogy:

In this instance, the number 0 will represent no value. If you pick a random number, say 15, how many times can 0 be subtracted from 15? Infinite times because 0 has no value, thus you are taking nothing out of 15. Do you have difficulty accepting that 15 - 0 = 15 instead of ERROR? So if we switch this analogy back to Java coding, the String "" represents no value. Pick a random string, say "hello world", how many times can "" be subtracted from "hello world"?

How to remove focus border (outline) around text/input boxes? (Chrome)

This will definitely work. Orange outline will not show anymore.. Common for all tags:

*:focus {
    outline: none;
}

Specific to some tag, ex: input tag

input:focus {
   outline:none;
}

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

Unix ls command: show full path when using options

You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.

ls -lart `find . -type f -name "*" `

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

For me - using Spring Boot with MongoDB, the following was the Problem:

In my POM.xml I had:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-starter-data-mongodb</artifactId>
</dependency>

but I needed the following:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

(Short: Add "spring-boot-..." instead of only "spring-...")

'negative' pattern matching in python

See it in action:

matchObj = re.search("^(?!OK|\\.).*", item)

Don't forget to put .* after negative look-ahead, otherwise you couldn't get any match ;-)

MVC DateTime binding with incorrect date format

I've just found the answer to this with some more exhaustive googling:

Melvyn Harbour has a thorough explanation of why MVC works with dates the way it does, and how you can override this if necessary:

http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx

When looking for the value to parse, the framework looks in a specific order namely:

  1. RouteData (not shown above)
  2. URI query string
  3. Request form

Only the last of these will be culture aware however. There is a very good reason for this, from a localization perspective. Imagine that I have written a web application showing airline flight information that I publish online. I look up flights on a certain date by clicking on a link for that day (perhaps something like http://www.melsflighttimes.com/Flights/2008-11-21), and then want to email that link to my colleague in the US. The only way that we could guarantee that we will both be looking at the same page of data is if the InvariantCulture is used. By contrast, if I'm using a form to book my flight, everything is happening in a tight cycle. The data can respect the CurrentCulture when it is written to the form, and so needs to respect it when coming back from the form.

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

SQL Server: Importing database from .mdf?

Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.

Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I had same problem, but I knew it had worked OK in other cases, so I reduced the problem to this:

parent.OtherRelatedItems.Clear();  //this worked OK on SaveChanges() - items were being deleted from DB
parent.ProblematicItems.Clear();   // this was causing the mentioned exception on SaveChanges()
  • OtherRelatedItems had a composite Primary Key (parentId + some local column) and worked OK
  • ProblematicItems had their own single-column Primary Key, and the parentId was only a FK. This was causing the exception after Clear().

All I had to do was to make the ParentId a part of composite PK to indicate that the children can't exist without a parent. I used DB-first model, added the PK and marked the parentId column as EntityKey (so, I had to update it both in DB and EF - not sure if EF alone would be enough).

I made RequestId part of the PK And then updated the EF model, AND set the other property as part of Entity Key

Once you think about it, it's a very elegant distinction that EF uses to decide if children "make sense" without a parent (in this case Clear() won't delete them and throw exception unless you set the ParentId to something else/special), or - like in the original question - we expect the items to be deleted once they are removed from the parent.

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

Can I inject a service into a directive in AngularJS?

Change your directive definition from app.module to app.directive. Apart from that everything looks fine. Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.

It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.

http://plnkr.co/edit/M8omDEjvPvBtrBHM84Am

Trying to retrieve first 5 characters from string in bash error?

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

How do I get the n-th level parent of an element in jQuery?

You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")

How to merge every two lines into one from the command line?

There are more ways to kill a dog than hanging. [1]

awk '{key=$0; getline; print key ", " $0;}'

Put whatever delimiter you like inside the quotes.


References:

  1. Originally "Plenty of ways to skin the cat", reverted to an older, potentially originating expression that also has nothing to do with pets.

Event system in Python

If you need an eventbus that works across process or network boundaries you can try PyMQ. It currently supports pub/sub, message queues and synchronous RPC. The default version works on top of a Redis backend, so you need a running Redis server. There is also an in-memory backend for testing. You can also write your own backend.

import pymq

# common code
class MyEvent:
    pass

# subscribe code
@pymq.subscriber
def on_event(event: MyEvent):
    print('event received')

# publisher code
pymq.publish(MyEvent())

# you can also customize channels
pymq.subscribe(on_event, channel='my_channel')
pymq.publish(MyEvent(), channel='my_channel')

To initialize the system:

from pymq.provider.redis import RedisConfig

# starts a new thread with a Redis event loop
pymq.init(RedisConfig())

# main application control loop

pymq.shutdown()

Disclaimer: I am the author of this library

How to create a dynamic array of integers

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

How to serialize object to CSV file?

I wrote a simple class that uses OpenCSV and has two static public methods.

static public File toCSVFile(Object object, String path, String name) {
    File pathFile = new File(path);
    pathFile.mkdirs();
    File returnFile = new File(path + name);
    try {

        CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
        writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
        for (Field field : object.getClass().getDeclaredFields()) {
            writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
        }
        writer.flush();
        writer.close();
        return returnFile;
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    } catch (IllegalAccessException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    }
}

static public void fromCSVFile(Object object, File file) {
    try {
        CSVReader reader = new CSVReader(new FileReader(file));
        String[] nextLine = reader.readNext(); // Ignore the first line.
        while ((nextLine = reader.readNext()) != null) {
            if (nextLine.length >= 2) {
                try {
                    Field field = object.getClass().getDeclaredField(nextLine[0]);
                    Class<?> rClass = field.getType();
                    if (rClass == String.class) {
                        field.set(object, nextLine[1]);
                    } else if (rClass == int.class) {
                        field.set(object, Integer.parseInt(nextLine[1]));
                    } else if (rClass == boolean.class) {
                        field.set(object, Boolean.parseBoolean(nextLine[1]));
                    } else if (rClass == float.class) {
                        field.set(object, Float.parseFloat(nextLine[1]));
                    } else if (rClass == long.class) {
                        field.set(object, Long.parseLong(nextLine[1]));
                    } else if (rClass == short.class) {
                        field.set(object, Short.parseShort(nextLine[1]));
                    } else if (rClass == double.class) {
                        field.set(object, Double.parseDouble(nextLine[1]));
                    } else if (rClass == byte.class) {
                        field.set(object, Byte.parseByte(nextLine[1]));
                    } else if (rClass == char.class) {
                        field.set(object, nextLine[1].charAt(0));
                    } else {
                        Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
                    }
                } catch (NoSuchFieldException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
                } catch (IllegalAccessException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);

                }
            } // Close if (nextLine.length >= 2)
        } // Close while ((nextLine = reader.readNext()) != null)
    } catch (FileNotFoundException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IllegalArgumentException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    }
}

I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Absolute position of an element on the screen using jQuery

For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..

function AbsoluteCoordinates($element) {
    var sTop = $(window).scrollTop();
    var sLeft = $(window).scrollLeft();
    var w = $element.width();
    var h = $element.height();
    var offset = $element.offset(); 
    var $p = $element;
    while(typeof $p == 'object') {
        var pOffset = $p.parent().offset();
        if(typeof pOffset == 'undefined') break;
        offset.left = offset.left + (pOffset.left);
        offset.top = offset.top + (pOffset.top);
        $p = $p.parent();
    }

    var pos = {
          left: offset.left + sLeft,
          right: offset.left + w + sLeft,
          top:  offset.top + sTop,
          bottom: offset.top + h + sTop,
    }
    pos.tl = { x: pos.left, y: pos.top };
    pos.tr = { x: pos.right, y: pos.top };
    pos.bl = { x: pos.left, y: pos.bottom };
    pos.br = { x: pos.right, y: pos.bottom };
    //console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom  );
    return pos;
}

Slide right to left Android Animations

You can do Your own Animation style as an xml file like this(put it in anim folder):

left to right:

  <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
        <translate android:fromXDelta="-100%" android:toXDelta="0%"
         android:fromYDelta="0%" android:toYDelta="0%"
         android:duration="500"/>
  </set>

right to left:

    <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
     <translate
        android:fromXDelta="0%" android:toXDelta="100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="500" />
   </set>

here You can set Your own values at duration, maybe it depends on the phone model how the animation will look like, try some values out if it looks not good.

and then You can call it in Your activity:

     Intent animActivity = new Intent(this,YourStartAfterAnimActivity.class);
      startActivity(nextActivity);

      overridePendingTransition(R.anim.your_left_to_right, R.anim.your_right_to_left);

Matching a space in regex

Use it like this to allow for single space.

$newtag = preg_replace("/[^a-zA-Z0-9\s]/", "", $tag)

Lock screen orientation (Android)

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Get the value of a dropdown in jQuery

var sal = $('.selectSal option:selected').eq(0).val();

selectSal is a class.

What are the differences between .gitignore and .gitkeep?

.gitignore

is a text file comprising a list of files in your directory that git will ignore or not add/update in the repository.

.gitkeep

Since Git removes or doesn't add empty directories to a repository, .gitkeep is sort of a hack (I don't think it's officially named as a part of Git) to keep empty directories in the repository.

Just do a touch /path/to/emptydirectory/.gitkeep to add the file, and Git will now be able to maintain this directory in the repository.

How to delete all rows from all tables in a SQL Server database?

I had to delete all the rows and did it with the next script:

DECLARE @Nombre NVARCHAR(MAX);
DECLARE curso CURSOR FAST_FORWARD 
FOR 
Select Object_name(object_id) AS Nombre from sys.objects where type = 'U'

OPEN curso
FETCH NEXT FROM curso INTO @Nombre

WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
DECLARE @statement NVARCHAR(200);
SET @statement = 'DELETE FROM ' + @Nombre;
print @statement
execute sp_executesql @statement;
END
FETCH NEXT FROM curso INTO @Nombre
END
CLOSE curso
DEALLOCATE curso

Hope this helps!

Unable to connect to any of the specified mysql hosts. C# MySQL

use SqlConnectionStringBuilder to simplify the connection

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Server";
builder["Data Source"] = "db";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }

Java: how to represent graphs?

class Vertex {
    private String name;
    private int score; // for path algos
    private boolean visited; // for path algos
    List<Edge> connections;
}

class Edge {
    private String vertex1Name; // same as Vertex.name
    private String vertex2Name;
    private int length;
}

class Graph {
    private List<Edge> edges;
}

How to read a string one letter at a time in python

Create a lookup table first:

morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
    morse[ord(line[0].lower()) - ord('a')] = line[2:]

Then convert using the table:

for ch in userInput:
    print morse[ord(ch.lower()) - ord('a')]

Month name as a string

Russian.

Month
.MAY
.getDisplayName(
    TextStyle.FULL_STANDALONE ,
    new Locale( "ru" , "RU" )
)

???

English in the United States.

Month
.MAY
.getDisplayName(
    TextStyle.FULL_STANDALONE ,
    Locale.US
)

May

See this code run live at IdeOne.com.

ThreeTenABP and java.time

Here’s the modern answer. When this question was asked in 2011, Calendar and GregorianCalendar were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.

Depending on your exact needs and situation there are two options:

  1. Use Month and its getDisplayName method.
  2. Use a DateTimeFormatter.

Use Month

    Locale desiredLanguage = Locale.ENGLISH;
    Month m = Month.MAY;
    String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
    System.out.println(monthName);

Output from this snippet is:

May

In a few languages it will make a difference whether you use TextStyle.FULL or TextStyle.FULL_STANDALONE. You will have to see, maybe check with your users, which of the two fits into your context.

Use a DateTimeFormatter

If you’ve got a date with or without time of day, I find a DateTimeFormatter more practical. For example:

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);

    ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
    String monthName = dateTime.format(monthFormatter);

I am showing the use of a ZonedDateTime, the closest replacement for the old Calendar class. The above code will work for a LocalDate, a LocalDateTime, MonthDay, OffsetDateTime and a YearMonth too.

What if you got a Calendar from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime and proceed as above:

    Calendar c = getCalendarFromLegacyApi();
    ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);

The rest is the same as before.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

HashMap: One Key, multiple Values

It sounds like you're looking for a multimap. Guava has various Multimap implementations, usually created via the Multimaps class.

I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc. If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too :)

What's the best way to set a single pixel in an HTML5 canvas?

Since different browsers seems to prefer different methods, maybe it would make sense to do a smaller test with all three methods as a part of the loading process to find out which is best to use and then use that throughout the application?

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I couldn't find an off-the-shelf module that added this function, so I wrote one:

In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:

Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String

Substring_Index = delims

start = 0
test = ""

For i = 1 To intCount
    oldstart = start + 1
    start = InStr(oldstart, strWord, strDelim)
    Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i

End Function

Save the module as module1 (the default). You can now use statements like:

SELECT Substring_Index([fieldname],",",2) FROM table

Copying text outside of Vim with set mouse=a enabled

Use ", +, y after making a visual selection. You shouldn’t be using the terminal’s copy command anyway, because that copies what the terminal sees instead of the actual content. Here is what this does:

  • ",+ tells Vim to use the register named + for the next delete, yank or put. The register named + is a special register, it is the X11 clipboard register. (On other systems, you would use * instead, I think, see :help clipboard and :help x11-selection)
  • y is the yank command, which tells Vim to put the selection in the register named previously.

You could map it like this:

:vmap <C-C> "+y

And then highlight something with the mouse and press Control-C to copy it.

This feature only works when Vim has been compiled with the +xterm_clipboard option. Run vim --version to find out if it has.

Check if a time is between two times (time DataType)

I had a very similar problem and want to share my solution

Given this table (all MySQL 5.6):

create table DailySchedule
(
  id         int auto_increment primary key,
  start_time time not null,
  stop_time  time not null
);

Select all rows where a given time x (hh:mm:ss) is between start and stop time. Including the next day.

Note: replace NOW() with the any time x you like

SELECT id
FROM DailySchedule
WHERE
  (start_time < stop_time AND NOW() BETWEEN start_time AND stop_time)
  OR
  (stop_time < start_time AND NOW() < start_time AND NOW() < stop_time)
  OR
  (stop_time < start_time AND NOW() > start_time)

Results

Given

  id: 1, start_time: 10:00:00, stop_time: 15:00:00
  id: 2, start_time: 22:00:00, stop_time: 12:00:00
  • Selected rows with NOW = 09:00:00: 2
  • Selected rows with NOW = 14:00:00: 1
  • Selected rows with NOW = 11:00:00: 1,2
  • Selected rows with NOW = 20:00:00: nothing

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

Barcode scanner for mobile phone for Website in form

Check this out: http://qrdroid.com/web-masters.php

You can create a link in your web form, something like:

http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}

When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

You didn't explicitly state emacs, but since you've highlighted lots of editors...

In emacs, you can use rectangles for this, where a column is a rectangle of width 1.

To create a rectangle, mark the top-left and bottom-right of the rectangle (where the bottom-right mark is one to the right of the further right point included in the rectangle. You can then manipulate via:

C-x r k
Kill the text of the region-rectangle, saving its contents as the "last killed rectangle" (kill-rectangle).

C-x r d
Delete the text of the region-rectangle (delete-rectangle).

C-x r y
Yank the last killed rectangle with its upper left corner at point (yank-rectangle).

C-x r o
Insert blank space to fill the space of the region-rectangle (open-rectangle). This pushes the previous contents of the region-rectangle rightward.

M-x clear-rectangle
Clear the region-rectangle by replacing its contents with spaces.

M-x delete-whitespace-rectangle
Delete whitespace in each of the lines on the specified rectangle, starting from the left edge column of the rectangle.

C-x r t string RET
Replace rectangle contents with string on each line. (string-rectangle).

M-x string-insert-rectangle RET string RET
Insert string on each line of the rectangle.

Bootstrap 4 - Glyphicons migration?

If you are using Laravel 5.6, it comes with Bootstrap 4. All you need to is:

npm install and npm install open-iconic --save

At /resources/assets/sass/app.scss change the line of of Google font import on line 2 to

@import '~open-iconic/font/css/open-iconic-bootstrap';

All you need to do now is

npm run watch

and include

<link rel="stylesheet" href="{{asset('css/app.css')}}">

on top of master blade file and <script src="{{asset('js/app.js')}}"></script> before closing body tag. You will get Bootstrap 4 and icon.

Usage is <span class="oi oi-cog"></span>

Refer here for icon details: Open Iconic: Recommended by Bootstrap 4

If on other project than Laravel, you can just do import @import 'node_modules/open-iconic/font/css/open-iconic-bootstrap-min.css'; in your style file.

Hope this helps. Happy trying.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How to find/identify large commits in git history?

How can I track down the large files in the git history?

Start by analyzing, validating and selecting the root cause. Use git-repo-analysis to help.

You may also find some value in the detailed reports generated by BFG Repo-Cleaner, which can be run very quickly by cloning to a Digital Ocean droplet using their 10MiB/s network throughput.

HTML5 phone number validation with pattern

enter image description here

^[789]\d{9,9}$

  • Minimum digits 10
  • Maximum digits 10
  • number starts with 7,8,9

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.