Programs & Examples On #Apache portable runtime

Could not find a version that satisfies the requirement <package>

After 2 hours of searching, I found a way to fix it with just one line of command. You need to know the version of the package (Just search up PACKAGE version).

Command:

python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION

Using `date` command to get previous, current and next month

If you happen to be using date in a MacOS environment, try this:

ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03

Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)

Vertical dividers on horizontal UL menu

Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.

#navigation ul
{
    margin: 0;
    padding: 0;
}

#navigation ul li
{
    list-style-type: none;
    display: inline;
}

#navigation li:not(:first-child):before {
    content: " | ";
}

Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:

<div id="navigation">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Support</a></li>
    </ul>
</div><!-- navigation -->

The result will be just like this:

HOME | ABOUT US | SUPPORT

Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!

How do I query between two dates using MySQL?

DATE() is a MySQL function that extracts only the date part of a date or date/time expression

SELECT * FROM table_name WHERE DATE(date_field) BETWEEN '2016-12-01' AND '2016-12-10';

How to fix: "HAX is not working and emulator runs in emulation mode"

Yes it should be fixed, HAXM isn't working.

HAXM sometimes works; experience with HAXM is currently sporadic across platforms.

For instance, I've got late 2009 iMac running 10.8.5 and i7 processor @2.8Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration on this iMac machine, API19 chokes out.

I also have early 2013 MBP 15" Retina running 10.8.5 and i7 processor @2.7Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration, API19 works great too.

Ditto for my (personal) late 2013 MBP Retina 13" with dual-core i5 and Mavericks.

There is something going on for virtualization at the chip level missing from older CPU's (even i7's) that the new API19 x86 images need for HAXM to work. If API19 is not working, give API17 or even 16 a try.

Symfony2 : How to get form validation errors after binding the request to the form

Translated Form Error Messages (Symfony2.3)

My version of solving the problem:

/src/Acme/MyBundle/Resources/config/services.yml

services:
    form_errors:
        class: Acme\MyBundle\Form\FormErrors

/src/Acme/MyBundle/Form/FormErrors.php

<?php
namespace Acme\MyBundle\Form;

class FormErrors
{
    public function getArray(\Symfony\Component\Form\Form $form)
    {
        return $this->getErrors($form);
    }

    private function getErrors($form)
    {
        $errors = array();

        if ($form instanceof \Symfony\Component\Form\Form) {

            // ??????? ?????? ????????
            foreach ($form->getErrors() as $error) {

                $errors[] = $error->getMessage();
            }

            // ?????????? ??? ???????? ?????????
            foreach ($form->all() as $key => $child) {
                /** @var $child \Symfony\Component\Form\Form */
                if ($err = $this->getErrors($child)) {
                    $errors[$key] = $err;
                }
            }
        }

        return $errors;
    }
}

/src/Acme/MyBundle/Controller/DefaultController.php

$form = $this->createFormBuilder($entity)->getForm();
$form_errors = $this->get('form_errors')->getArray($form);
return new JsonResponse($form_errors);

In Symfony 2.5 you can get all fields errors very easy:

    $errors = array();
    foreach ($form as $fieldName => $formField) {
        foreach ($formField->getErrors(true) as $error) {
            $errors[$fieldName] = $error->getMessage();
        }
    }

jQuery ui datepicker with Angularjs

As a best practice, especially if you have multiple date pickers, you should not hardcode the element's scope variable name.

Instead, you should get the clicked input's ng-model and update its corresponding scope variable inside the onSelect method.

app.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'yy-mm-dd',

                onSelect: function(date) {
                    var ngModelName = this.attributes['ng-model'].value;

                    // if value for the specified ngModel is a property of 
                    // another object on the scope
                    if (ngModelName.indexOf(".") != -1) {
                        var objAttributes = ngModelName.split(".");
                        var lastAttribute = objAttributes.pop();
                        var partialObjString = objAttributes.join(".");
                        var partialObj = eval("scope." + partialObjString);

                        partialObj[lastAttribute] = date;
                    }
                    // if value for the specified ngModel is directly on the scope
                    else {
                        scope[ngModelName] = date;
                    }
                    scope.$apply();
                }

            });
        }
    };
});

EDIT

To address the issue that @Romain raised up (Nested Elements), I have modified my answer

Switch statement for string matching in JavaScript

It may be easier. Try to think like this:

  • first catch a string between regular characters
  • after that find "case"

:

// 'www.dev.yyy.com'
// 'xxx.foo.pl'

var url = "xxx.foo.pl";

switch (url.match(/\..*.\./)[0]){
   case ".dev.yyy." :
          console.log("xxx.dev.yyy.com");break;

   case ".some.":
          console.log("xxx.foo.pl");break;
} //end switch

customize Android Facebook Login button

In newer Facebook SDK, the login and logout text name is :

 <com.facebook.login.widget.LoginButton
 xmlns:facebook="http://schemas.android.com/apk/res-auto"
 facebook:com_facebook_login_text=""
 facebook:com_facebook_logout_text=""/>

JavaScript: location.href to open in new window/tab?

You can also open a new tab calling to an action method with parameter like this:

   var reportDate = $("#inputDateId").val();
   var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
   window.open(window.location.href = url.replace('findme', reportDate), '_blank');

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

getting "No column was specified for column 2 of 'd'" in sql server cte?

Because you are creatin a table expression, you have to specify the structure of that table, you can achive this on two way:

1: In the select you can use the original columnnames (as in your first example), but with aggregates you have to use an alias (also in conflicting names). Like

sum(totalitems) as bkdqty

2: You need to specify the column names rigth after the name of the talbe, and then you just have to take care that the count of the names should mach the number of coulms was selected in the query. Like:

d (duration, bkdqty) 
AS (Select.... ) 

With the second solution both of your query will work!

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

MySQL maximum memory usage

If you are looking for optimizing your docker mysql container then the below command may help. I was able to run mysql docker container from a default 480mb to mere 100 mbs

docker run -d -p 3306:3306 -e MYSQL_DATABASE=test -e MYSQL_ROOT_PASSWORD=tooor -e MYSQL_USER=test -e MYSQL_PASSWORD=test -v /mysql:/var/lib/mysql --name mysqldb mysql --table_definition_cache=100 --performance_schema=0 --default-authentication-plugin=mysql_native_password

How to fix java.net.SocketException: Broken pipe?

I have implemented data downloading functionality through FTP server and found the same exception there too while resuming that download. To resolve this exception, you will always have to disconnect from the previous session and create new instance of the Client and new connection with the server. This same approach could be helpful for HTTPClient too.

How to add line break for UILabel?

In xCode 11, Swift 5 the \n works fine, try the below code:

textlabel.numberOfLines = 0
textlabel.text = "This is line one \n This is line two \n This is line three"

Press enter in textbox to and execute button command

If you're just gonna click the button when Enter was pressed how about this?

private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSearch.PerformClick();
        }

Vertical (rotated) text in HTML table

After having tried for over two hours, I can safely say that all the method mentioned so far don't work across browsers, or for IE even across browser versions...

For example (top upvoted answer):

 filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */
     -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */

rotates twice in IE9, once for filter, and once for -ms-filter, so...

All other mentioned methods do not work either, at least not if you have to set no fixed height/width of the table header cell (with background color), where it should automatically adjust to size of the highest element.

So to elaborate on the server-side image generation proposed by Nathan Long, which is really the only universially working method, here my VB.NET code for a generic handler (*.ashx ):

Imports System.Web
Imports System.Web.Services


