Programs & Examples On #Typeinfo

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

How to export a CSV to Excel using Powershell

I had some problem getting the other examples to work.

EPPlus and other libraries produces OpenDocument Xml format, which is not the same as you get when you save from Excel as xlsx.

macks example with open CSV and just re-saving didn't work, I never managed to get the ',' delimiter to be used correctly.

Ansgar Wiechers example has some slight error which I found the answer for in the commencts.

Anyway, this is a complete working example. Save this in a File CsvToExcel.ps1

param (
[Parameter(Mandatory=$true)][string]$inputfile,
[Parameter(Mandatory=$true)][string]$outputfile
)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false

$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

write-output "Opening $inputfile"

$i = 1
Import-Csv $inputfile | Foreach-Object { 
    $j = 1
    foreach ($prop in $_.PSObject.Properties)
    {
        if ($i -eq 1) {
            $ws.Cells.Item($i, $j) = $prop.Name
        } else {
            $ws.Cells.Item($i, $j) = $prop.Value
        }
        $j++
    }
    $i++
}

$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"

Execute with:

.\CsvToExcel.ps1 -inputfile "C:\Temp\X\data.csv" -outputfile "C:\Temp\X\data.xlsx"

Converting LastLogon to DateTime format

DateTime.FromFileTime should do the trick:

PS C:\> [datetime]::FromFileTime(129948127853609000)

Monday, October 15, 2012 3:13:05 PM

Then depending on how you want to format it, check out standard and custom datetime format strings.

PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM

If you want to integrate this into your one-liner, change your select statement to this:

... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

I can't understand why this JAXB IllegalAnnotationException is thrown

I had this same issue, I was passing a spring bean back as a ResponseBody object. When I handed back an object created by new, all was good.

Parsing JSON in Excel VBA

UPDATE 3 (Sep 24 '17)

Check VBA-JSON-parser on GitHub for the latest version and examples. Import JSON.bas module into the VBA project for JSON processing.

UPDATE 2 (Oct 1 '16)

However if you do want to parse JSON on 64-bit Office with ScriptControl, then this answer may help you to get ScriptControl to work on 64-bit.

UPDATE (Oct 26 '15)

Note that a ScriptControl-based approachs makes the system vulnerable in some cases, since they allows a direct access to the drives (and other stuff) for the malicious JS code via ActiveX's. Let's suppose you are parsing web server response JSON, like JsonString = "{a:(function(){(new ActiveXObject('Scripting.FileSystemObject')).CreateTextFile('C:\\Test.txt')})()}". After evaluating it you'll find new created file C:\Test.txt. So JSON parsing with ScriptControl ActiveX is not a good idea.

Trying to avoid that, I've created JSON parser based on RegEx's. Objects {} are represented by dictionaries, that makes possible to use dictionary's properties and methods: .Count, .Exists(), .Item(), .Items, .Keys. Arrays [] are the conventional zero-based VB arrays, so UBound() shows the number of elements. Here is the code with some usage examples:

Option Explicit

Sub JsonTest()
    Dim strJsonString As String
    Dim varJson As Variant
    Dim strState As String
    Dim varItem As Variant

    ' parse JSON string to object
    ' root element can be the object {} or the array []
    strJsonString = "{""a"":[{}, 0, ""value"", [{""stuff"":""content""}]], b:null}"
    ParseJson strJsonString, varJson, strState

    ' checking the structure step by step
    Select Case False ' if any of the checks is False, the sequence is interrupted
        Case IsObject(varJson) ' if root JSON element is object {},
        Case varJson.Exists("a") ' having property a,
        Case IsArray(varJson("a")) ' which is array,
        Case UBound(varJson("a")) >= 3 ' having not less than 4 elements,
        Case IsArray(varJson("a")(3)) ' where forth element is array,
        Case UBound(varJson("a")(3)) = 0 ' having the only element,
        Case IsObject(varJson("a")(3)(0)) ' which is object,
        Case varJson("a")(3)(0).Exists("stuff") ' having property stuff,
        Case Else
            MsgBox "Check the structure step by step" & vbCrLf & varJson("a")(3)(0)("stuff") ' then show the value of the last one property.
    End Select

    ' direct access to the property if sure of structure
    MsgBox "Direct access to the property" & vbCrLf & varJson.Item("a")(3)(0).Item("stuff") ' content

    ' traversing each element in array
    For Each varItem In varJson("a")
        ' show the structure of the element
        MsgBox "The structure of the element:" & vbCrLf & BeautifyJson(varItem)
    Next

    ' show the full structure starting from root element
    MsgBox "The full structure starting from root element:" & vbCrLf & BeautifyJson(varJson)

End Sub

Sub BeautifyTest()
    ' put sourse JSON string to "desktop\source.json" file
    ' processed JSON will be saved to "desktop\result.json" file
    Dim strDesktop As String
    Dim strJsonString As String
    Dim varJson As Variant
    Dim strState As String
    Dim strResult As String
    Dim lngIndent As Long

    strDesktop = CreateObject("WScript.Shell").SpecialFolders.Item("Desktop")
    strJsonString = ReadTextFile(strDesktop & "\source.json", -2)
    ParseJson strJsonString, varJson, strState
    If strState <> "Error" Then
        strResult = BeautifyJson(varJson)
        WriteTextFile strResult, strDesktop & "\result.json", -1
    End If
    CreateObject("WScript.Shell").PopUp strState, 1, , 64
End Sub

Sub ParseJson(ByVal strContent As String, varJson As Variant, strState As String)
    ' strContent - source JSON string
    ' varJson - created object or array to be returned as result
    ' strState - Object|Array|Error depending on processing to be returned as state
    Dim objTokens As Object
    Dim objRegEx As Object
    Dim bMatched As Boolean

    Set objTokens = CreateObject("Scripting.Dictionary")
    Set objRegEx = CreateObject("VBScript.RegExp")
    With objRegEx
        ' specification http://www.json.org/
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = """(?:\\""|[^""])*""(?=\s*(?:,|\:|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "str"
        .Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)e(?:[+-])?\d+(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "num"
        .Pattern = "(?:[+-])?(?:\d+\.\d*|\.\d+|\d+)(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "num"
        .Pattern = "\b(?:true|false|null)(?=\s*(?:,|\]|\}))"
        Tokenize objTokens, objRegEx, strContent, bMatched, "cst"
        .Pattern = "\b[A-Za-z_]\w*(?=\s*\:)" ' unspecified name without quotes
        Tokenize objTokens, objRegEx, strContent, bMatched, "nam"
        .Pattern = "\s"
        strContent = .Replace(strContent, "")
        .MultiLine = False
        Do
            bMatched = False
            .Pattern = "<\d+(?:str|nam)>\:<\d+(?:str|num|obj|arr|cst)>"
            Tokenize objTokens, objRegEx, strContent, bMatched, "prp"
            .Pattern = "\{(?:<\d+prp>(?:,<\d+prp>)*)?\}"
            Tokenize objTokens, objRegEx, strContent, bMatched, "obj"
            .Pattern = "\[(?:<\d+(?:str|num|obj|arr|cst)>(?:,<\d+(?:str|num|obj|arr|cst)>)*)?\]"
            Tokenize objTokens, objRegEx, strContent, bMatched, "arr"
        Loop While bMatched
        .Pattern = "^<\d+(?:obj|arr)>$" ' unspecified top level array
        If Not (.Test(strContent) And objTokens.Exists(strContent)) Then
            varJson = Null
            strState = "Error"
        Else
            Retrieve objTokens, objRegEx, strContent, varJson
            strState = IIf(IsObject(varJson), "Object", "Array")
        End If
    End With
End Sub

Sub Tokenize(objTokens, objRegEx, strContent, bMatched, strType)
    Dim strKey As String
    Dim strRes As String
    Dim lngCopyIndex As Long
    Dim objMatch As Object

    strRes = ""
    lngCopyIndex = 1
    With objRegEx
        For Each objMatch In .Execute(strContent)
            strKey = "<" & objTokens.Count & strType & ">"
            bMatched = True
            With objMatch
                objTokens(strKey) = .Value
                strRes = strRes & Mid(strContent, lngCopyIndex, .FirstIndex - lngCopyIndex + 1) & strKey
                lngCopyIndex = .FirstIndex + .Length + 1
            End With
        Next
        strContent = strRes & Mid(strContent, lngCopyIndex, Len(strContent) - lngCopyIndex + 1)
    End With
End Sub

Sub Retrieve(objTokens, objRegEx, strTokenKey, varTransfer)
    Dim strContent As String
    Dim strType As String
    Dim objMatches As Object
    Dim objMatch As Object
    Dim strName As String
    Dim varValue As Variant
    Dim objArrayElts As Object

    strType = Left(Right(strTokenKey, 4), 3)
    strContent = objTokens(strTokenKey)
    With objRegEx
        .Global = True
        Select Case strType
            Case "obj"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)
                Set varTransfer = CreateObject("Scripting.Dictionary")
                For Each objMatch In objMatches
                    Retrieve objTokens, objRegEx, objMatch.Value, varTransfer
                Next
            Case "prp"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)

                Retrieve objTokens, objRegEx, objMatches(0).Value, strName
                Retrieve objTokens, objRegEx, objMatches(1).Value, varValue
                If IsObject(varValue) Then
                    Set varTransfer(strName) = varValue
                Else
                    varTransfer(strName) = varValue
                End If
            Case "arr"
                .Pattern = "<\d+\w{3}>"
                Set objMatches = .Execute(strContent)
                Set objArrayElts = CreateObject("Scripting.Dictionary")
                For Each objMatch In objMatches
                    Retrieve objTokens, objRegEx, objMatch.Value, varValue
                    If IsObject(varValue) Then
                        Set objArrayElts(objArrayElts.Count) = varValue
                    Else
                        objArrayElts(objArrayElts.Count) = varValue
                    End If
                    varTransfer = objArrayElts.Items
                Next
            Case "nam"
                varTransfer = strContent
            Case "str"
                varTransfer = Mid(strContent, 2, Len(strContent) - 2)
                varTransfer = Replace(varTransfer, "\""", """")
                varTransfer = Replace(varTransfer, "\\", "\")
                varTransfer = Replace(varTransfer, "\/", "/")
                varTransfer = Replace(varTransfer, "\b", Chr(8))
                varTransfer = Replace(varTransfer, "\f", Chr(12))
                varTransfer = Replace(varTransfer, "\n", vbLf)
                varTransfer = Replace(varTransfer, "\r", vbCr)
                varTransfer = Replace(varTransfer, "\t", vbTab)
                .Global = False
                .Pattern = "\\u[0-9a-fA-F]{4}"
                Do While .Test(varTransfer)
                    varTransfer = .Replace(varTransfer, ChrW(("&H" & Right(.Execute(varTransfer)(0).Value, 4)) * 1))
                Loop
            Case "num"
                varTransfer = Evaluate(strContent)
            Case "cst"
                Select Case LCase(strContent)
                    Case "true"
                        varTransfer = True
                    Case "false"
                        varTransfer = False
                    Case "null"
                        varTransfer = Null
                End Select
        End Select
    End With
End Sub

Function BeautifyJson(varJson As Variant) As String
    Dim strResult As String
    Dim lngIndent As Long
    BeautifyJson = ""
    lngIndent = 0
    BeautyTraverse BeautifyJson, lngIndent, varJson, vbTab, 1
End Function

Sub BeautyTraverse(strResult As String, lngIndent As Long, varElement As Variant, strIndent As String, lngStep As Long)
    Dim arrKeys() As Variant
    Dim lngIndex As Long
    Dim strTemp As String

    Select Case VarType(varElement)
        Case vbObject
            If varElement.Count = 0 Then
                strResult = strResult & "{}"
            Else
                strResult = strResult & "{" & vbCrLf
                lngIndent = lngIndent + lngStep
                arrKeys = varElement.Keys
                For lngIndex = 0 To UBound(arrKeys)
                    strResult = strResult & String(lngIndent, strIndent) & """" & arrKeys(lngIndex) & """" & ": "
                    BeautyTraverse strResult, lngIndent, varElement(arrKeys(lngIndex)), strIndent, lngStep
                    If Not (lngIndex = UBound(arrKeys)) Then strResult = strResult & ","
                    strResult = strResult & vbCrLf
                Next
                lngIndent = lngIndent - lngStep
                strResult = strResult & String(lngIndent, strIndent) & "}"
            End If
        Case Is >= vbArray
            If UBound(varElement) = -1 Then
                strResult = strResult & "[]"
            Else
                strResult = strResult & "[" & vbCrLf
                lngIndent = lngIndent + lngStep
                For lngIndex = 0 To UBound(varElement)
                    strResult = strResult & String(lngIndent, strIndent)
                    BeautyTraverse strResult, lngIndent, varElement(lngIndex), strIndent, lngStep
                    If Not (lngIndex = UBound(varElement)) Then strResult = strResult & ","
                    strResult = strResult & vbCrLf
                Next
                lngIndent = lngIndent - lngStep
                strResult = strResult & String(lngIndent, strIndent) & "]"
            End If
        Case vbInteger, vbLong, vbSingle, vbDouble
            strResult = strResult & varElement
        Case vbNull
            strResult = strResult & "Null"
        Case vbBoolean
            strResult = strResult & IIf(varElement, "True", "False")
        Case Else
            strTemp = Replace(varElement, "\""", """")
            strTemp = Replace(strTemp, "\", "\\")
            strTemp = Replace(strTemp, "/", "\/")
            strTemp = Replace(strTemp, Chr(8), "\b")
            strTemp = Replace(strTemp, Chr(12), "\f")
            strTemp = Replace(strTemp, vbLf, "\n")
            strTemp = Replace(strTemp, vbCr, "\r")
            strTemp = Replace(strTemp, vbTab, "\t")
            strResult = strResult & """" & strTemp & """"
    End Select

End Sub

Function ReadTextFile(strPath As String, lngFormat As Long) As String
    ' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
        ReadTextFile = ""
        If Not .AtEndOfStream Then ReadTextFile = .ReadAll
        .Close
    End With
End Function

Sub WriteTextFile(strContent As String, strPath As String, lngFormat As Long)
    With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 2, True, lngFormat)
        .Write (strContent)
        .Close
    End With
End Sub

One more opportunity of this JSON RegEx parser is that it works on 64-bit Office, where ScriptControl isn't available.

INITIAL (May 27 '15)

Here is one more method to parse JSON in VBA, based on ScriptControl ActiveX, without external libraries:

Sub JsonTest()

    Dim Dict, Temp, Text, Keys, Items

    ' Converting JSON string to appropriate nested dictionaries structure
    ' Dictionaries have numeric keys for JSON Arrays, and string keys for JSON Objects
    ' Returns Nothing in case of any JSON syntax issues
    Set Dict = GetJsonDict("{a:[[{stuff:'result'}]], b:''}")
    ' You can use For Each ... Next and For ... Next loops through keys and items
    Keys = Dict.Keys
    Items = Dict.Items

    ' Referring directly to the necessary property if sure, without any checks
    MsgBox Dict("a")(0)(0)("stuff")

    ' Auxiliary DrillDown() function
    ' Drilling down the structure, sequentially checking if each level exists
    Select Case False
    Case DrillDown(Dict, "a", Temp, "")
    Case DrillDown(Temp, 0, Temp, "")
    Case DrillDown(Temp, 0, Temp, "")
    Case DrillDown(Temp, "stuff", "", Text)
    Case Else
        ' Structure is consistent, requested value found
        MsgBox Text
    End Select

End Sub

Function GetJsonDict(JsonString As String)
    With CreateObject("ScriptControl")
        .Language = "JScript"
        .ExecuteStatement "function gettype(sample) {return {}.toString.call(sample).slice(8, -1)}"
        .ExecuteStatement "function evaljson(json, er) {try {var sample = eval('(' + json + ')'); var type = gettype(sample); if(type != 'Array' && type != 'Object') {return er;} else {return getdict(sample);}} catch(e) {return er;}}"
        .ExecuteStatement "function getdict(sample) {var type = gettype(sample); if(type != 'Array' && type != 'Object') return sample; var dict = new ActiveXObject('Scripting.Dictionary'); if(type == 'Array') {for(var key = 0; key < sample.length; key++) {dict.add(key, getdict(sample[key]));}} else {for(var key in sample) {dict.add(key, getdict(sample[key]));}} return dict;}"
        Set GetJsonDict = .Run("evaljson", JsonString, Nothing)
    End With
End Function

Function DrillDown(Source, Prop, Target, Value)
    Select Case False
    Case TypeName(Source) = "Dictionary"
    Case Source.exists(Prop)
    Case Else
        Select Case True
        Case TypeName(Source(Prop)) = "Dictionary"
            Set Target = Source(Prop)
            Value = Empty
        Case IsObject(Source(Prop))
            Set Value = Source(Prop)
            Set Target = Nothing
        Case Else
            Value = Source(Prop)
            Set Target = Nothing
        End Select
        DrillDown = True
        Exit Function
    End Select
    DrillDown = False
End Function

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

C++ static virtual members?

First, the replies are correct that what the OP is requesting is a contradiction in terms: virtual methods depend on the run-time type of an instance; static functions specifically don't depend on an instance -- just on a type. That said, it makes sense to have static functions return something specific to a type. For example, I had a family of MouseTool classes for the State pattern and I started having each one have a static function returning the keyboard modifier that went with it; I used those static functions in the factory function that made the correct MouseTool instance. That function checked the mouse state against MouseToolA::keyboardModifier(), MouseToolB::keyboardModifier(), etc. and then instantiated the appropriate one. Of course later I wanted to check if the state was right so I wanted write something like "if (keyboardModifier == dynamic_type(*state)::keyboardModifier())" (not real C++ syntax), which is what this question is asking.

So, if you find yourself wanting this, you may want to rething your solution. Still, I understand the desire to have static methods and then call them dynamically based on the dynamic type of an instance. I think the Visitor Pattern can give you what you want. It gives you what you want. It's a bit of extra code, but it could be useful for other visitors.

See: http://en.wikipedia.org/wiki/Visitor_pattern for background.

struct ObjectVisitor;

struct Object
{
     struct TypeInformation;

     static TypeInformation GetTypeInformation();
     virtual void accept(ObjectVisitor& v);
};

struct SomeObject : public Object
{
     static TypeInformation GetTypeInformation();
     virtual void accept(ObjectVisitor& v) const;
};

struct AnotherObject : public Object
{
     static TypeInformation GetTypeInformation();
     virtual void accept(ObjectVisitor& v) const;
};

Then for each concrete Object:

void SomeObject::accept(ObjectVisitor& v) const {
    v.visit(*this); // The compiler statically picks the visit method based on *this being a const SomeObject&.
}
void AnotherObject::accept(ObjectVisitor& v) const {
    v.visit(*this); // Here *this is a const AnotherObject& at compile time.
}

and then define the base visitor:

struct ObjectVisitor {
    virtual ~ObjectVisitor() {}
    virtual void visit(const SomeObject& o) {} // Or = 0, depending what you feel like.
    virtual void visit(const AnotherObject& o) {} // Or = 0, depending what you feel like.
    // More virtual void visit() methods for each Object class.
};

Then the concrete visitor that selects the appropriate static function:

struct ObjectVisitorGetTypeInfo {
    Object::TypeInformation result;
    virtual void visit(const SomeObject& o) {
        result = SomeObject::GetTypeInformation();
    }
    virtual void visit(const AnotherObject& o) {
        result = AnotherObject::GetTypeInformation();
    }
    // Again, an implementation for each concrete Object.
};

finally, use it:

void printInfo(Object& o) {
    ObjectVisitorGetTypeInfo getTypeInfo;
    Object::TypeInformation info = o.accept(getTypeInfo).result;
    std::cout << info << std::endl;
}

Notes:

  • Constness left as an exercise.
  • You returned a reference from a static. Unless you have a singleton, that's questionable.

If you want to avoid copy-paste errors where one of your visit methods calls the wrong static function, you could use a templated helper function (which can't itself be virtual) t your visitor with a template like this:

struct ObjectVisitorGetTypeInfo {
    Object::TypeInformation result;
    virtual void visit(const SomeObject& o) { doVisit(o); }
    virtual void visit(const AnotherObject& o) { doVisit(o); }
    // Again, an implementation for each concrete Object.

  private:
    template <typename T>
    void doVisit(const T& o) {
        result = T::GetTypeInformation();
    }
};

g++ undefined reference to typeinfo

Possible solutions for code that deal with RTTI and non-RTTI libraries:

a) Recompile everything with either -frtti or -fno-rtti
b) If a) is not possible for you, try the following:

Assume libfoo is built without RTTI. Your code uses libfoo and compiles with RTTI. If you use a class (Foo) in libfoo that has virtuals, you're likely to run into a link-time error that says: missing typeinfo for class Foo.

Define another class (e.g. FooAdapter) that has no virtual and will forward calls to Foo that you use.

Compile FooAdapter in a small static library that doesn't use RTTI and only depends on libfoo symbols. Provide a header for it and use that instead in your code (which uses RTTI). Since FooAdapter has no virtual function it won't have any typeinfo and you'll be able to link your binary. If you use a lot of different classes from libfoo, this solution may not be convenient, but it's a start.

How to convert a Kotlin source file to a Java source file

  1. open kotlin file in android studio
  2. go to tools -> kotlin ->kotlin bytecode
  3. in the new window that open beside your kotlin file , click the decompile button . it will create java equivalent of your kotlin file .

How to set conditional breakpoints in Visual Studio?

Create a conditional function breakpoint:

  1. In the Breakpoints window, click New to create a new breakpoint.

  2. On the Function tab, type Reverse for Function. Type 1 for Line, type 1 for Character, and then set Language to Basic.

  3. Click Condition and make sure that the Condition checkbox is selected. Type instr.length > 0 for Condition, make sure that the is true option is selected, and then click OK.

  4. In the New Breakpoint dialog box, click OK.

  5. On the Debug menu, click Start.

Python error "ImportError: No module named"

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.

How to run shell script file using nodejs?

You can execute any shell command using the shelljs module

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

How to auto resize and adjust Form controls with change in resolution

Use Dock and Anchor properties. Here is a good article. Note that these will handle changes when maximizing/minimizing. That is a little different that if the screen resolution changes, but it will be along the same idea.

Initialize/reset struct to zero/null

I believe you can just assign the empty set ({}) to your variable.

struct x instance;

for(i = 0; i < n; i++) {
    instance = {};
    /* Do Calculations */
}

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

Error: macro names must be identifiers using #ifdef 0

#ifdef 0
...
#endif

#ifdef expect a macro rather than expression when using constant or expression

#if 0
...
#endif

or

#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

if #ifdef is used the it reports this error

#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

Where #ifdef expect a macro rather than macro expresssion

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Hiding the address bar of a browser (popup)

It's different in every browser.

Some years ago, what you tried, was right. But nowadays it is regarded as a security risk by browser vendors that one cannot see the browsers address bar (for phishing reasons) and so they (or most of them) made the decision to always show the browser address bar. Which is good in my eyes.

How to set multiple commands in one yaml file with Kubernetes?

Just to bring another possible option, secrets can be used as they are presented to the pod as volumes:

Secret example:

apiVersion: v1
kind: Secret 
metadata:
  name: secret-script
type: Opaque
data:
  script_text: <<your script in b64>>

Yaml extract:

....
containers:
    - name: container-name
      image: image-name
      command: ["/bin/bash", "/your_script.sh"]
      volumeMounts:
        - name: vsecret-script
          mountPath: /your_script.sh
          subPath: script_text
....
  volumes:
    - name: vsecret-script
      secret:
        secretName: secret-script

I know many will argue this is not what secrets must be used for, but it is an option.

How to convert .pem into .key?

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

You can try this before using job_titles string:

source = unicode(job_titles, 'utf-8')

ImportError: no module named win32api

The following should work:

pip install pywin32

But it didn't for me. I fixed this by downloading and installing the exe from here:

https://github.com/mhammond/pywin32/releases

JSLint says "missing radix parameter"

Simply add your custom rule in .eslintrc which looks like that "radix": "off" and you will be free of this eslint unnesesery warning. This is for the eslint linter.

Cast a Double Variable to Decimal

Convert.ToDecimal(the double you are trying to convert);

Python Dictionary Comprehension

The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.

Instead of writing

l = []
for n in range(1, 11):
    l.append(n)

or

l = [n for n in range(1, 11)]

you should write only

l = range(1, 11)

In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.

To get a new dictionary with all keys set to the same value based on another dict, do this:

old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}

You're receiving a SyntaxError because when you write

d = {}
d[i for i in range(1, 11)] = True

you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like

d[[i for i in range(1, 11)]] = True

and not

d[i for i in range(1, 11)] = True

but lists are not hashable, so you can't use them as dict keys.

Convert LocalDateTime to LocalDateTime in UTC

you can implement a helper doing something like that :

public static LocalDateTime convertUTCFRtoUTCZ(LocalDateTime dateTime) {
    ZoneId fr = ZoneId.of("Europe/Paris");
    ZoneId utcZ = ZoneId.of("Z");
    ZonedDateTime frZonedTime = ZonedDateTime.of(dateTime, fr);
    ZonedDateTime utcZonedTime = frZonedTime.withZoneSameInstant(utcZ);
    return utcZonedTime.toLocalDateTime();
}

Process to convert simple Python script into Windows executable

You could create an installer for you EXE file by:
1. Press WinKey + R
2. Type "iexpress" (without quotes) into the run window
3. Complete the wizard for creating the installation program.
4. Distribute the completed EXE.

How to assign from a function which returns more than one value?

Usually I wrap the output into a list, which is very flexible (you can have any combination of numbers, strings, vectors, matrices, arrays, lists, objects int he output)

so like:

func2<-function(input) {
   a<-input+1
   b<-input+2
   output<-list(a,b)
   return(output)
}

output<-func2(5)

for (i in output) {
   print(i)
}

[1] 6
[1] 7

What is the difference between tree depth and height?

I wanted to make this post because I'm an undergrad CS student and more and more we use OpenDSA and other open source textbooks. It seems like from the top rated answer that the way height and depth is being taught has changed from one generation to the next, and I'm posting this so everyone is aware that this discrepancy now exists and hopefully won't cause bugs in any programs! Thanks.

From the OpenDSA Data Structures & Algos book:

If n1, n2,...,nk is a sequence of nodes in the tree such that ni is the parent of ni+1 for 1<=i<k, then this sequence is called a path from n1 to nk. The length of the path is k-1. If there is a path from node R to node M, then R is an ancestor of M, and M is a descendant of R. Thus, all nodes in the tree are descendants of the root of the tree, while the root is the ancestor of all nodes. The depth of a node M in the tree is the length of the path from the root of the tree to M. The height of a tree is one more than the depth of the deepest node in the tree. All nodes of depth d are at level d in the tree. The root is the only node at level 0, and its depth is 0.

Figure 7.2.1

Figure 7.2.1: A binary tree. Node A is the root. Nodes B and C are A's children. Nodes B and D together form a subtree. Node B has two children: Its left child is the empty tree and its right child is D. Nodes A, C, and E are ancestors of G. Nodes D, E, and F make up level 2 of the tree; node A is at level 0. The edges from A to C to E to G form a path of length 3. Nodes D, G, H, and I are leaves. Nodes A, B, C, E, and F are internal nodes. The depth of I is 3. The height of this tree is 4.

Xcode 6 Storyboard the wrong size?

Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.

Recommended SQL database design for tags or tagging

I would suggest following design : Item Table: Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.

In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.

Now while searching for items for a tag it will be super fast.

How to show an empty view with a RecyclerView?

if you want to display a text view when the recycler view is empty you can do it like this :

ArrayList<SomeDataModel> arrayList = new ArrayList<>();

RecycleAdapter recycleAdapter =  new RecycleAdapter(getContext(),project_Ideas);

recyclerView..setAdapter(recycleAdapter);

if(arrayList.isEmpty())
{
    emptyTextView.setVisibility(View.VISIBLE);
    recyclerView.setVisibility(View.GONE);
}

I Assume you have TextView

and XML like this

 android:visibility="gone"

    
  

Error on renaming database in SQL Server 2008 R2

Change database to single user mode as shown in the other answers

Sometimes, even after converting to single user mode, the only connection allowed to the database may be in use.

To close a connection even after converting to single user mode try:

select * from master.sys.sysprocesses
where spid>50 -- don't want system sessions
  and dbid = DB_ID('BOSEVIKRAM')

Look at the results and see the ID of the connection to the database in question.

Then use the command below to close this connection (there should only be one since the database is now in single user mode)

KILL connection_ID

Replace connection_id with the ID in the results of the 1st query

Greater than and less than in one statement

Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

How to convert an array to a string in PHP?

serialize() and unserialize() convert between php objects and a string representation.

Splitting dataframe into multiple dataframes

You can use the groupby command, if you already have some labels for your data.

 out_list = [group[1] for group in in_series.groupby(label_series.values)]

Here's a detailed example:

Let's say we want to partition a pd series using some labels into a list of chunks For example, in_series is:

2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00    1.16
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 5, dtype: float64

And its corresponding label_series is:

2019-07-01 08:00:00   1
2019-07-01 08:02:00   1
2019-07-01 08:04:00   2
2019-07-01 08:06:00   2
2019-07-01 08:08:00   2
Length: 5, dtype: float64

Run

out_list = [group[1] for group in in_series.groupby(label_series.values)]

which returns out_list a list of two pd.Series:

[2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00   1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 3, dtype: float64]

Note that you can use some parameters from in_series itself to group the series, e.g., in_series.index.day

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Personally, I have create a file.sh (right 755) in the root directory, file who do this job, on order of the crontab.

Crontab code:

10 2 * * * root /root/backupautomatique.sh

File.sh code:

rm -f /home/mordb-148-251-89-66.sql.gz #(To erase the old one)

mysqldump mor | gzip > /home/mordb-148-251-89-66.sql.gz (what you have done)

scp -P2222 /home/mordb-148-251-89-66.sql.gz root@otherip:/home/mordbexternes/mordb-148-251-89-66.sql.gz

(to send a copy somewhere else if the sending server crashes, because too old, like me ;-))

Printing with sed or awk a line following a matching pattern

awk Version:

awk '/regexp/ { getline; print $0; }' filetosearch

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.

  • Click on Configure ( As Soon Android studio open )
  • Click Project Default
  • Click Project Structure
  • Clik Android Sdk Location

  • Select & Browse your Android SDK Location (Like: C:\Android\sdk)

  • Uncheck USE EMBEDDED JDK LOCATION

  • Set & Browse JDK Location, Like C:\Program Files\Java\jdk1.8.0_121

Android : Check whether the phone is dual SIM

Update 23 March'15 :

Official multiple SIM API is available now from Android 5.1 onwards

Other possible option :

You can use Java reflection to get both IMEI numbers.

Using these IMEI numbers you can check whether the phone is a DUAL SIM or not.

Try following activity :

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);

        String imeiSIM1 = telephonyInfo.getImsiSIM1();
        String imeiSIM2 = telephonyInfo.getImsiSIM2();

        boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
        boolean isSIM2Ready = telephonyInfo.isSIM2Ready();

        boolean isDualSIM = telephonyInfo.isDualSIM();

        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(" IME1 : " + imeiSIM1 + "\n" +
                " IME2 : " + imeiSIM2 + "\n" +
                " IS DUAL SIM : " + isDualSIM + "\n" +
                " IS SIM1 READY : " + isSIM1Ready + "\n" +
                " IS SIM2 READY : " + isSIM2Ready + "\n");
    }
}

And here is TelephonyInfo.java :

import java.lang.reflect.Method;

import android.content.Context;
import android.telephony.TelephonyManager;

public final class TelephonyInfo {

    private static TelephonyInfo telephonyInfo;
    private String imeiSIM1;
    private String imeiSIM2;
    private boolean isSIM1Ready;
    private boolean isSIM2Ready;

    public String getImsiSIM1() {
        return imeiSIM1;
    }

    /*public static void setImsiSIM1(String imeiSIM1) {
        TelephonyInfo.imeiSIM1 = imeiSIM1;
    }*/

    public String getImsiSIM2() {
        return imeiSIM2;
    }

    /*public static void setImsiSIM2(String imeiSIM2) {
        TelephonyInfo.imeiSIM2 = imeiSIM2;
    }*/

    public boolean isSIM1Ready() {
        return isSIM1Ready;
    }

    /*public static void setSIM1Ready(boolean isSIM1Ready) {
        TelephonyInfo.isSIM1Ready = isSIM1Ready;
    }*/

    public boolean isSIM2Ready() {
        return isSIM2Ready;
    }

    /*public static void setSIM2Ready(boolean isSIM2Ready) {
        TelephonyInfo.isSIM2Ready = isSIM2Ready;
    }*/

    public boolean isDualSIM() {
        return imeiSIM2 != null;
    }

    private TelephonyInfo() {
    }

    public static TelephonyInfo getInstance(Context context){

        if(telephonyInfo == null) {

            telephonyInfo = new TelephonyInfo();

            TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));

            telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();;
            telephonyInfo.imeiSIM2 = null;

            try {
                telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
                telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
            } catch (GeminiMethodNotFoundException e) {
                e.printStackTrace();

                try {
                    telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
                    telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }

            telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
            telephonyInfo.isSIM2Ready = false;

            try {
                telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
                telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
            } catch (GeminiMethodNotFoundException e) {

                e.printStackTrace();

                try {
                    telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
                    telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }
        }

        return telephonyInfo;
    }

    private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        String imei = null;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimID.invoke(telephony, obParameter);

            if(ob_phone != null){
                imei = ob_phone.toString();

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return imei;
    }

    private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        boolean isReady = false;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);

            if(ob_phone != null){
                int simState = Integer.parseInt(ob_phone.toString());
                if(simState == TelephonyManager.SIM_STATE_READY){
                    isReady = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return isReady;
    }


    private static class GeminiMethodNotFoundException extends Exception {

        private static final long serialVersionUID = -996812356902545308L;

        public GeminiMethodNotFoundException(String info) {
            super(info);
        }
    }
}

Edit :

Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist.

If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices.

Finding method names for other manufacturers can be done using Java reflection as follows :

public static void printTelephonyManagerMethodNamesForThisDevice(Context context) {

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    Class<?> telephonyClass;
    try {
        telephonyClass = Class.forName(telephony.getClass().getName());
        Method[] methods = telephonyClass.getMethods();
        for (int idx = 0; idx < methods.length; idx++) {

            System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass());
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
} 

EDIT :

As Seetha pointed out in her comment :

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1); 

It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device.

Add <uses-permission android:name="android.permission.READ_PHONE_STATE" />

EDIT 2 :

The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa):

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0); 
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1); 

How to check if a String contains only ASCII?

Iterate through the string and make sure all the characters have a value less than 128.

Java Strings are conceptually encoded as UTF-16. In UTF-16, the ASCII character set is encoded as the values 0 - 127 and the encoding for any non ASCII character (which may consist of more than one Java char) is guaranteed not to include the numbers 0 - 127

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.

...

How to delete a remote tag?

For tortoise git users, at a scale of hundreds tags, you can delete multiple tags at once using UI, but the UI is well hidden under context menu.

From explorer windows right click -> Browse references -> Right click on ref/refmotes/name -> choose 'Delete remote tags'

enter image description here

See https://tortoisegit.org/docs/tortoisegit/tgit-dug-browse-ref.html

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Make an existing Git branch track a remote branch?

Given a branch foo and a remote upstream:

As of Git 1.8.0:

git branch -u upstream/foo

Or, if local branch foo is not the current branch:

git branch -u upstream/foo foo

Or, if you like to type longer commands, these are equivalent to the above two:

git branch --set-upstream-to=upstream/foo

git branch --set-upstream-to=upstream/foo foo

As of Git 1.7.0 (before 1.8.0):

git branch --set-upstream foo upstream/foo

Notes:

  • All of the above commands will cause local branch foo to track remote branch foo from remote upstream.
  • The old (1.7.x) syntax is deprecated in favor of the new (1.8+) syntax. The new syntax is intended to be more intuitive and easier to remember.
  • Defining an upstream branch will fail when run against newly-created remotes that have not already been fetched. In that case, run git fetch upstream beforehand.

See also: Why do I need to do `--set-upstream` all the time?

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

One solution is to reset_index (and get back to df) and use pivot_table.

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

Cannot add or update a child row: a foreign key constraint fails

Yet another weird case that gave me this error. I had erroneously referenced my foreign keys to the id primary key. This was caused by incorrect alter table commands. I found this out by querying the INFORMATION_SCHEMA table (See this stackoverflow answer)

The table was so confused it could not be fixed by any ALTER TABLE commands. I finally dropped the table and reconstructed it. This got rid of the integrityError.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

for sbt, use below versions

val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"

val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"

val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

How do I exit a WPF application programmatically?

If you want to exit from another thread that didn't create the application object, use: System.Windows.Application.Current.Dispatcher.InvokeShutdown()

How do I add a Maven dependency in Eclipse?

Open the pom.xml file.

under the project tag add <dependencies> as another tag, and google for the Maven dependencies. I used this to search.

So after getting the dependency create another tag dependency inside <dependencies> tag.

So ultimately it will look something like this.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>doc-examples</groupId>
  <artifactId>lambda-java-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lambda-java-example</name>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.0.0</version>
    </dependency>
  </dependencies>
</project>

Hope it helps.

Ignoring directories in Git repositories on Windows

You can create the ".gitignore" file with the contents:

*
!.gitignore

It works for me.

How to center a <p> element inside a <div> container?

?you should do these steps :

  1. the mother Element should be positioned(for EXP you can give it position:relative;)
  2. the child Element should have positioned "Absolute" and values should set like this: top:0;buttom:0;right:0;left:0; (to be middle vertically)
  3. for the child Element you should set "margin : auto" (to be middle vertically)
  4. the child and mother Element should have "height"and"width" value
  5. for mother Element => text-align:center (to be middle horizontally)

??simply here is the summery of those 5 steps:

.mother_Element {
    position : relative;
    height : 20%;
    width : 5%;
    text-align : center
    }
.child_Element {
    height : 1.2 em;
    width : 5%;
    margin : auto;
    position : absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    }

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Override intranet compatibility mode IE8

Change the headers in .htaccess

BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie

Found the solution to this problem here: https://github.com/h5bp/html5-boilerplate/issues/378

What is the difference between Sessions and Cookies in PHP?

Cookie

  • is a small amount of data saved in the browser (client-side)

  • can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

  • can be set directly client-side in Javascript: document.cookie = 'foo=bar';

  • if no expiration date is set, by default, it will expire when the browser is closed.
    Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

  • you can also set a precise expiration date other than "deleted when browser is closed".

  • the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

    enter image description here

  • can be read client-side with document.cookie

  • can be read server-side with $_COOKIE['foo']

  • Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

    from bottle import get, run, request, response
    @get('/')
    def index():
        if request.get_cookie("visited"):
            return "Welcome back! Nice to see you again"
        else:
            response.set_cookie("visited", "yes")
            return "Hello there! Nice to meet you"
    run(host='localhost', port=8080, debug=True, reloader=True)
    

Session

  • is some data relative to a browser session saved server-side

  • each server-side language may implement it in a different way

  • in PHP, when session_start(); is called:

    • a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
    • a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
    • the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

      enter image description here

      (it can also be be sent via the URL instead of cookie but not the default behaviour)

    • you can see the session ID on client-side with document.cookie:

      enter image description here

  • the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

  • can be set/read in PHP with $_SESSION

  • the client-side does not see the session data but only the ID: do this in index.php:

    <?php
    session_start();
    $_SESSION["abc"]="def";
    ?>
    

    The only thing that is seen on client-side is (as mentioned above) the session ID:

    enter image description here

  • because of this, session is useful to store data that you don't want to be seen or modified by the client

  • you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast has runtime type checking and only works with references and pointers, whereas static_cast does not offer runtime type checking. For complete information, see the MSDN article static_cast Operator.

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The CP1 means 'Code Page 1' - technically this translates to code page 1252

What's the difference between xsd:include and xsd:import?

Use xsd:include brings all declarations and definitions of an external schema document into the current schema.

Use xsd:import to bring in an XSD from a different namespace and used to build a new schema by extending existing schema documents..

Turn off warnings and errors on PHP and MySQL

If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors) in a .htaccess file in any directory by adding the following line:

php_flag display_errors off

additionally, you can add error logging to a file:

php_flag log_errors on

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

Adding a line break in MySQL INSERT INTO text

If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');

I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));

How do you add CSS with Javascript?

Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

And then execute it with the new CSS attributes as an object.

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.

How to create an empty file at the command line in Windows?

.>>file.txt
  • >> append STDOUT into a file
  • . is just a wrong command to pass the empty STDOUT to >>

However, you'll see STDERR's output in the CMD:

'.' is not recognized as an internal or external command, operable program or batch file.

You can suppress this error message (if you want) by redirecting STDERR to NUL.

.>>file.txt 2>nul

Put request with simple string as request body

I solved this by overriding the default Content-Type:

const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
    ...
});

Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.

How to disable compiler optimizations in gcc?

Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options.

What is the purpose of flush() in Java streams?

When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I encountered the same problem, probably when I uninstalled it and tried to install it again. This happens because of the database file containing login details is still stored in the pc, and the new password will not match the older one. So you can solve this by just uninstalling mysql, and then removing the left over folder from the C: drive (or wherever you must have installed).

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

Understanding the difference between Object.create() and new SomeFunction()

Let me try to explain (more on Blog) :

  1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.
  2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods What is happening?

    Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
    Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).

Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.

Preferred way in OO JavaScript :

Suppose we have two objects a and b.

var a = new Object();
var b = new Object();

Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.

Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).

Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype. Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:

var b = Object.create(a);

then,

a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)

So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.

Add Header and Footer for PDF using iTextsharp

Easy codes that work successfully:

protected void Page_Load(object sender, EventArgs e)
{
 .
 .       
 using (MemoryStream ms = new MemoryStream())
 {
  .
  .
  iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54);
  iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
  writer.PageEvent = new HeaderFooter();
  doc.Open();
  .
  .
  // make your document content..
  .
  .                   
  doc.Close();
  writer.Close();

  // output
  Response.ContentType = "application/pdf;";
  Response.AddHeader("Content-Disposition", "attachment; filename=clientfilename.pdf");
  byte[] pdf = ms.ToArray();
  Response.OutputStream.Write(pdf, 0, pdf.Length);
 }
 .
 .
 .
}
class HeaderFooter : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{

    // Make your table header using PdfPTable and name that tblHeader
    .
    . 
    tblHeader.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, page.Top, writer.DirectContent);
    .
    .
    // Make your table footer using PdfPTable and name that tblFooter
    .
    . 
    tblFooter.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
}
}

Disable Drag and Drop on HTML elements?

With jQuery it will be something like that:

$(document).ready(function() {
  $('#yourDiv').on('mousedown', function(e) {
      e.preventDefault();
  });
});

In my case I wanted to disable the user from drop text in the inputs so I used "drop" instead "mousedown".

$(document).ready(function() {
  $('input').on('drop', function(event) {
    event.preventDefault();
  });
});

Instead event.preventDefault() you can return false. Here's the difference.

And the code:

$(document).ready(function() {
  $('input').on('drop', function() {
    return false;
  });
});

How to redirect the output of print to a TXT file

Usinge the file argument in the print function, you can have different files per print:

print('Redirect output to file', file=open('/tmp/example.log', 'w'))

Loaded nib but the 'view' outlet was not set

I had face the same problem while accidentally deleted xib reference and added it again.I just fixed by making connection between Files owner and the view.Also make sure that your FilesOwner's custom class is your expected viewController.

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

How to Select a substring in Oracle SQL up to a specific character?

This can be done using REGEXP_SUBSTR easily.

Please use

REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) 

where STRING_EXAMPLE is your string.

Try:

SELECT 
REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1) 
from dual

It will solve your problem.

How to comment/uncomment in HTML code

/* (opener) */ (closer)

for example,

<html>
 /*<p>Commented P Tag </p>*/
<html>

How to use localization in C#

Great answer by F.Mörk. But if you want to update translation, or add new languages once the application is released, you're stuck, because you always have to recompile it to generate the resources.dll.

Here is a solution to manually compile a resource dll. It uses the resgen.exe and al.exe tools (installed with the sdk).

Say you have a Strings.fr.resx resource file, you can compile a resources dll with the following batch:

resgen.exe /compile Strings.fr.resx,WpfRibbonApplication1.Strings.fr.resources 
Al.exe /t:lib /embed:WpfRibbonApplication1.Strings.fr.resources /culture:"fr" /out:"WpfRibbonApplication1.resources.dll"
del WpfRibbonApplication1.Strings.fr.resources
pause

Be sure to keep the original namespace in the file names (here "WpfRibbonApplication1")

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

How to rename with prefix/suffix?

Bulk rename files bash script

#!/bin/bash
# USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER
# USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_
# VERSION: 2016.03.05.
# COPYRIGHT: HarkĂ¡ly Gergo | mangoRDI (https://wwww.mangordi.com/) 

# check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming
if [ -z "$2" ]
    then i=1;
else
    i=$2;
fi

# counts the files to set leading zeros before number | max 1000 files
count=$(ls -l * | wc -l)
if [ $count -lt 10 ]
    then zeros=1;
else
    if [ $count -lt 100 ]
        then zeros=2;
    else
        zeros=3
    fi
fi

# rename script
for file in *
do
    mv $file $1_$(printf %0"$zeros"d.%s ${i%.*} ${file##*.})
    let i="$i+1"
done

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Xcode - ld: library not found for -lPods

Delete all the corresponding files/folders of imported cocoapods source except podfile.

install cocoapod again.This should clear any redundant pull from the original source.

Allow only pdf, doc, docx format for file upload?

For only acept files with extension doc and docx in the explorer window try this

    <input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
    System.out.println(d);
    System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

Include files from parent or other directory

In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!

".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.

As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.

Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.

Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:

  • C:\myDocuments\PHP1
  • C:\myDocuments\PHP2

In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:

  • C:\myDocuments\PHP1\index.php
  • C:\myDocuments\PHP2\found.php

Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:

<?php include ('../php2/found.php')?>

The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.

Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:

  • C:\myDocuments\PHP1\PHP2

you would simply reference/code

<?php include('/PHP2/found.php') ?>

as PHP2 exist as a sub-directory, below or within PHP1 directory.

If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as

$newObject = new nameobject("origianlThingy");

Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.

To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do. your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.

In my drunken state I realize that I know too much to be sane, and not enough to be insane!"

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Update statement with inner join on Oracle

MERGE with WHERE clause:

MERGE into table1
USING table2
ON (table1.id = table2.id)
WHEN MATCHED THEN UPDATE SET table1.startdate = table2.start_date
WHERE table1.startdate > table2.start_date;

You need the WHERE clause because columns referenced in the ON clause cannot be updated.

HTML select dropdown list

This is how I do this with JQuery...

using the jquery-watermark plugin (http://code.google.com/p/jquery-watermark/)

$('#inputId').watermark('Please select a name');

works like a charm!!

There is some good documentation at that google code site.

Hope this helps!

Core dumped, but core file is not in the current directory?

Read /usr/src/linux/Documentation/sysctl/kernel.txt.

[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.

  • If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.

Instead of writing the core dump to disk, your system is configured to send it to the abrt program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...

In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt, where abrt stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash, and so on.

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

MySQL - Using COUNT(*) in the WHERE clause

i think you can not add count() with where. now see why ....

where is not same as having , having means you are working or dealing with group and same work of count , it is also dealing with the whole group ,

now how count it is working as whole group

create a table and enter some id's and then use:

select count(*) from table_name

you will find the total values means it is indicating some group ! so where does added with count() ;

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

Changing image sizes proportionally using CSS?

Put it as a background on your holder e.g.

<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">
&nbsp;
</div>

This will center your image inside a 120x120 div chopping off any excess of the image

Convert Java object to XML string

Here is a util class for marshaling and unmarshaling objects. In my case it was a nested class, so I made it static JAXBUtils.

import javax.xml.bind.JAXB;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtils
{
    /**
     * Unmarshal an XML string
     * @param xml     The XML string
     * @param type    The JAXB class type.
     * @return The unmarshalled object.
     */
    public <T> T unmarshal(String xml, Class<T> type)
    {
        StringReader reader = new StringReader(xml);
        return javax.xml.bind.JAXB.unmarshal(reader, type);
    }

    /**
     * Marshal an Object to XML.
     * @param object    The object to marshal.
     * @return The XML string representation of the object.
     */
    public String marshal(Object object)
    {
        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(object, stringWriter);
        return stringWriter.toString();
    }
}

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

Function names in C++: Capitalize or not?

Since C++11, you may want to use either snake_case or camelCase for function names.

This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin and end (case-sensitive) for that class.

Consequently, using e.g. PascalCase for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.

Query to select data between two dates with the format m/d/yyyy

Try this:

select * from xxx where dates between convert(datetime,'10/10/2012',103) and convert(dattime,'10/12/2012',103)

How to draw border on just one side of a linear layout?

I was able to achieve the effect with the following code

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:left="0dp" android:right="-5dp" android:top="-5dp" android:bottom="-5dp">
        <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#123456" />
        </shape>
    </item>
</layer-list>

You can adjust to your needs for border position by changing the direction of displacement

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Clear text input on click with AngularJS

An easier and shorter way is:

 <input type="text" class="form-control" data-ng-model="searchAll">
 <a class="clear" data-ng-click="searchAll = '' ">X</a>

This has always worked for me.

Javascript loop through object array?

Iterations

Method 1: forEach method

messages.forEach(function(message) {
   console.log(message);
}

Method 2: for..of method

for(let message of messages){
   console.log(message);
}

Note: This method might not work with objects, such as:

let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }

Method 2: for..in method

for(let key in messages){
       console.log(messages[key]);
 }

Add line break to ::after or ::before pseudo-element content

I had to have new lines in a tooltip. I had to add this CSS on my :after :

.tooltip:after {
  width: 500px;
  white-space: pre;
  word-wrap: break-word;
}

The word-wrap seems necessary.

In addition, the \A didn't work in the middle of the text to display, to force a new line.

 &#13;&#10; 

worked. I was then able to get such a tooltip :

enter image description here

how to check if string value is in the Enum list?

You should use Enum.TryParse to achive your goal

This is a example:

[Flags]
private enum TestEnum
{
    Value1 = 1,
    Value2 = 2
}

static void Main(string[] args)
{
    var enumName = "Value1";
    TestEnum enumValue;

    if (!TestEnum.TryParse(enumName, out enumValue))
    {
        throw new Exception("Wrong enum value");
    }

    // enumValue contains parsed value
}

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

Execute a batch file on a remote PC using a batch file on local PC

If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.

UPDATE:

Seems shutdown.bat here is for shutting down apache-tomcat.

So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client

As native solution could be wmic

Example:

wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"

In your example should be:

wmic /node:inidsoasrv01 process call create ^
    "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"

wmic /? and wmic /node /? for more

invalid_client in google oauth2

Check your Project name on Google APIs console. you choose another project you created. I was same error. my mistake was choosing diffirent project.

How is length implemented in Java Arrays?

Every array in java is considered as an object. The public final length is the data member which contains the number of components of the array (length may be positive or zero)

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.

Essentially both commands are alternative-syntax versions of standard commands.

PHP: merge two arrays while keeping keys instead of reindexing?

While this question is quite old I just want to add another possibility of doing a merge while keeping keys.

Besides adding key/values to existing arrays using the + sign you could do an array_replace.

$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');

$merged = array_replace($a, $b);

The result will be:

Array
(
  [foo] => bar
  [some] => string
  [42] => answer to the life and everything
  [1337] => leet
)

Same keys will be overwritten by the latter array.
There is also an array_replace_recursive, which do this for subarrays, too.

Live example on 3v4l.org

"Keep Me Logged In" - the best approach

Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.

Usually I do something like this:

  1. User logs in with 'keep me logged in'
  2. Create session
  3. Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id
  4. Store cookie in database
  5. User does stuff and leaves ----
  6. User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1

Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.

Also you could use sha1 instead of md5 (or pretty much any algorithm)

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

How to set default value for form field in Symfony2?

You can set a default value, e.g. for the form message, like this:

$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
    ->add('name', 'text')
    ->add('email', 'email')
    ->add('message', 'textarea')
    ->add('send', 'submit')
    ->getForm();

In case your form is mapped to an Entity, you can go like this (e.g. default username):

$user = new User();
$user->setUsername('John Doe');

$form = $this->createFormBuilder($user)
    ->add('username')
    ->getForm();

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

How do I get java logging output to appear on a single line?

Similar to Tervor, But I like to change the property on runtime.

Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.

    System.setProperty("java.util.logging.SimpleFormatter.format", 
            "%1$tF %1$tT %4$s %2$s %5$s%6$s%n");

string.split - by multiple character delimiter

Another option:

Replace the string delimiter with a single character, then split on that character.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

How to easily consume a web service from PHP

This article explains how you can use PHP SoapClient to call a api web service.

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

How do I remove a property from a JavaScript object?

The obvious way to remove a property from an object is to use the delete keyword. this can be done like this:

delete myObject['regex']

or this:

delete myObject.regex

If you are cocerned with mutability, you can create a new object by copying all the properties from the old, except the one you would like to remove

let myObject = {
   ircEvent: "PRIVMSG",
   method: "newURI",
   regex: "^http://.*"
};

const propertyToRemove = 'regex'
const newObject = Object.keys(myObject).reduce((object, key) => {
   if (key !== propertyToRemove ) {
      object[key] = car[key]
   }
return object }, {})

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

IIS Express Windows Authentication

This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx (even though there is no such file on your site).

Add the following two lines to the appSettingssection of your site's Web.config.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

jQuery.css() - marginLeft vs. margin-left?

jQuery is simply supporting the way CSS is written.

Also, it ensures that no matter how a browser returns a value, it will be understood

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

Setting max-height for table cell contents

I had the same problem with a table layout I was creating. I used Joseph Marikle's solution but made it work for FireFox as well, and added a table-row style for good measure. Pure CSS solution since using Javascript for this seems completely unnecessary and overkill.

html

<div class='wrapper'>
    <div class='table'>
        <div class='table-row'>
            <div class='table-cell'>
                content here
            </div>
            <div class='table-cell'>
                <div class='cell-wrap'>
                    lots of content here
                </div>
            </div>
            <div class='table-cell'>
                content here
            </div>
            <div class='table-cell'>
                content here
            </div>
        </div>
    </div>
</div>

css

.wrapper {height: 200px;}
.table {position: relative; overflow: hidden; display: table; width: 100%; height: 50%;}
.table-row {display: table-row; height: 100%;}
.table-cell {position: relative; overflow: hidden; display: table-cell;}
.cell-wrap {position: absolute; overflow: hidden; top: 0; left: 0; width: 100%; height: 100%;}

You need a wrapper around the table if you want the table to respect a percentage height, otherwise you can just set a pixel height on the table element.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

Operator overloading in Java

Just use Xtend along with your Java code. It supports Operator Overloading:

    package com.example;

@SuppressWarnings("all")
public class Test {
  protected int wrapped;

  public Test(final int value) {
    this.wrapped = value;
  }

  public int operator_plus(final Test e2) {
    return (this.wrapped + e2.wrapped);
  }
}

package com.example

class Test2 {

    new() {
        val t1 = new Test(3)
        val t2 = new Test(5)
        val t3 = t1 + t2
    }

}

On the official website, there is a list of the methods to implement for each operator !

cartesian product in pandas

With method chaining:

product = (
    df1.assign(key=1)
    .merge(df2.assign(key=1), on="key")
    .drop("key", axis=1)
)

Pentaho Data Integration SQL connection

To be concise and precise download the compatible jdbc (.jar) file compatible with your MySql version and put it in lib folder. For example for MySQL 8.0.2 download Connector/J 8.0.20

How to make a UILabel clickable?

SWIFT 4 Update

 @IBOutlet weak var tripDetails: UILabel!

 override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction))
    tripDetails.isUserInteractionEnabled = true
    tripDetails.addGestureRecognizer(tap)
}

@objc func tapFunction(sender:UITapGestureRecognizer) {

    print("tap working")
}

Should I URL-encode POST data?

@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)

Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .

Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.

$fields = array(
    'mediaupload'=>$file_field,
    'username'=>$_POST["username"],
    'password'=>$_POST["password"],
    'latitude'=>$_POST["latitude"],
    'longitude'=>$_POST["longitude"],
    'datetime'=>$_POST["datetime"],
    'category'=>$_POST["category"],
    'metacategory'=>$_POST["metacategory"],
    'caption'=>$_POST["description"]
);

$fields_string = http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.

$fields = array(
        'mediaupload'=>$file_field,
        'username'=>$_POST["username"],
        'password'=>$_POST["password"],
        'latitude'=>$_POST["latitude"],
        'longitude'=>$_POST["longitude"],
        'datetime'=>$_POST["datetime"],
        'category'=>$_POST["category"],
        'metacategory'=>$_POST["metacategory"],
        'caption'=>$_POST["description"]
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);

Both code snippets work, but using different HTTP headers and bodies.

Why are elementwise additions much faster in separate loops than in a combined loop?

It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.

The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.

The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.

How to show empty data message in Datatables

By default the grid view will take care, just pass empty data set.

Return Result from Select Query in stored procedure to a List

// GET: api/GetStudent

public Response Get() {
    return StoredProcedure.GetStudent();
}

public static Response GetStudent() {
    using (var db = new dal()) {
        var student = db.Database.SqlQuery<GetStudentVm>("GetStudent").ToList();
        return new Response {
            Sucess = true,
            Message = student.Count() + " Student found",
            Data = student
        };
    }
}

Is there a "null coalescing" operator in JavaScript?

After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

REST API Login Pattern

TL;DR Login for each request is not a required component to implement API security, authentication is.

It is hard to answer your question about login without talking about security in general. With some authentication schemes, there's no traditional login.

REST does not dictate any security rules, but the most common implementation in practice is OAuth with 3-way authentication (as you've mentioned in your question). There is no log-in per se, at least not with each API request. With 3-way auth, you just use tokens.

  1. User approves API client and grants permission to make requests in the form of a long-lived token
  2. Api client obtains a short-lived token by using the long-lived one.
  3. Api client sends the short-lived token with each request.

This scheme gives the user the option to revoke access at any time. Practially all publicly available RESTful APIs I've seen use OAuth to implement this.

I just don't think you should frame your problem (and question) in terms of login, but rather think about securing the API in general.

For further info on authentication of REST APIs in general, you can look at the following resources:

jQuery Validation plugin: disable validation for specified submit buttons

This question is old, but I found another way around it is to use $('#formId')[0].submit(), which gets the dom element instead of the jQuery object, thus bypassing any validation hooks. This button submits the parent form that contains the input.

<input type='button' value='SubmitWithoutValidation' onclick='$(this).closest('form')[0].submit()'/>

Also, make sure you don't have any input's named "submit", or it overrides the function named submit.

Possible to access MVC ViewBag object from Javascript file?

Use this code in your .cshtml file.

 @{
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var val = jss.Serialize(ViewBag.somevalue); 
    }

    <script>
        $(function () {
            var val = '@Html.Raw(val)';
            var obj = $.parseJSON(val);
            console.log(0bj);
    });
    </script>

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Best way to add Activity to an Android project in Eclipse?

It is now much easier to do this in Eclipse now. Just right click on the package that will contain your new activity. New -> Other -> (Under Android tab) Android Activity.

And that's all. Your new activity is automatically added to the manifest file as well.

Can we add div inside table above every <tr>?

"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page

For example:

<table>
    <tbody class="green">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
    <tbody class="blue">
        <tr>
            <td>Data</td>
        </tr>
    </tbody>
</table>

secondly, you can put "div" tag inside "td" tag.

<table>
    <tr>
        <td>
            <div></div>
        </td>
    </tr>
</table>

Further questions are always welcome.

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

Is it possible to set async:false to $.getJSON call

I don't think you can set that option there. You will have to use jQuery.ajax() with the appropriate parameters (basically getJSON just wraps that call into an easier API, as well).

Extract Month and Year From Date in R

The zoo package has the function of as.yearmon can help to convert.

require(zoo)

df$ym<-as.yearmon(df$date, "%Y %m")

View RDD contents in Python Spark?

Try this:

data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()

Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

git: diff between file in local repo and origin

For that I wrote a bash script:

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | awk '{if ($1 == "modified:") print $2;}'`
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool  FETCH_HEAD $file ;
done

In the above script, I fetch the remote main branch (not necessary its master branch ANY branch) to FETCH_HEAD, then make a list of my modified file only and compare modified files to git difftool.

There are many difftool supported by git, I configured Meld Diff Viewer for good GUI comparison.
From the above script, I have prior knowledge what changes done by other teams in same file, before I follow git stages untrack-->staged-->commit which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on the main branch.

Extracting Ajax return data in jQuery

You can use json like the following example.

PHP code:

echo json_encode($array);

$array is array data, and the jQuery code is:

$.get("period/education/ajaxschoollist.php?schoolid="+schoolid, function(responseTxt, statusTxt, xhr){
    var a = JSON.parse(responseTxt);
    $("#hideschoolid").val(a.schoolid);
    $("#section_id").val(a.section_id);
    $("#schoolname").val(a.schoolname);
    $("#country_id").val(a.country_id);
    $("#state_id").val(a.state_id);
}

Git merge reports "Already up-to-date" though there is a difference

What works for me, let's say you have branch1 and you wanna merge it into branch2.

You open git command line go to root folder of branch2 and type:

git checkout branch1
git pull branch1
git checkout branch2
git merge branch1
git push

If you have comflicts you don't need to do git push, but first solve the conflits and then push.

Where can I find "make" program for Mac OS X Lion?

After upgrading to Mountain Lion using the NDK, I had the following error:

Cannot find 'make' program. Please install Cygwin make package or define the GNUMAKE variable to point to it

Error was fixed by downloading and using the latest NDK

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

MySQL select query with multiple conditions

Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).

we have following basic commands for MySQL -

select * from hello;
select name, city from hello;
etc 

select name from hello where id = 8;
select id from hello where name = 'GAURAV';

now lets see multiple where condition -

select name from hello where id = 3 or id = 4 or id = 8 or id = 22;

select name from hello where id =3 and count = 3 city = 'Delhi';

This is how we can use multiple where commands in MySQL.

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

String.equals versus ==

The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.

Dynamically add data to a javascript map

Javascript now has a specific built in object called Map, you can call as follows :

   var myMap = new Map()

You can update it with .set :

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Generate a random date between two other dates

Pandas + numpy solution

import pandas as pd
import numpy as np

def RandomTimestamp(start, end):
    dts = (end - start).total_seconds()
    return start + pd.Timedelta(np.random.uniform(0, dts), 's')

dts is the difference between timestamps in seconds (float). It is then used to create a pandas timedelta between 0 and dts, that is added to the start timestamp.

Implementing autocomplete

I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.

How is an HTTP POST request made in node.js?

I use Restler and Needle for production purposes. They are both much more powerful than native httprequest. It is possible to request with basic authentication, special header entry or even upload/download files.

As for post/get operation, they also are much simpler to use than raw ajax calls using httprequest.

needle.post('https://my.app.com/endpoint', {foo:'bar'}, 
    function(err, resp, body){
        console.log(body);
});

What are FTL files

An ftl file could just have a series of html tags just as a JSP page or it can have freemarker template coding for representing the objects passed on from a controller java file.
But, its actual ability is to combine the contents of a java class and view/client side stuff(html/ JQuery/ javascript etc). It is quite similar to velocity. You could map a method or object of a class to a freemarker (.ftl) page and use it as if it is a variable or a functionality created in the very page.

Apply pandas function to column to create multiple new columns?

def extract_text_features(feature):
    ...
    ...
    return pd.Series((feature1, feature2)) 

df[['NewFeature1', 'NewFeature1']] = df[['feature']].apply(extract_text_features, axis=1)

Here the a dataframe with a single feature is being converted to two new features. Give this a try too.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

Am I missing something? You can just convert offer_date in the comparison:

SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
      offer_rate > 0 

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

How to efficiently count the number of keys/properties of an object in JavaScript?

I'm not aware of any way to do this, however to keep the iterations to a minimum, you could try checking for the existance of __count__ and if it doesn't exist (ie not Firefox) then you could iterate over the object and define it for later use eg:

if (myobj.__count__ === undefined) {
  myobj.__count__ = ...
}

This way any browser supporting __count__ would use that, and iterations would only be carried out for those which don't. If the count changes and you can't do this, you could always make it a function:

if (myobj.__count__ === undefined) {
  myobj.__count__ = function() { return ... }
  myobj.__count__.toString = function() { return this(); }
}

This way anytime you reference myobj.__count__ the function will fire and recalculate.

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I did everything provided in the previous answers to this question, but still had the issue. I did have the update installed, but I ran the installer again, reapplying the update while SQL 2012 Installer was open on the screen where I could run the check again. After it finished, I ran the check again and it passed.

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

Posting array from form

What you are doing is not necessarily bad practice but it does however require an extraordinary amount of typing. I would accomplish what you are trying to do like this.

foreach($_POST as $var => $val){
    $$var = $val;
}

This will take all the POST variables and put them in their own individual variables. So if you have a input field named email and the luser puts in [email protected] you will have a var named $email with a value of "[email protected]".

Laravel - Model Class not found

Make sure to be careful when editing your model file. For example, in your post model:

<?php 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';    
}

You need to pay close attention to the class Post extend Model line. The class Post defined here will be your namespace for your controller.

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

Find non-ASCII characters in varchar columns using SQL Server

I've been running this bit of code with success

declare @UnicodeData table (
     data nvarchar(500)
)
insert into 
    @UnicodeData
values 
    (N'Horse?')
    ,(N'Dog')
    ,(N'Cat')

select
    data
from
    @UnicodeData 
where
    data collate LATIN1_GENERAL_BIN != cast(data as varchar(max))

Which works well for known columns.

For extra credit, I wrote this quick script to search all nvarchar columns in a given table for Unicode characters.

declare 
    @sql    varchar(max)    = ''
    ,@table sysname         = 'mytable' -- enter your table here

;with ColumnData as (
    select
        RowId               = row_number() over (order by c.COLUMN_NAME)
        ,c.COLUMN_NAME
        ,ColumnName         = '[' + c.COLUMN_NAME + ']'
        ,TableName          = '[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']' 
    from
        INFORMATION_SCHEMA.COLUMNS c
    where
        c.DATA_TYPE         = 'nvarchar'
        and c.TABLE_NAME    = @table
)
select
    @sql = @sql + 'select FieldName = ''' + c.ColumnName + ''',         InvalidCharacter = [' + c.COLUMN_NAME + ']  from ' + c.TableName + ' where ' + c.ColumnName + ' collate LATIN1_GENERAL_BIN != cast(' + c.ColumnName + ' as varchar(max)) '  +  case when c.RowId <> (select max(RowId) from ColumnData) then  ' union all ' else '' end + char(13)
from
    ColumnData c

-- check
-- print @sql
exec (@sql)

I'm not a fan of dynamic SQL but it does have its uses for exploratory queries like this.

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

Angular2 QuickStart npm start is not working correctly

If you use proxy it may cause this error:

  1. npm config set proxy http://username:pass@proxy:port

  2. npm config set https-proxy http://username:pass@proxy:port

  3. create a file named .typingsrc in your application folder that includes:

    • proxy = (value on step 1)
    • https-proxy = (value on step 1)
  4. run npm cache clean

  5. run npm install
  6. run npm typings install
  7. run npm start

it will work then

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

How do check if a PHP session is empty?

I would use isset and empty:

session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!';
}

array_key_exists is a nice alternative to using isset to check for keys:

session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!';
}

Make sure you're calling session_start before reading from or writing to the session array.

remove item from stored array in angular 2

Use splice() to remove item from the array its refresh the array index to be consequence.

delete will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4

this.data.splice(this.data.indexOf(msg), 1)

Python find min max and average of a list (array)

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

Build Eclipse Java Project from Command Line

To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:

      <javac
          srcdir="${src}"
          destdir="${build.dir}/classes"> 
        <compilerarg 
           compiler="org.eclipse.jdt.core.JDTCompilerAdapter" 
           line="-warn:+unused -Xemacs"/>
        <classpath refid="compile.classpath" />
      </javac>

The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.

You can find a full ant script example here which would be invoked in a command line with:

java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose

BUT all that involves ant, which is not what Keith is after.

For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"

The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.

Running the batch compiler From the command line would give

java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java

or:

java -jar ecj.jar -classpath rt.jar A.java

All java compilation options are detailed in that section as well.

The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.

So, then short answer is: "yes, Eclipse kind of does." ;)

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

If you don't have MySQL installed on your host, you have to execute it in the container (https://docs.docker.com/engine/reference/commandline/exec/#/examples gives explanation about docker run vs docker exec).

Considering your container is running, you might use docker exec yourcontainername mysql -u root -p to access to the client.

Also, if you are using Docker Compose, and you've declared a mysql db service named database, you can use : docker-compose exec database mysql -u root -p

How do I remove the first characters of a specific column in a table?

You Can also do this in SQL..

substring(StudentCode,4,len(StudentCode))

syntax

substring (ColumnName,<Number of starting Character which u want to remove>,<length of given string>)

Maven: How do I activate a profile from command line?

I have encountered this problem and i solved mentioned problem by adding -DprofileIdEnabled=true parameter while running mvn cli command.

Please run your mvn cli command as : mvn clean install -Pdev1 -DprofileIdEnabled=true.

In addition to this solution, you don't need to remove activeByDefault settings in your POM mentioned as previouses answer.

I hope this answer solve your problem.

C# Wait until condition is true

After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!

public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
    var tcs = new TaskCompletionSource<int>();
    using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
    {
        cancellationTokenSource.Token.Register(() =>
        {
            tcs.SetException(
                new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
            tcs.TrySetCanceled();
        });

        while(!cancellationTokenSource.IsCancellationRequested)
        {
            try
            {
                if (!predicate(elem))
                {
                    continue;
                }
            }
            catch(Exception e)
            {
                tcs.TrySetException(e);
            }

            tcs.SetResult(0);
            break;
        }

        return tcs.Task;
    }
}

Override browser form-filling and input highlighting with HTML/CSS

The form element has an autocomplete attribute that you can set to off. As of the CSS the !important directive after a property keeps it from being overriden:

background-color: white !important;

Only IE6 doesn't understand it.

If I misunderstood you, there's also the outline property that you could find useful.

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

Can gcc output C code after preprocessing?

Run:

gcc -E <file>.c

or

g++ -E <file>.cpp

Java: Replace all ' in a string with \'

You can use apache's commons-text library (instead of commons-lang):

Example code:

org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);

Dependency:

compile 'org.apache.commons:commons-text:1.8'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.8</version>
</dependency>

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

Key hash for Android-Facebook app

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    Button btn;
    EditText et;
    PackageInfo info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button)findViewById(R.id.button1);
        et=(EditText)findViewById(R.id.editText1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                try {
                    info = getPackageManager().getPackageInfo("com.example.id", PackageManager.GET_SIGNATURES);
                    for (Signature signature : info.signatures) {
                        MessageDigest md;
                        md = MessageDigest.getInstance("SHA");
                        md.update(signature.toByteArray());
                        String something = new String(Base64.encode(md.digest(), 0));
                        //String something = new String(Base64.encodeBytes(md.digest()));
                        et.setText("" + something);
                        Log.e("hash key", something);
                    }
                } catch (NameNotFoundException e1) {
                    Log.e("name not found", e1.toString());
                } catch (NoSuchAlgorithmException e) {
                    Log.e("no such an algorithm", e.toString());
                } catch (Exception e) {
                    Log.e("exception", e.toString());
                }
            }
        });
    }



}

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).