Public Class GenerateImage
    Implements System.Web.IHttpHandler


    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World!")
        context.Response.ContentType = "image/png"

        Dim strText As String = context.Request.QueryString("text")
        Dim strRotate As String = context.Request.QueryString("rotate")
        Dim strBGcolor As String = context.Request.QueryString("bgcolor")

        Dim bRotate As Boolean = True

        If String.IsNullOrEmpty(strText) Then
            strText = "No Text"
        End If


        Try
            If Not String.IsNullOrEmpty(strRotate) Then
                bRotate = System.Convert.ToBoolean(strRotate)
            End If
        Catch ex As Exception

        End Try


        'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
        'Dim img As System.Drawing.Image = CreateBitmapImage(strText, bRotate)

        ' Generic error in GDI+
        'img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

        'Dim bm As System.Drawing.Bitmap = New System.Drawing.Bitmap(img)
        'bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

        Using msTempOutputStream As New System.IO.MemoryStream
            'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
            Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)
                img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)
                msTempOutputStream.Flush()

                context.Response.Buffer = True
                context.Response.ContentType = "image/png"
                context.Response.BinaryWrite(msTempOutputStream.ToArray())
            End Using ' img

        End Using ' msTempOutputStream

    End Sub ' ProcessRequest


    Private Function CreateBitmapImage(strImageText As String) As System.Drawing.Image
        Return CreateBitmapImage(strImageText, True)
    End Function ' CreateBitmapImage


    Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean) As System.Drawing.Image
        Return CreateBitmapImage(strImageText, bRotate, Nothing)
    End Function


    Private Function InvertMeAColour(ColourToInvert As System.Drawing.Color) As System.Drawing.Color
        Const RGBMAX As Integer = 255
        Return System.Drawing.Color.FromArgb(RGBMAX - ColourToInvert.R, RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B)
    End Function



    Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean, strBackgroundColor As String) As System.Drawing.Image
        Dim bmpEndImage As System.Drawing.Bitmap = Nothing

        If String.IsNullOrEmpty(strBackgroundColor) Then
            strBackgroundColor = "#E0E0E0"
        End If

        Dim intWidth As Integer = 0
        Dim intHeight As Integer = 0


        Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray
        bgColor = System.Drawing.ColorTranslator.FromHtml(strBackgroundColor)

        Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black
        TextColor = InvertMeAColour(bgColor)

        'TextColor = Color.FromArgb(102, 102, 102)



        ' Create the Font object for the image text drawing.
        Using fntThisFont As New System.Drawing.Font("Arial", 11, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel)

            ' Create a graphics object to measure the text's width and height.
            Using bmpInitialImage As New System.Drawing.Bitmap(1, 1)

                Using gStringMeasureGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpInitialImage)
                    ' This is where the bitmap size is determined.
                    intWidth = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Width)
                    intHeight = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Height)

                    ' Create the bmpImage again with the correct size for the text and font.
                    bmpEndImage = New System.Drawing.Bitmap(bmpInitialImage, New System.Drawing.Size(intWidth, intHeight))

                    ' Add the colors to the new bitmap.
                    Using gNewGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpEndImage)
                        ' Set Background color
                        'gNewGraphics.Clear(Color.White)
                        gNewGraphics.Clear(bgColor)
                        gNewGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias
                        gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias


                        ''''

                        'gNewGraphics.TranslateTransform(bmpEndImage.Width, bmpEndImage.Height)
                        'gNewGraphics.RotateTransform(180)
                        'gNewGraphics.RotateTransform(0)
                        'gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault


                        gNewGraphics.DrawString(strImageText, fntThisFont, New System.Drawing.SolidBrush(TextColor), 0, 0)

                        gNewGraphics.Flush()

                        If bRotate Then
                            'bmpEndImage = rotateImage(bmpEndImage, 90)
                            'bmpEndImage = RotateImage(bmpEndImage, New PointF(0, 0), 90)
                            'bmpEndImage.RotateFlip(RotateFlipType.Rotate90FlipNone)
                            bmpEndImage.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone)
                        End If ' bRotate

                    End Using ' gNewGraphics

                End Using ' gStringMeasureGraphics

            End Using ' bmpInitialImage

        End Using ' fntThisFont

        Return bmpEndImage
    End Function ' CreateBitmapImage


    ' http://msdn.microsoft.com/en-us/library/3zxbwxch.aspx
    ' http://msdn.microsoft.com/en-us/library/7e1w5dhw.aspx
    ' http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=286
    ' http://road-blogs.blogspot.com/2011/01/rotate-text-in-ssrs.html
    Public Shared Function GenerateImage_CrappyOldReportingServiceVariant(ByVal strText As String, ByVal strFont As String, bRotate As Boolean) As System.Drawing.Image
        Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray
        bgColor = System.Drawing.ColorTranslator.FromHtml("#E0E0E0")


        Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black
        'TextColor = System.Drawing.Color.FromArgb(255, 0, 0, 255)

        If String.IsNullOrEmpty(strFont) Then
            strFont = "Arial"
        Else
            If strFont.Trim().Equals(String.Empty) Then
                strFont = "Arial"
            End If
        End If


        'Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Regular
        Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Bold
        Dim fontFamily As New System.Drawing.FontFamily(strFont)
        Dim iFontSize As Integer = 8 '//Change this as needed


        ' vice-versa, because 270° turn
        'Dim height As Double = 2.25
        Dim height As Double = 4
        Dim width As Double = 1

        ' width = 10
        ' height = 10

        Dim bmpImage As New System.Drawing.Bitmap(1, 1)
        Dim iHeight As Integer = CInt(height * 0.393700787 * bmpImage.VerticalResolution) 'y DPI
        Dim iWidth As Integer = CInt(width * 0.393700787 * bmpImage.HorizontalResolution) 'x DPI

        bmpImage = New System.Drawing.Bitmap(bmpImage, New System.Drawing.Size(iWidth, iHeight))



        '// Create the Font object for the image text drawing.
        'Dim MyFont As New System.Drawing.Font("Arial", iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)
        '// Create a graphics object to measure the text's width and height.
        Dim MyGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpImage)
        MyGraphics.Clear(bgColor)


        Dim stringFormat As New System.Drawing.StringFormat()
        stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical
        'stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical Or System.Drawing.StringFormatFlags.DirectionRightToLeft
        Dim solidBrush As New System.Drawing.SolidBrush(TextColor)
        Dim pointF As New System.Drawing.PointF(CSng(iWidth / 2 - iFontSize / 2 - 2), 5)
        Dim font As New System.Drawing.Font(fontFamily, iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)


        MyGraphics.TranslateTransform(bmpImage.Width, bmpImage.Height)
        MyGraphics.RotateTransform(180)
        MyGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault
        MyGraphics.DrawString(strText, font, solidBrush, pointF, stringFormat)
        MyGraphics.ResetTransform()

        MyGraphics.Flush()

        'If Not bRotate Then
        'bmpImage.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone)
        'End If

        Return bmpImage
    End Function ' GenerateImage



    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property ' IsReusable


End Class

Note that if you think that this part

        Using msTempOutputStream As New System.IO.MemoryStream
            'Dim img As System.Drawing.Image = GenerateImage(strText, "Arial", bRotate)
            Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)
                img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)
                msTempOutputStream.Flush()

                context.Response.Buffer = True
                context.Response.ContentType = "image/png"
                context.Response.BinaryWrite(msTempOutputStream.ToArray())
            End Using ' img

        End Using ' msTempOutputStream

can be replaced with

img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)

because it works on the development server, then you are sorely mistaken to assume the very same code wouldn't throw a Generic GDI+ exception if you deploy it to a Windows 2003 IIS 6 server...

then use it like this:

<img alt="bla" src="GenerateImage.ashx?no_cache=123&text=Hello%20World&rotate=true" />

Add resources, config files to your jar using gradle

I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).

None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle file :

sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]

It tells Gradle to look for resources in the src folder, and ask it to include only PNG files.

EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/ for example, and to set it as srcDirs instead of src/.

"Parameter not valid" exception loading System.Drawing.Image

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?

How do you explicitly set a new property on `window` in TypeScript?

For those using the Angular CLI it's straightforward:

src/polyfills.ts

declare global {
  interface Window {
    myCustomFn: () => void;
  }
}

my-custom-utils.ts

window.myCustomFn = function () {
  ...
};

If you're using IntelliJ, you also needed to change the following setting in the IDE before your new polyfills pick up:

> File 
> Settings 
> Languages & Frameworks 
> TypeScript 
> check 'Use TypeScript Service'.

No shadow by default on Toolbar?

This worked for me very well:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary"
    card_view:cardElevation="4dp"
    card_view:cardCornerRadius="0dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/primary"
        android:minHeight="?attr/actionBarSize" />

</android.support.v7.widget.CardView>

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Today, I stuck with this error, and went through all the answers but nothing worked out for me.

For me the issue was **Java version**.

Initially, I installed Java 8 Update 251 x64 which actually was the reason of my issue applet not working issue with Internet Explorer version 11.

Solution

Uninstalled Java 8 Update 251 x64

Installed Java 8 Update 251 x86

issue resolved.

Is there any way to set environment variables in Visual Studio Code?

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

Arrow operator (->) usage in C

Well I have to add something as well. Structure is a bit different than array because array is a pointer and structure is not. So be careful!

Lets say I write this useless piece of code:

#include <stdio.h>

typedef struct{
        int km;
        int kph;
        int kg;
    } car;

int main(void){

    car audi = {12000, 230, 760};
    car *ptr = &audi;

}

Here pointer ptr points to the address (!) of the structure variable audi but beside address structure also has a chunk of data (!)! The first member of the chunk of data has the same address than structure itself and you can get it's data by only dereferencing a pointer like this *ptr (no braces).

But If you want to acess any other member than the first one, you have to add a designator like .km, .kph, .kg which are nothing more than offsets to the base address of the chunk of data...

But because of the preceedence you can't write *ptr.kg as access operator . is evaluated before dereference operator * and you would get *(ptr.kg) which is not possible as pointer has no members! And compiler knows this and will therefore issue an error e.g.:

error: ‘ptr’ is a pointer; did you mean to use ‘->’?
  printf("%d\n", *ptr.km);

Instead you use this (*ptr).kg and you force compiler to 1st dereference the pointer and enable acess to the chunk of data and 2nd you add an offset (designator) to choose the member.

Check this image I made:

enter image description here

But if you would have nested members this syntax would become unreadable and therefore -> was introduced. I think readability is the only justifiable reason for using it as this ptr->kg is much easier to write than (*ptr).kg.

Now let us write this differently so that you see the connection more clearly. (*ptr).kg ? (*&audi).kg ? audi.kg. Here I first used the fact that ptr is an "address of audi" i.e. &audi and fact that "reference" & and "dereference" * operators cancel eachother out.

Android button font size

Button butt= new Button(_context);
butt.setTextAppearance(_context, R.style.ButtonFontStyle);

and in res/values/style.xml

<resources>   
    <style name="ButtonFontStyle">
            <item name="android:textSize">12sp</item>
    </style>
</resources>

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

Regular expression that matches valid IPv6 addresses

This regular expression will match valid IPv6 and IPv4 addresses in accordance with GNU C++ implementation of regex with REGULAR EXTENDED mode used:

"^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(%.+)?\s*$"

Text in HTML Field to disappear when clicked?

Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">

inner join in linq to entities

You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

Check if application is on its first run

SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // second argument is the default to use if the preference can't be found
    Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);

    if (!welcomeScreenShown) {
        // here you can launch another activity if you like

        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(welcomeScreenShownPref, true);
        editor.commit(); // Very important to save the preference

    }
}

Use sed to replace all backslashes with forward slashes

This might work for you:

sed 'y/\\/\//'

Programmatically close aspx page from code behind

You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup

UITextView that expands to text using auto layout

I see multiple answers suggest simply turning off scrollEnabled. This is the best solution. I’m writing this answer to explain why it works.

UITextView implements the intrinsicContentSize property if scrollEnabled == NO. The disassembly of the getter method looks like this:

- (CGSize)intrinsicContentSize {
  if (self.scrollEnabled) {
    return CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric);
  } else {
    // Calculate and return intrinsic content size based on current width.
  }
}

That means you just need to make sure the width of the text view is constrained enough and then you can use the intrinsic content height (either via Auto Layout content hugging/compression resistance priorities or directly using the value during manual layout).

Unfortunately, this behavior is not documented. Apple could have easily saved us all some headaches… no need for an extra height constraint, subclassing, etc.

Powershell get ipv4 address into a variable

$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""

Also check which index of ipconfig has the IPv4 Address

MySQL CURRENT_TIMESTAMP on create and on update

you can try this ts_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, ts_update TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP

Examples for string find in Python

Try

myString = 'abcabc'
myString.find('a')

This will give you the index!!!

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

Maybe not very elegant, but it does the job:

exec(open("script.py").read())

How to do a redirect to another route with react-router?

1) react-router > V5 useHistory hook:

If you have React >= 16.8 and functional components you can use the useHistory hook from react-router.

import React from 'react';
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
    const history = useHistory();

    const handleClick = () => {
        history.push("/path/to/push");
    }

    return (
        <div>
            <button onClick={handleClick} type="button" />
        </div>
    );
}

export default YourComponent;

2) react-router > V4 withRouter HOC:

As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

export default withRouter(YourComponent);

3) React-router < V4 with browserHistory

You can achieve this functionality using react-router BrowserHistory. Code below:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class YourComponent extends Component {
    handleClick = () => {
        browserHistory.push('/login');
    };

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

4) Redux connected-react-router

If you have connected your component with redux, and have configured connected-react-router all you have to do is this.props.history.push("/new/url"); ie, you don't need withRouter HOC to inject history to the component props.

// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

export default (history) => combineReducers({
    router: connectRouter(history),
    ... // rest of your reducers
});


// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();

export default function configureStore(preloadedState) {
    const store = createStore(
        createRootReducer(history), // root reducer with router state
        preloadedState,
        compose(
            applyMiddleware(
                routerMiddleware(history), // for dispatching history actions
                // ... other middlewares ...
            ),
        ),
    );

    return store;
}


// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <> { /* your usual react-router v4/v5 routing */ }
                <Switch>
                    <Route exact path="/yourPath" component={YourComponent} />
                </Switch>
            </>
        </ConnectedRouter>
    </Provider>,
    document.getElementById('root')
);


// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
          <div>
            <button onClick={this.handleClick} type="button">
          </div>
        );
      }
    };

}

export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);

Android set height and width of Custom view programmatically

spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

spin12 is your spinner and 200,120 is width and height for your spinner.

Read specific columns with pandas or other python module

An easy way to do this is using the pandas library like this.

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name

The problem here was the skipinitialspace which remove the spaces in the header. So ' star_name' becomes 'star_name'

Count the number occurrences of a character in a string

An alternative way to get all the character counts without using Counter(), count and regex

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)

Sort columns of a dataframe by column name

You can use order on the names, and use that to order the columns when subsetting:

test[ , order(names(test))]
  A B C
1 4 1 0
2 2 3 2
3 4 8 4
4 7 3 7
5 8 2 8

For your own defined order, you will need to define your own mapping of the names to the ordering. This would depend on how you would like to do this, but swapping whatever function would to this with order above should give your desired output.

You may for example have a look at Order a data frame's rows according to a target vector that specifies the desired order, i.e. you can match your data frame names against a target vector containing the desired column order.

JSON Stringify changes time of date because of UTC

Recently I have run into the same issue. And it was resolved using the following code:

x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

How to check if a char is equal to an empty space?

You can try:

if(Character.isSpaceChar(ch))
{
    // Do something...
}

Or:

if((int) ch) == 32)
{
    // Do something...
}

How to wait 5 seconds with jQuery?

I ran across this question and I thought I'd provide an update on this topic. jQuery (v1.5+) includes a Deferred model, which (despite not adhering to the Promises/A spec until jQuery 3) is generally regarded as being a clearer way to approach many asynchronous problems. Implementing a $.wait() method using this approach is particularly readable I believe:

$.wait = function(ms) {
    var defer = $.Deferred();
    setTimeout(function() { defer.resolve(); }, ms);
    return defer;
};

And here's how you can use it:

$.wait(5000).then(disco);

However if, after pausing, you only wish to perform actions on a single jQuery selection, then you should be using jQuery's native .delay() which I believe also uses Deferred's under the hood:

$(".my-element").delay(5000).fadeIn();

Git Diff with Beyond Compare

Run these commands for Beyond Compare 3(if the BCompare.exe path is different in your system, please replace it according to yours):

git config --global diff.tool bc3
git config --global difftool.bc3.cmd "\"c:/program files (x86)/beyond compare 3/BCompare.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false

Then use git difftool

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

Hide text using css

Why not simply use:

h1 { color: transparent; }

how to reference a YAML "setting" from elsewhere in the same YAML file?

That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the * with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:

paths:
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c

This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'?', 1)
            kw, rest = rest.split(u'? +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

which will print:

root -> /path/to/root/
pathc -> /path/to/root/c

The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.

By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

this will change the mapping key ordering. If that is a problem you have to make self.d a CommentedMap (imported from ruamel.yaml.comments.py)

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to detect when cancel is clicked on file input?

I found this atribute, its most simple yet.

if ($('#selectedFile')[0].files.length > 1)
{
   // Clicked on 'open' with file
} else {
   // Clicked on 'cancel'
}

Here, selectedFile is an input type=file.

Why are arrays of references illegal?

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

This works the best for me:

.noSelect:hover {
  background-color: white;
}

C++ template constructor

You can create a templated factory function:

class Foo
{
public:
    template <class T> static Foo* create() // could also return by value, or a smart pointer
    {
        return new Foo(...);
    }
...        
};

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

Solve error javax.mail.AuthenticationFailedException

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

How to check if a query string value is present via JavaScript?

In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.

Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, you can grab the query string using window.location.search:

const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m

You can then parse the query string’s parameters using URLSearchParams:

const urlParams = new URLSearchParams(queryString);

Then you can call any of its methods on the result.

For example, URLSearchParams.get() will return the first value associated with the given search parameter:

const product = urlParams.get('product')
console.log(product);
// shirt

const color = urlParams.get('color')
console.log(color);
// blue

const newUser = urlParams.get('newuser')
console.log(newUser);
// empty string

You can use URLSearchParams.has() to check whether a certain parameter exists:

console.log(urlParams.has('product'));
// true

console.log(urlParams.has('paymentmethod'));
// false

For further reading please click here.

How can I create numbered map markers in Google Maps V3?

This how I do it in V3:

I start by loading the google maps api and within the callback method initialize() I load MarkerWithLabel.js that I found here:

function initialize() {

            $.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){

            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(currentLat, currentLng),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: false,
                mapTypeControl: false
            };

            var map = new google.maps.Map(document.getElementById('mapholder'),
                    mapOptions);

            var bounds = new google.maps.LatLngBounds();

            for (var i = 0; i &lt; mapData.length; i++) {
                createMarker(i+1, map, mapData[i]); <!-- MARKERS! -->
                extendBounds(bounds, mapData[i]);
            }
            map.fitBounds(bounds);
            var maximumZoomLevel = 16;
            var minimumZoomLevel = 11;
            var ourZoom = defaultZoomLevel; // default zoom level

            var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                if (this.getZoom(map.getBounds) &gt; 16) {
                    this.setZoom(maximumZoomLevel);
                }
                google.maps.event.removeListener(blistener);
            });
            });
        }

        function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places&amp;sensor=false&amp;callback=initialize";
            document.body.appendChild(script);
        }

        window.onload = loadScript;

    </script> 

I then create the markers with createMarker():

function createMarker(number, currentMap, currentMapData) {

   var marker = new MarkerWithLabel({
       position: new google.maps.LatLng(currentMapData[0], currentMapData[1]),
                 map: currentMap,
                 icon: '/img/sticker/empty.png',
                 shadow: '/img/sticker/bubble_shadow.png',
                 transparent: '/img/sticker/bubble_transparent.png',
                 draggable: false,
                 raiseOnDrag: false,
                 labelContent: ""+number,
                 labelAnchor: new google.maps.Point(3, 30),
                 labelClass: "mapIconLabel", // the CSS class for the label
                 labelInBackground: false
                });
            }

Since I added mapIconLabel class to the marker I can add some css rules in my css:

.mapIconLabel {
    font-size: 15px;
    font-weight: bold;
    color: #FFFFFF;
    font-family: 'DINNextRoundedLTProMediumRegular';
}

And here is the result:

MarkerWithIconAndLabel

How to make type="number" to positive numbers only

With text type of input you can use this for a better validation,

return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();

How to set the environmental variable LD_LIBRARY_PATH in linux

The file .bash_profile is only executed by login shells. You may need to put it in ~/.bashrc, or simply logout and login again.

How to read a single character at a time from a file in Python?

You should try f.read(1), which is definitely correct and the right thing to do.

How to skip over an element in .map()?

You can do this

_x000D_
_x000D_
var sources = [];
images.map(function (img) {
    if(img.src.split('.').pop() !== "json"){ // if extension is not .json
        sources.push(img.src); // just push valid value
    }
});
_x000D_
_x000D_
_x000D_

How to delete a folder with files using Java

Using Apache Commons-IO, it is following one-liner:

import org.apache.commons.io.FileUtils;

FileUtils.forceDelete(new File(destination));

This is (slightly) more performant than FileUtils.deleteDirectory.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later):

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

Above is the equivalent of jQuery .ready:

$(document).ready(function() {
    console.log("Ready!");
});

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.

$(function() {
    console.log("ready!");
});

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready):

DO NOT use an IIFE like this that is self executing:

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

This IIFE will NOT wait for your DOM to load. (I'm even talking about latest version of Chrome browser!)

What's the strangest corner case you've seen in C# or .NET?

This is the strangest I've encountered by accident:

public class DummyObject
{
    public override string ToString()
    {
        return null;
    }
}

Used as follows:

DummyObject obj = new DummyObject();
Console.WriteLine("The text: " + obj.GetType() + " is " + obj);

Will throw a NullReferenceException. Turns out the multiple additions are compiled by the C# compiler to a call to String.Concat(object[]). Prior to .NET 4, there is a bug in just that overload of Concat where the object is checked for null, but not the result of ToString():

object obj2 = args[i];
string text = (obj2 != null) ? obj2.ToString() : string.Empty;
// if obj2 is non-null, but obj2.ToString() returns null, then text==null
int length = text.Length;

This is a bug by ECMA-334 §14.7.4:

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

Upload a file to Amazon S3 with NodeJS

Thanks to David as his solution helped me come up with my solution for uploading multi-part files from my Heroku hosted site to S3 bucket. I did it using formidable to handle incoming form and fs to get the file content. Hopefully, it may help you.

api.service.ts

public upload(files): Observable<any> {  
    const formData: FormData = new FormData(); 
    files.forEach(file => {
      // create a new multipart-form for every file 
      formData.append('file', file, file.name);           
    });   
    return this.http.post(uploadUrl, formData).pipe(
      map(this.extractData),
      catchError(this.handleError)); 
  }
}

server.js

app.post('/api/upload', upload);
app.use('/api/upload', router);

upload.js

const IncomingForm = require('formidable').IncomingForm;
const fs = require('fs');
const AWS = require('aws-sdk');

module.exports = function upload(req, res) {
    var form = new IncomingForm();

    const bucket = new AWS.S3(
      {
        signatureVersion: 'v4',
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: 'us-east-1'       
      }
    ); 

    form.on('file', (field, file) => {

        const fileContent = fs.readFileSync(file.path);

        const s3Params = {
            Bucket: process.env.AWS_S3_BUCKET,
            Key: 'folder/' + file.name,
            Expires: 60,             
            Body: fileContent,
            ACL: 'public-read'
        };

        bucket.upload(s3Params, function(err, data) {
            if (err) {
                throw err;
            }            
            console.log('File uploaded to: ' + data.Location);
            fs.unlink(file.path, function (err) {
              if (err) {
                  console.error(err);
              }
              console.log('Temp File Delete');
          });
        });
    });              

    // The second callback is called when the form is completely parsed. 
    // In this case, we want to send back a success status code.
    form.on('end', () => {        
      res.status(200).json('upload ok');
    });

    form.parse(req);
}

upload-image.component.ts

import { Component, OnInit, ViewChild, Output, EventEmitter, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-upload-image',
  templateUrl: './upload-image.component.html',
  styleUrls: ['./upload-image.component.css']
})

export class UploadImageComponent implements OnInit {
  public files: Set<File> = new Set();
  @ViewChild('file', { static: false }) file;
  public uploadedFiles: Array<string> = new Array<string>();
  public uploadedFileNames: Array<string> = new Array<string>();
  @Output() filesOutput = new EventEmitter<Array<string>>();
  @Input() CurrentImage: string;
  @Input() IsPublic: boolean;
  @Output() valueUpdate = new EventEmitter();
  strUploadedFiles:string = '';
  filesUploaded: boolean = false;     

  constructor(private api: ApiService, public snackBar: MatSnackBar,) { }

  ngOnInit() {    
  }

  updateValue(val) {  
    this.valueUpdate.emit(val);  
  }  

  reset()
  {
    this.files = new Set();
    this.uploadedFiles = new Array<string>();
    this.uploadedFileNames = new Array<string>();
    this.filesUploaded = false;
  }

  upload() { 

    this.api.upload(this.files).subscribe(res => {   
      this.filesOutput.emit(this.uploadedFiles); 
      if (res == 'upload ok')
      {
        this.reset(); 
      }     
    }, err => {
      console.log(err);
    });
  }

  onFilesAdded() {
    var txt = '';
    const files: { [key: string]: File } = this.file.nativeElement.files;

    for (let key in files) {
      if (!isNaN(parseInt(key))) {

        var currentFile = files[key];
        var sFileExtension = currentFile.name.split('.')[currentFile.name.split('.').length - 1].toLowerCase();
        var iFileSize = currentFile.size;

        if (!(sFileExtension === "jpg" 
              || sFileExtension === "png") 
              || iFileSize > 671329) {
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iFileSize + "\n\n";
            txt += "Please make sure your file is in jpg or png format and less than 655 KB.\n\n";
            alert(txt);
            return false;
        }

        this.files.add(files[key]);
        this.uploadedFiles.push('https://gourmet-philatelist-assets.s3.amazonaws.com/folder/' + files[key].name);
        this.uploadedFileNames.push(files[key].name);
        if (this.IsPublic && this.uploadedFileNames.length == 1)
        {
          this.filesUploaded = true;
          this.updateValue(files[key].name);
          break;
        } 
        else if (!this.IsPublic && this.uploadedFileNames.length == 3)
        {
          this.strUploadedFiles += files[key].name;          
          this.updateValue(this.strUploadedFiles); 
          this.filesUploaded = true;
          break;
        }
        else
        {
          this.strUploadedFiles += files[key].name + ",";          
          this.updateValue(this.strUploadedFiles); 
        }      
      }
    }    
  }

  addFiles() {
    this.file.nativeElement.click();  
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
      verticalPosition: 'top'
    });
  }   

}

upload-image.component.html

<input type="file" #file style="display: none" (change)="onFilesAdded()" multiple />
&nbsp;<button mat-raised-button color="primary" 
         [disabled]="filesUploaded" (click)="$event.preventDefault(); addFiles()">
  Add Files
</button>
&nbsp;<button class="btn btn-success" [disabled]="uploadedFileNames.length == 0" (click)="$event.preventDefault(); upload()">
  Upload
</button>

batch script - read line by line

This has worked for me in the past and it will even expand environment variables in the file if it can.

for /F "delims=" %%a in (LogName.txt) do (
     echo %%a>>MyDestination.txt
)

Calling dynamic function with dynamic number of parameters

The simplest way might be:

var func='myDynamicFunction_'+myHandler;
var arg1 = 100, arg2 = 'abc';

window[func].apply(null,[arg1, arg2]);

Assuming, that target function is already attached to a "window" object.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

EXEC sp_helptext 'your procedure name';

This avoids the problem with INFORMATION_SCHEMA approach wherein the stored procedure gets cut off if it is too long.

Update: David writes that this isn't identical to his sproc...perhaps because it returns the lines as 'records' to preserve formatting? If you want to see the results in a more 'natural' format, you can use Ctrl-T first (output as text) and it should print it out exactly as you've entered it. If you are doing this in code, it is trivial to do a foreach to put together your results in exactly the same way.

Update 2: This will provide the source with a "CREATE PROCEDURE" rather than an "ALTER PROCEDURE" but I know of no way to make it use "ALTER" instead. Kind of a trivial thing, though, isn't it?

Update 3: See the comments for some more insight on how to maintain your SQL DDL (database structure) in a source control system. That is really the key to this question.

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

Text overwrite in visual studio 2010

I'm using Visual Studio with Parallels/Win 7 on a MacBook laptop keyboard and the only thing that worked was Fn + Enter/Return (that's the Mac shortcut for Insert).

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Just make a PKCS12 keystore, Java can use it directly now. In fact, if you list a Java-style keystore, keytool itself alerts you to the fact that PKCS12 is now the preferred format.

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root -chain

You should have received all three files (server.crt, server.key, ca.crt) from your certificate provider. I am not sure what "-caname root" actually means, but it seems to have to be specified that way.

In the Java code, make sure to specify the right keystore type.

KeyStore.getInstance("PKCS12")

I got my comodo.com-issued SSL certificate working fine in NanoHTTPD this way.

How to use ES6 Fat Arrow to .filter() an array of objects

It appears I cannot use an if statement.

Arrow functions either allow to use an expression or a block as their body. Passing an expression

foo => bar

is equivalent to the following block

foo => { return bar; }

However,

if (person.age > 18) person

is not an expression, if is a statement. Hence you would have to use a block, if you wanted to use if in an arrow function:

foo => {  if (person.age > 18) return person; }

While that technically solves the problem, this a confusing use of .filter, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter should return a Boolean, i.e. true or false, indicating whether the element should be included in the new array or not.

So all you need is

family.filter(person => person.age > 18);

In ES5:

family.filter(function (person) {
  return person.age > 18;
});

getString Outside of a Context or Activity

Unfortunately, the only way you can access any of the string resources is with a Context (i.e. an Activity or Service). What I've usually done in this case, is to simply require the caller to pass in the context.

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

How do I read input character-by-character in Java?

Combining the recommendations from others for specifying a character encoding and buffering the input, here's what I think is a pretty complete answer.

Assuming you have a File object representing the file you want to read:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(
        new FileInputStream(file),
        Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
  char character = (char) c;
  // Do something with your character
}

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

AngularJS accessing DOM elements inside directive template

This answer comes a little bit late, but I just was in a similar need.

Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.

For example, use the directive like this:

<my-directive class2add="special-class" />

And get the following html:

<div>
    <ul>
       <li class="special-class">Item 1</li>
       <li class="special-class">Item 2</li>
    </ul>
</div>

The solution found here applied with templateUrl, would be:

app.directive("myDirective", function() {
    return {
        template: function(element, attrs){
            return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
        },
        link: function(scope, element, attrs) {
            var list = element.find("ul");
        }
    }
});

Just tried it successfully with AngularJS 1.4.9.

Hope it helps.

How to use 'find' to search for files created on a specific date?

It's two steps but I like to do it this way:

First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight

touch -t 0810010000 /tmp/t

Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).

find / -newer /tmp/t
find / -not -newer /tmp/t

You could also look at files between certain dates by creating two files with touch

touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2

This will find files between the two dates & times

find / -newer /tmp/t1 -and -not -newer /tmp/t2

PHP combine two associative arrays into one array

I stumbled upon this question trying to identify a clean way to join two assoc arrays.

I was trying to join two different tables that didn't have relationships to each other.

This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge() +1 to him.

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
        $ResidentialData = $pdo->prepare($sql);
        $ResidentialData->execute(array($lapi));
        $ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
        $CommercialData = $pdo->prepare($sql);
        $CommercialData->execute(array($lapi));
        $CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);

        $Prospects = array_merge($ResidentialProspects,$CommercialProspects);
        echo '<pre>';
        var_dump($Prospects);
        echo '</pre>';

Maybe this will help someone else out.

iOS UIImagePickerController result image orientation after upload

If I understand, what you want to do is disregard the orientation of the UIImage? If so then you could do this:-

//image is your original image
image = [UIImage imageWithCGImage:[image CGImage]
                             scale:[image scale]
                       orientation: UIImageOrientationUp];

or in Swift :-

image = UIImage(CGImage: image.CGImage!, scale: image.scale, orientation:.Up)

It solved my cropping issue.. Hope, this is what you're looking for..

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

Error:java: javacTask: source release 8 requires target release 1.8

If you are working with Android-studio 1.3, Follow the below steps -

Go to File - Project Structure

Under modules- app-Properties tab, choose Source Compatibility -1.8 and

Target Compatibility - 1.8.

And you are good to go.

How to create a drop-down list?

You can also use AppCompatSpinner widget:

<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spinner_order_type"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="@color/red"/>

Inside your Activity class:

AppCompatSpinner spinOrderType = (AppCompatSpinner) findViewById(R.id.spinner_order_type);
List<String> categories = new ArrayList<String>();
        categories.add(getString(R.string.label_table_order));
        categories.add(getString(R.string.label_take_away));

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
                R.layout.layout_spinner_item, categories);
        dataAdapter.setDropDownViewResource(R.layout.layout_spinner_item);
        spinOrderType.setAdapter(dataAdapter);
        spinOrderType.setSelection(0);

        spinOrderType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                String item = parent.getItemAtPosition(position).toString();
                Log.d(TAG, item);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

layout_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="left"
    android:textSize="@dimen/text.size.large"
    android:textColor="@color/text.link"
    android:padding="@dimen/margin.3" />

Convert floats to ints in Pandas?

To modify the float output do this:

df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df

Out[33]:

          a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000

pd.options.display.float_format = '{:,.0f}'.format
df

Out[35]:

   a
0  0
1  1
2  2
3  3
4  4

jQuery Get Selected Option From Dropdown

Probably your best bet with this kind of scenario is to use jQuery's change method to find the currently selected value, like so:

$('#aioConceptName').change(function(){

   //get the selected val using jQuery's 'this' method and assign to a var
   var selectedVal = $(this).val();

   //perform the rest of your operations using aforementioned var

});

I prefer this method because you can then perform functions for each selected option in a given select field.

Hope that helps!

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

Linux Script to check if process is running and act on the result

If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{ $1=""; print $0}')
    ;;
esac

It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

Just an FYI

Excel compare two columns and highlight duplicates

A1 --> conditional formatting --> cell value is B1 --> format: whatever you want

hope that helps

$(window).height() vs $(document).height

$(document).height:if your device height was bigger. Your page has Not any scroll;

$(document).height: assume you have not scroll and return this height;

$(window).height: return your page height on your device.

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

How to fix on Laravel 7:

Download the latest cacert.pem file from cURL website.

wget https://curl.haxx.se/ca/cacert.pem

Edit php.ini (you can do php --ini to find it), update (or create if they don't exist already) those two lines:

curl.cainfo="/path/to/downloaded/cacert.pem"
...
openssl.cafile="/path/to/downloaded/cacert.pem"

Those lines should already exist but commented out, so uncomment them and edit both values with the path to the downloaded cacert.pem

Restart PHP and Nginx/Apache.

Edit: You may need to chown/chmod the downloaded certificate file so PHP (and its user) can read it.

source

Save PHP array to MySQL?

you can insert serialized object ( array ) to mysql , example serialize($object) and you can unserize object example unserialize($object)

How to test if list element exists?

Use purrr::has_element to check against the value of a list element:

> x <- list(c(1, 2), c(3, 4))
> purrr::has_element(x, c(3, 4))
[1] TRUE
> purrr::has_element(x, c(3, 5))
[1] FALSE

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

In addition to bchhun's great answer, if you want absoulte positioning, you can do this

var options = {
    placement: function (context, source) {
         setTimeout(function () {
               $(context).css('top',(source.getBoundingClientRect().top+ 500) + 'px')
         },0)
         return "top";
    },
    trigger: "click"
};
$(".infopoint").popover(options);

npm ERR! network getaddrinfo ENOTFOUND

does your proxy require you to authenticate? because if it does, you might want you configure your proxy like this.

placeholder names. username is a placeholder for your actual username. password is a placeholder for your actual password. proxy.company.com is a placeholder for your actualy proxy *port" is your actualy port the proxy goes through. its usualy 8080

npm config set proxy "http://username:[email protected]:port"
npm config set https-proxy "http://username:[email protected]:port"

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

Showing empty view when ListView is empty

A programmatically solution will be:

TextView textView = new TextView(context);
textView.setId(android.R.id.empty);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("No result found");
listView.setEmptyView(textView);

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Understanding colors on Android (six characters)

Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1)
        hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}

Output:

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

A JavaScript version is below:

_x000D_
_x000D_
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
    i = Math.round(i * 100) / 100;_x000D_
    var alpha = Math.round(i * 255);_x000D_
    var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
    var perc = Math.round(i * 100);_x000D_
    text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_


You can also just Google "number to hex" where 'number' is any value between 0 and 255.

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

For (2), Guava provides exactly what you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans for boolean, etc.

    int[] arr={1,2,3};
    for(Integer i : Ints.asList(arr)) {
      System.out.println(i);
    }

Cutting the videos based on start and end time using ffmpeg

Even though I'm 6 years late, but I think all the answers above didn't properly address the question @kalai is asking. The bash script below will process a text file in the following format:

URL | start_time | end_time | filename

for example

https://www.youtube.com/watch?v=iUDURCrvrMI|00:02:02|00:03:41|1

and loop through the file, downloads the file that youtube-dl supports, calculating duration between start_time and end_time and passing it to ffmpeg, since -t is actually the duration, not the real end_time

Hit me up if you have any question.

    for i in $(<video.txt);
    do
        URL=`echo $i | cut -d "|" -f 1`;
        START=`echo $i | cut -d "|" -f 2`;
        END=`echo $i | cut -d "|" -f 3`;
        FILE=`echo $i | cut -d "|" -f 4`;

        SEC1=`echo $START | sed 's/^/((/; s/:/)*60+/g' | bc`
        SEC2=`echo $END | sed 's/^/((/; s/:/)*60+/g' | bc`

        DIFFSEC=`expr ${SEC2} - ${SEC1}`

        ffmpeg $(youtube-dl -g $URL | sed "s/.*/-ss $START -i &/") -t $DIFFSEC -c copy $FILE".mkv";
        ffmpeg -i $FILE".mkv" -f mp3 -ab 192000 -vn $FILE".mp3";
        rm $FILE".mkv";
    done;

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

What is the use of System.in.read()?

Two and a half years late is better than never, right?

int System.in.read() reads the next byte of data from the input stream. But I am sure you already knew that, because it is trivial to look up. So, what you are probably asking is:

  • Why is it declared to return an int when the documentation says that it reads a byte?

  • and why does it appear to return garbage? (I type '9', but it returns 57.)

It returns an int because besides all the possible values of a byte, it also needs to be able to return an extra value to indicate end-of-stream. So, it has to return a type which can express more values than a byte can.

Note: They could have made it a short, but they opted for int instead, possibly as a tip of the hat of historical significance to C, whose getc() function also returns an int, but more importantly because short is a bit cumbersome to work with, (the language offers no means of specifying a short literal, so you have to specify an int literal and cast it to short,) plus on certain architectures int has better performance than short.

It appears to return garbage because when you view a character as an integer, what you are looking at is the ASCII(*) value of that character. So, a '9' appears as a 57. But if you cast it to a character, you get '9', so all is well.

Think of it this way: if you typed the character '9' it is nonsensical to expect System.in.read() to return the number 9, because then what number would you expect it to return if you had typed an 'a'? Obviously, characters must be mapped to numbers. ASCII(*) is a system of mapping characters to numbers. And in this system, character '9' maps to number 57, not number 9.

(*) Not necessarily ASCII; it may be some other encoding, like UTF-16; but in the vast majority of encodings, and certainly in all popular encodings, the first 127 values are the same as ASCII. And this includes all english alphanumeric characters and popular symbols.

How do I add a border to an image in HTML?

You can also add padding for a nice effect.

<img src="image.png" style="padding:1px;border:thin solid black;">

What's the difference between KeyDown and KeyPress in .NET?

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress

How to add a tooltip to an svg graphic?

You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/

setBackground vs setBackgroundDrawable (Android)

This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)

 public void verifyDrawable (View view, int drawable){

        int sdk = Build.VERSION.SDK_INT;

        if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(
                    ContextCompat.getDrawable(getContext(),drawable));
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(getResources().getDrawable(drawable));
        }    
    }

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

When to use NSInteger vs. int

You should use NSIntegers if you need to compare them against constant values such as NSNotFound or NSIntegerMax, as these values will differ on 32-bit and 64-bit systems, so index values, counts and the like: use NSInteger or NSUInteger.

It doesn't hurt to use NSInteger in most circumstances, excepting that it takes up twice as much memory. The memory impact is very small, but if you have a huge amount of numbers floating around at any one time, it might make a difference to use ints.

If you DO use NSInteger or NSUInteger, you will want to cast them into long integers or unsigned long integers when using format strings, as new Xcode feature returns a warning if you try and log out an NSInteger as if it had a known length. You should similarly be careful when sending them to variables or arguments that are typed as ints, since you may lose some precision in the process.

On the whole, if you're not expecting to have hundreds of thousands of them in memory at once, it's easier to use NSInteger than constantly worry about the difference between the two.

Remove all subviews?

This does only apply to OSX since in iOS a copy of the array is kept

When removing all the subviews, it is a good idea to start deleting at the end of the array and keep deleting until you reach the beginning. This can be accomplished with this two lines of code:

for (int i=mySuperView.subviews.count-1; i>=0; i--)
        [[mySuperView.subviews objectAtIndex:i] removeFromSuperview];

SWIFT 1.2

for var i=mySuperView.subviews.count-1; i>=0; i-- {
    mySuperView.subviews[i].removeFromSuperview();
}

or (less efficient, but more readable)

for subview in mySuperView.subviews.reverse() {
    subview.removeFromSuperview()
}

NOTE

You should NOT remove the subviews in normal order, since it may cause a crash if a UIView instance is deleted before the removeFromSuperview message has been sent to all objects of the array. (Obviously, deleting the last element would not cause a crash)

Therefore, the code

[[someUIView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

should NOT be used.

Quote from Apple documentation about makeObjectsPerformSelector:

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

(which would be the wrong direction for this purpose)

Cannot stop or restart a docker container

Check if there is any zombie process using "top" command.

docker ps | grep <<container name>> 

Get the container id.

ps -ef | grep <<container id>>

ps -ef|grep defunct | grep java

And kill the container by Parent PID .

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use

[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }

as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:

{
  "Items": [
    {
      "$type": "Namespace.ClassA, Assembly",
      "Property": "Value"
    },
    {
      "$type": "Namespace.ClassB, Assembly",
      "Property": "Value",
      "Additional_ClassB_Property": 3
    }
  ]
}

Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.

How can you sort an array without mutating the original array?

Try the following

function sortCopy(arr) { 
  return arr.slice(0).sort();
}

The slice(0) expression creates a copy of the array starting at element 0.

MySQL root access from all hosts

Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.

Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client

sudo service mysql restart

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

Django. Override save for model

What I did to achieve the goal was to make this..

# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):

and below the save() method is this..

# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
    # your logic here

so when i edit some fields but not editing the image, I put this..

Model.save("skip creating photo thumbnail")

you can replace the "skip creating photo thumbnail" with "im just editing the description" or a more formal text.

Hope this one helps!

How can I delete a service in Windows?

Use services.msc or (Start > Control Panel > Administrative Tools > Services) to find the service in question. Double-click to see the service name and the path to the executable.

Check the exe version information for a clue as to the owner of the service, and use Add/Remove programs to do a clean uninstall if possible.

Failing that, from the command prompt:

sc stop servicexyz
sc delete servicexyz

No restart should be required.

How do I give ASP.NET permission to write to a folder in Windows 7?

Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.

If you are using II7 (and I guess you do) do the following.

  1. Open IIS7
  2. Select Website for which you need to modify permissions
  3. Go to Basic Settings and see which application pool you're using.
  4. Go to Application pools and find application pool from #3
  5. Find system account used for running this application pool (Identity column)
  6. Navigate to your storage folder in IIS, select it and click on Edit Permissions (under Actions sub menu on the right)
  7. Open security tab and add needed permissions only for user you identified in #3

Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool

Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.

How to dynamically change header based on AngularJS partial view?

Declaring ng-app on the html element provides root scope for both the head and body.

Therefore in your controller inject $rootScope and set a header property on this:

function Test1Ctrl($rootScope, $scope, $http) { $rootScope.header = "Test 1"; }

function Test2Ctrl($rootScope, $scope, $http) { $rootScope.header = "Test 2"; }

and in your page:

<title ng-bind="header"></title>

How to get client IP address in Laravel 5+

If you have multiple layer proxies just like CDN + Load Balancer.
Using Laravel Request::ip() function will get right-most proxy IP but not client IP.
You may try following solution.

app/Http/Middleware/TrustProxies.php

protected $proxies = ['0.0.0.0/0'];

Reference: https://github.com/fideloper/TrustedProxy/issues/107#issuecomment-373065215

How do you modify the web.config appSettings at runtime?

And if you want to avoid the restart of the application, you can move out the appSettings section:

<appSettings configSource="Config\appSettings.config"/>

to a separate file. And in combination with ConfigurationSaveMode.Minimal

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);

you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

HTTP POST with Json on Body - Flutter/Dart

this works for me

String body = json.encode(data);

http.Response response = await http.post(
  url: 'https://example.com',
  headers: {"Content-Type": "application/json"},
  body: body,
);

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

What are the most-used vim commands/keypresses?

What most people do is start out with the bare basics, like maybe i, yw, yy, and p. You can continue to use arrow keys to move around, selecting text with the mouse, using the menus, etc. Then when something is slowing you down, you look up the faster way to do it, and gradually add more and more commands. You might learn one new command per day for a while, then it will trickle to one per week. You'll feel fairly productive in a month. After a year you will have a pretty solid repertoire, and after 2-3 years you won't even consciously think what your fingers are typing, and it will look weird if you have to spell it out for someone. I learned vi in 1993 and still pick up 2 or 3 new commands a year.

Writing MemoryStream to Response Object

The problem for me was that my stream was not set to the origin before download.

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);

myMemoryStream.WriteTo(Response.OutputStream); 
Response.Flush();
Response.Close();

How do I find the parent directory in C#?

I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

Path.Combine makes sure you never go wrong with slashes.

.. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

Some basic .. behavior:

  1. If there is a file name, .. will chop that off:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\

  1. If the path is a directory, .. will move up a level:

Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\

  1. ..\.. follows the same rules, twice in a row:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\

  1. And this has the exact same effect:

Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:\

Spring MVC - How to return simple String as JSON in Rest Controller

This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.

My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.

The supports method makes sure that all requests that were handled by the StringHttpMessageConverter(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).

@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
    
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
        converterType === StringHttpMessageConverter::class.java

    override fun beforeBodyWrite(
        body: Any?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Any? {
        return if (request.uri.path.contains("api")) {
            response.getHeaders().contentType = MediaType.APPLICATION_JSON
            ob.writeValueAsString(body)
        } else body
    }
}

I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter should be used for the output.

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

How to check user is "logged in"?

Easiest way to check if they are authenticated is Request.User.IsAuthenticated I think (from memory)

Spring Boot and how to configure connection details to MongoDB?

It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

Get the length of a String

Updated for Xcode 6 beta 4, change method utf16count --> utf16Count

 var test1: String = "Scott"
 var length =  test1.utf16Count

Or

 var test1: String = "Scott"
 var length = test1.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)

Powershell send-mailmessage - email to multiple recipients

here is a full (gmail) and simple solution... just use normal ; delimiter.. best for passing in as params.

$to = "[email protected];[email protected]"
$user = "[email protected]"    
$pass = ConvertTo-SecureString -String "pass" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$mailParam = @{
    To = $to.Split(';')
    From = "IT Alerts <[email protected]>"
    Subject = "test"
    Body = "test"
    SmtpServer = "smtp.gmail.com"
    Port = 587
    Credential = $cred
}

Send-MailMessage @mailParam -UseSsl

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

Get type name without full namespace

Try this to get type parameters for generic types:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

Maybe not the best solution (due to the recursion), but it works. Outputs look like:

Dictionary<String, Object>

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Replacing:

$_SERVER["REMOTE_ADDR"];

With:

$_SERVER["HTTP_X_REAL_IP"];

Worked for me.

Insert an element at a specific index in a list and return the updated list

The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy:

new = old.copy()
new.insert(index, value)

On Python 2 copying the list can be achieved via new = old[:] (this also works on Python 3).

In terms of performance there is no difference to other proposed methods:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

Any decent debugger can do this. Try OllyDbg. (edit: which has a great disassembler that even decodes the parameters to WinAPI calls!)

How to $watch multiple variable change in angular


UPDATE

Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.


This should work independent of the types and values:

$scope.$watch('[age,name]', function () { ... }, true);

You have to set the third parameter to true in this case.

The string concatenation 'age + name' will fail in a case like this:

<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>

Before the user clicks the button the watched value would be 42foo (42 + foo) and after the click 42foo (4 + 2foo). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
        <script>

angular.module('demo', []).controller('MainCtrl', function ($scope) {

    $scope.firstWatchFunctionCounter = 0;
    $scope.secondWatchFunctionCounter = 0;

    $scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
    $scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});

describe('Demo module', function () {
    beforeEach(module('demo'));
    describe('MainCtrl', function () {
        it('watch function should increment a counter', inject(function ($controller, $rootScope) {
            var scope = $rootScope.$new();
            scope.age = 42;
            scope.name = 'foo';
            var ctrl = $controller('MainCtrl', { '$scope': scope });
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(1);
            expect(scope.secondWatchFunctionCounter).toBe(1);

            scope.age = 4;
            scope.name = '2foo';
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(2);
            expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
        }));
    });
});


(function () {
    var jasmineEnv = jasmine.getEnv();
    var htmlReporter = new jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter = function (spec) {
        return htmlReporter.specFilter(spec);
    };
    var currentWindowOnload = window.onload;
    window.onload = function() {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };
    function execJasmine() {
        jasmineEnv.execute();
    }
})();

        </script>
    </head>
    <body></body>
</html>

http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview

PS:

As stated by @reblace in a comment, it is of course possible to access the values:

$scope.$watch('[age,name]', function (newValue, oldValue) {
    var newAge  = newValue[0];
    var newName = newValue[1];
    var oldAge  = oldValue[0];
    var oldName = oldValue[1];
}, true);

Python regex for integer?

You are apparently using Django.

You are probably better off just using models.IntegerField() instead of models.TextField(). Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

How do I undo a checkout in git?

To undo git checkout do git checkout -, similarly to cd and cd - in shell.

Linux command line howto accept pairing for bluetooth device without pin

follow steps (CentOs):

  1. bluetoothctl
  2. devices
  3. scan on
  4. pair 34:88:5D:51:5A:95 (34:88:5D:51:5A:95 is my device code,replace it with yours)
  5. trust 34:88:5D:51:5A:95
  6. connect 34:88:5D:51:5A:95

If you want more details https://www.youtube.com/watch?v=CB1E4Ir3AV4

Attach (open) mdf file database with SQL Server Management Studio

i don't know if this answer can be found on the links above, but i just run SQL management studio as Administrator and worked. Hope it helps

Cheers

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

How to get Database Name from Connection String using SqlConnectionStringBuilder

string connectString = "Data Source=(local);" + "Integrated Security=true";

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I am able to resolved this by running below commmand

modprobe -a vboxguest vboxsf vboxvideo

Redirect Windows cmd stdout and stderr to a single file

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.

Using ffmpeg to encode a high quality video

Make sure the PNGs are fully opaque before creating the video

e.g. with imagemagick, give them a black background:

convert 0.png -background black -flatten +matte 0_opaque.png

From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency

How can I get the current screen orientation?

Activity.getResources().getConfiguration().orientation

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

Is it possible to wait until all javascript files are loaded before executing javascript code?

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

Postgres: clear entire database before re-creating / re-populating from bash script

If you want to clean your database named "example_db":

1) Login to another db(for example 'postgres'):

psql postgres

2) Remove your database:

DROP DATABASE example_db;

3) Recreate your database:

CREATE DATABASE example_db;

How do I set the figure title and axes labels font size in Matplotlib?

If you're more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

I don't know of a similar way to set the suptitle size after it's created.

How can I extract audio from video with ffmpeg?

To encode a high quality MP3 or MP4 audio from a movie file (eg AVI, MP4, MOV, etc), I find it's best to use -q:a 0 for variable bit rate and it's good practice to specify -map a to exclude video/subtitles and only grab audio:

ffmpeg -i sample.avi -q:a 0 -map a sample.mp3

If you want to extract a portion of audio from a video use the -ss option to specify the starting timestamp, and the -t option to specify the encoding duration, eg from 3 minutes and 5 seconds in for 45 seconds:

ffmpeg -i sample.avi -ss 00:03:05 -t 00:00:45.0 -q:a 0 -map a sample.mp3
  • The timestamps need to be in HH:MM:SS.xxx format or in seconds.

  • If you don't specify the -t option it will go to the end.

  • You can use the -to option instead of the -t option, if you want to specify the range, eg for 45 seconds: 00:03:05 + 45 = 00:03:50

Working example:

  1. Download ffmpeg
  2. Open a Command Prompt (Start > Run > CMD) or on a Linux/Mac open a Terminal
  3. cd to the directory with the ffmeg.exe
  4. Issue your command and wait for the output file (or troubleshoot any errors)

enter image description here

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

Using "If cell contains" in VBA excel

Dim celltxt As String
Range("C6").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltext, "TOTAL") > 0 Then
Range("C7").Select 
Selection.End(xlToRight).Select
Selection.Value = "-"
End If

You declared "celltxt" and used "celltext" in the instr.

IntelliJ: Error:java: error: release version 5 not supported

By default, your "Project bytecode version isn't set in maven project.

It thinks that your current version is 5.

Solution 1:

Just go to "Project Settings>Build, Execution...>compiler>java compiler" and then change your bytecode version to your current java version.

Solution 2:

Adding below build plugin in POM file:

 <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Use FontAwesome or Glyphicons with css :before

The accepted answer (as of 2019 JULY 29) is only still valid if you have not started using the more recent SVG-with-JS approach of FontAwesome. In which case you need to follow the instructions on their CSS Pseudo-Elements HowTo. Basically there are three things to watch out for:

  • place the data-attribute on the SCRIPT-Tag "data-search-pseudo-elements" loading the fontawesome.min.js
  • make the pseudo-element itself have display:none
  • proper font-family & font-weight combination for the icon you need: "Font Awesome 5 Free" and 300 (fal/light), 400 (far/regular) or 900 (fas/solid)

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

Different font size of strings in the same TextView

Try spannableStringbuilder. Using this we can create string with multiple font sizes.

Remove non-ascii character in string

It can also be done with a positive assertion of removal, like this:

textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");

This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx} but also the flag 'u' must present; note the regex has flags 'gu'.

I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^" says "not" and the range \x00-\x7F says "ascii," so the two together say "not ascii."

textContent = textContent.replace(/[^\x00-\x7F]/g,"");

That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.

A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":

> textContent
""
> textContent.length
7

This prompted me to want to see what was in that string.

> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"

This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B" might be inserted by CK-Editor (CKEditor).

encodeURI()  UTF-8     Unicode  html     Meaning
-----------  --------  -------  -------  -------------------
"%E2%80%8B"  EC 80 8B  U 200B   &#8203;  zero-width-space
"%E2%80%8E"  EC 80 8E  U 200E   &#8206;  left-to-right-mark
"%E2%80%8F"  EC 80 8F  U 200F   &#8207;  right-to-left-mark

Some references on those:

http://www.fileformat.info/info/unicode/char/200B/index.htm

https://en.wikipedia.org/wiki/Left-to-right_mark

Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:

https://en.wikipedia.org/wiki/UTF-8

Definitive way to trigger keypress events with jQuery

If you want to trigger the keypress or keydown event then all you have to do is:

var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);

Add table row in jQuery

If you are using Datatable JQuery plugin you can try.

oTable = $('#tblStateFeesSetup').dataTable({
            "bScrollCollapse": true,
            "bJQueryUI": true,
            ...
            ...
            //Custom Initializations.
            });

//Data Row Template of the table.
var dataRowTemplate = {};
dataRowTemplate.InvoiceID = '';
dataRowTemplate.InvoiceDate = '';
dataRowTemplate.IsOverRide = false;
dataRowTemplate.AmountOfInvoice = '';
dataRowTemplate.DateReceived = '';
dataRowTemplate.AmountReceived = '';
dataRowTemplate.CheckNumber = '';

//Add dataRow to the table.
oTable.fnAddData(dataRowTemplate);

Refer Datatables fnAddData Datatables API

How do I escape a reserved word in Oracle?

Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.

CREATE TABLE table AS ...

Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!

Change the mouse cursor on mouse over to anchor-like style

You actually don't need jQuery, just CSS. For example, here's some HTML:

<div class="special"></div>

And here's the CSS:

.special
{
    cursor: pointer;
}

Fixed page header overlaps in-page anchors

<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

This code should do the trick. Swap out 45px for the height of your header bar.

EDIT: If using jQuery is an option, I've also been successful using jQuery.localScroll with an offset value set. The offset option is a part of jQuery.scrollTo, which jQuery.localScroll is built upon. A demo is available here: http://demos.flesler.com/jquery/scrollTo/ (second window, under 'offset')

How to format strings using printf() to get equal length in the output

Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).

However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).

To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.

CSS media query to target iPad and iPad only?

I am a bit late to answer this but none of the above worked for me.

This is what worked for me

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
    //your styles here
   }

How do I create a comma-separated list from an array in PHP?

Follow this one

$teacher_id = '';

        for ($i = 0; $i < count($data['teacher_id']); $i++) {

            $teacher_id .= $data['teacher_id'][$i].',';

        }
        $teacher_id = rtrim($teacher_id, ',');
        echo $teacher_id; exit;

Get the time difference between two datetimes

If you want a localized number of days between two dates (startDate, endDate):

var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);

nbDaysStr will contain something like '3 days';

See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.

How to permanently remove few commits from remote branch

You git reset --hard your local branch to remove changes from working tree and index, and you git push --force your revised local branch to the remote. (other solution here, involving deleting the remote branch, and re-pushing it)

This SO answer illustrates the danger of such a command, especially if people depends on the remote history for their own local repos.
You need to be prepared to point out people to the RECOVERING FROM UPSTREAM REBASE section of the git rebase man page


With Git 2.23 (August 2019, nine years later), you would use the new command git switch.
That is: git switch -C mybranch origin/mybranch~n
(replace n by the number of commits to remove)

That will restore the index and working tree, like a git reset --hard would.
The documentation adds:

-C <new-branch>
--force-create <new-branch>

Similar to --create except that if <new-branch> already exists, it will be reset to <start-point>.
This is a convenient shortcut for:

$ git branch -f <new-branch>
$ git switch <new-branch>

select2 onchange event only works once

My select2 element was not firing the onchange event as the drop down list offered only one value, making it impossible to change the value.

The value not having changed, no event was fired and the handler could not execute.

I then added another handler to clear the value, with the select2-open handler being executed before the onchange handler.

The source code now looks like:

el.on("select2-open", function(e) {
    $(this).val('');
});
el.on('change', function() {
    ...
});

The first handler clears the value, allowing the second handler to fire up even if selecting the same value.

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2