Programs & Examples On #Physx

PhysX is a 3rd-party physics engine owned by NVIDIA and most commonly used in the video game industry.

No Spring WebApplicationInitializer types detected on classpath

xml was not in the WEB-INF folder, thats why i was getting this error, make sure that web.xml and xxx-servlet.xml is inside WEB_INF folder and not in the webapp folder .

Program "make" not found in PATH

In MinGW, I had to install the following things:

Basic Setup -> mingw32-base  
Basic Setup -> mingw32-gcc-g++  
Basic Setup -> msys-base 

And in Eclipse, go to

Windows -> Preferences -> C/C++ -> Build -> Environment

And set the following environment variables (with "Append variables to native environment" option set):

MINGW_HOME   C:\MinGW
PATH   C:\MinGW\bin;C:\MinGW\msys\1.0\bin

Click "Apply" and then "OK".

This worked for me, as far as I can tell.

Swift presentViewController

I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue

DispatchQueue.main.async {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)
}

alternative to "!is.null()" in R

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
{
  do whatever
}

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)

Running python script inside ipython

for Python 3.6.5

import os
os.getcwd()
runfile('testing.py')

How to do a JUnit assert on a message in a logger

Wow. I'm unsure why this was so hard. I found I was unable to use any of the code samples above because I was using log4j2 over slf4j. This is my solution:

public class SpecialLogServiceTest {

  @Mock
  private Appender appender;

  @Captor
  private ArgumentCaptor<LogEvent> captor;

  @InjectMocks
  private SpecialLogService specialLogService;

  private LoggerConfig loggerConfig;

  @Before
  public void setUp() {
    // prepare the appender so Log4j likes it
    when(appender.getName()).thenReturn("MockAppender");
    when(appender.isStarted()).thenReturn(true);
    when(appender.isStopped()).thenReturn(false);

    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    loggerConfig = config.getLoggerConfig("org.example.SpecialLogService");
    loggerConfig.addAppender(appender, AuditLogCRUDService.LEVEL_AUDIT, null);
  }

  @After
  public void tearDown() {
    loggerConfig.removeAppender("MockAppender");
  }

  @Test
  public void writeLog_shouldCreateCorrectLogMessage() throws Exception {
    SpecialLog specialLog = new SpecialLogBuilder().build();
    String expectedLog = "this is my log message";

    specialLogService.writeLog(specialLog);

    verify(appender).append(captor.capture());
    assertThat(captor.getAllValues().size(), is(1));
    assertThat(captor.getAllValues().get(0).getMessage().toString(), is(expectedLog));
  }
}

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

onChange and onSelect in DropDownList

Simply & Easy : JavaScript code :

function JoinedOrNot(){
    var cat = document.getElementById("mySelect");
    if(cat.value == "yes"){
        document.getElementById("mySelect1").disabled = false;
    }else{
        document.getElementById("mySelect1").disabled = true;
    }
}

just add in this line [onChange="JoinedOrNot()"] : <select id="mySelect" onchange="JoinedOrNot()">

it's work fine ;)

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

ImportError: No module named google.protobuf

if protobuf is installed then import it like this

pip install protobuf

import google.protobuf

How to remove the border highlight on an input text element

The only solutiion that worked with me

The border is actually a shadow. So to hide it I had to do this:

input[type="text"]:focus{
     box-shadow: 0 0 0 rgb(255, 255, 255);
}

 input[type="checkbox"]:focus{
      box-shadow: 0 0 0 rgb(255, 255, 255);
 }

JavaScript CSS how to add and remove multiple CSS classes to an element

  addClass(element, className1, className2){
    element.classList.add(className1, className2);
  }
  removeClass(element, className1, className2) {
    element.classList.remove(className1, className2);
  }

removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');

Sharing a URL with a query string on Twitter

This will Work For You

http://twitter.com/share?text=text goes here&url=http://url goes here&hashtags=hashtag1,hashtag2,hashtag3

Here is a Live Example About it


http://twitter.com/share?text=Im Sharing on Twitter&url=https://stackoverflow.com/users/2943186/youssef-subehi&hashtags=stackoverflow,example,youssefusf

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

Http Post With Body

 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

then add elements for each pair

 nameValuePairs.add(new BasicNameValuePair("yourReqVar", Value);
 nameValuePairs.add( ..... );

Then use the HttpPost:

HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

and use the HttpClient and Response to get the response from the server

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

If you want to have an affix on your header you can use this tricks, add position: relative on your th and change the position in eventListener('scroll')

I have created an example: https://codesandbox.io/s/rl1jjx0o

I use vue.js but you can use this, without vue.js

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

Flatten list of lists

Given

d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]

and your specific question: How can I remove the brackets?

Using list comprehension :

new_d = [i[0] for i in d]

will give you this

[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

then you can access individual items with the appropriate index, e.g., new_d[0] will give you 180.0 etc which you can then use for math.

If you are going to have a collection of data, you will have some sort of bracket or parenthesis.

Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.

Change the "No file chosen":

This will help you to change the name for "no file choose to Select profile picture"

<input type='file'id="files" class="hidden"/>  
<label for="files">Select profile picture</label>

How to add `style=display:"block"` to an element using jQuery?

If you need to add multiple then you can do it like this:

$('#element').css({
    'margin-left': '5px',
    'margin-bottom': '-4px',
    //... and so on
});

As a good practice I would also put the property name between quotes to allow the dash since most styles have a dash in them. If it was 'display', then quotes are optional but if you have a dash, it will not work without the quotes. Anyways, to make it simple: always enclose them in quotes.

How do you use the ? : (conditional) operator in JavaScript?

It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator".

If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.

To answer your question, conditional operators replace simple if statements. An example is best:

var insurancePremium = age > 21 ? 100 : 200;

Instead of:

var insurancePremium;

if (age > 21) {
    insurancePremium = 100;
} else {
    insurancePremium = 200;
}

Switch firefox to use a different DNS than what is in the windows.host file

I use this to override system's DNS with localserver
in about:config
change this value:

  • network.dns.forceResolve
  • network.dns.ipv4OnlyDomains
  • network.dns.localDomains
  • with IP address of local DNS server (for exsample 192.168.1.88)
    Sorry for my english

    Spacing between elements

    If you want vertical spacing between elements, use a margin.

    Don't add extra elements if you don't need to.

    UIImageView - How to get the file name of the image assigned?

    You can use objective c Runtime feature for associating imagename with the UImageView.

    First import #import <objc/runtime.h> in your class

    then implement your code as below :

    NSString *filename = @"exampleImage";
    UIImage *image = [UIImage imagedName:filename];
    objc_setAssociatedObject(image, "imageFilename", filename, OBJC_ASSOCIATION_COPY);
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    //You can then get the image later:
    NSString *filename = objc_getAssociatedObject(imageView, "imageFilename");
    

    Hope it helps you.

    SQL Server - copy stored procedures from one db to another

    You can use SSMS's "Generate Scripts..." function to script out whatever you need to transfer. Right-click on the source database in SSMS, choose "Generate Scripts...", and follow the wizard along. Then run your resultant script that will now contain the stored procedure create statements.

    sql - insert into multiple tables in one query

    Multiple SQL statements must be executed with the mysqli_multi_query() function.

    Example (MySQLi Object-oriented):

        <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    
    $sql = "INSERT INTO names (firstname, lastname)
    VALUES ('inpute value here', 'inpute value here');";
    $sql .= "INSERT INTO phones (landphone, mobile)
    VALUES ('inpute value here', 'inpute value here');";
    
    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
    ?>
    

    IntelliJ shortcut to show a popup of methods in a class that can be searched

    command+fn+F12 is correct. Lacking of button fn the F12 is used adjust the volume.

    How to Scroll Down - JQuery

    $('.btnMedio').click(function(event) {
        // Preventing default action of the event
        event.preventDefault();
        // Getting the height of the document
        var n = $(document).height();
        $('html, body').animate({ scrollTop: n }, 50);
    //                                       |    |
    //                                       |    --- duration (milliseconds) 
    //                                       ---- distance from the top
    });
    

    Makefile, header dependencies

    I prefer this solution, over the accepted answer by Michael Williamson, it catches changes to sources+inline files, then sources+headers, and finally sources only. Advantage here is that the whole library is not recompiled if only a a few changes are made. Not a huge consideration for a project with a couple of files, bur if you have 10 or a 100 sources, you will notice the difference.

    COMMAND= gcc -Wall -Iinclude ...
    
    %.o: %.cpp %.inl
        $(COMMAND)
    
    %.o: %.cpp %.hpp
        $(COMMAND)
    
    %.o: %.cpp
        $(COMMAND)
    

    Should I use Java's String.format() if performance is important?

    The answer to this depends very much on how your specific Java compiler optimizes the bytecode it generates. Strings are immutable and, theoretically, each "+" operation can create a new one. But, your compiler almost certainly optimizes away interim steps in building long strings. It's entirely possible that both lines of code above generate the exact same bytecode.

    The only real way to know is to test the code iteratively in your current environment. Write a QD app that concatenates strings both ways iteratively and see how they time out against each other.

    How do I convert datetime to ISO 8601 in PHP

    You can try this way:

    $datetime = new DateTime('2010-12-30 23:21:46');
    
    echo $datetime->format(DATE_ATOM);
    

    Converting JSON to XML in Java

    If you want to replace any node value you can do like this

    JSONObject json = new JSONObject(str);
    String xml = XML.toString(json);
    xml.replace("old value", "new value");
    

    Google Chrome forcing download of "f.txt" file

    Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.

    The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/

    JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.

    NSString with \n or line break

    If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0

    myView.numberOfLines=0;
    

    Is there any ASCII character for <br>?

    You may be looking for the special HTML character, &#10; .

    You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt label.

    Can Windows' built-in ZIP compression be scripted?

    There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.

    The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.

    Unzipping is easier - just treat it as a directory.

    In case the web pages are lost again, here are a few of the relevant code snippets:

    ZIP

    Sub NewZip(sPath)
    'Create empty Zip File
    'Changed by keepITcool Dec-12-2005
        If Len(Dir(sPath)) > 0 Then Kill sPath
        Open sPath For Output As #1
        Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
        Close #1
    End Sub
    
    
    Function bIsBookOpen(ByRef szBookName As String) As Boolean
    ' Rob Bovey
        On Error Resume Next
        bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
    End Function
    
    
    Function Split97(sStr As Variant, sdelim As String) As Variant
    'Tom Ogilvy
        Split97 = Evaluate("{""" & _
                           Application.Substitute(sStr, sdelim, """,""") & """}")
    End Function
    
    Sub Zip_File_Or_Files()
        Dim strDate As String, DefPath As String, sFName As String
        Dim oApp As Object, iCtr As Long, I As Integer
        Dim FName, vArr, FileNameZip
    
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If
    
        strDate = Format(Now, " dd-mmm-yy h-mm-ss")
        FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
    
        'Browse to the file(s), use the Ctrl key to select more files
        FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                        MultiSelect:=True, Title:="Select the files you want to zip")
        If IsArray(FName) = False Then
            'do nothing
        Else
            'Create empty Zip File
            NewZip (FileNameZip)
            Set oApp = CreateObject("Shell.Application")
            I = 0
            For iCtr = LBound(FName) To UBound(FName)
                vArr = Split97(FName(iCtr), "\")
                sFName = vArr(UBound(vArr))
                If bIsBookOpen(sFName) Then
                    MsgBox "You can't zip a file that is open!" & vbLf & _
                           "Please close it and try again: " & FName(iCtr)
                Else
                    'Copy the file to the compressed folder
                    I = I + 1
                    oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
    
                    'Keep script waiting until Compressing is done
                    On Error Resume Next
                    Do Until oApp.Namespace(FileNameZip).items.Count = I
                        Application.Wait (Now + TimeValue("0:00:01"))
                    Loop
                    On Error GoTo 0
                End If
            Next iCtr
    
            MsgBox "You find the zipfile here: " & FileNameZip
        End If
    End Sub
    

    UNZIP

    Sub Unzip1()
        Dim FSO As Object
        Dim oApp As Object
        Dim Fname As Variant
        Dim FileNameFolder As Variant
        Dim DefPath As String
        Dim strDate As String
    
        Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                            MultiSelect:=False)
        If Fname = False Then
            'Do nothing
        Else
            'Root folder for the new folder.
            'You can also use DefPath = "C:\Users\Ron\test\"
            DefPath = Application.DefaultFilePath
            If Right(DefPath, 1) <> "\" Then
                DefPath = DefPath & "\"
            End If
    
            'Create the folder name
            strDate = Format(Now, " dd-mm-yy h-mm-ss")
            FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"
    
            'Make the normal folder in DefPath
            MkDir FileNameFolder
    
            'Extract the files into the newly created folder
            Set oApp = CreateObject("Shell.Application")
    
            oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
    
            'If you want to extract only one file you can use this:
            'oApp.Namespace(FileNameFolder).CopyHere _
             'oApp.Namespace(Fname).items.Item("test.txt")
    
            MsgBox "You find the files here: " & FileNameFolder
    
            On Error Resume Next
            Set FSO = CreateObject("scripting.filesystemobject")
            FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
        End If
    End Sub
    

    Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

    I try to perform a TLS1.2 connection. I tried eveything mention above but didn't work. Do you have any additional idea?

    String WebserviceApiURL = "https://soapServiceURL";
    
    Uri uri = new Uri(WebserviceApiURL);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.ContentType = "application/json";
    request.Headers.Add("Token", "xxxxxx");
    
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    System.Net.ServicePointManager.Expect100Continue = false;
    
    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;
    request.ServicePoint.ConnectionLimit = 1;
    
    WebResponse response = request.GetResponse();
    

    add an element to int [] array in java

    Like others suggested you are better off using collection. If you however for some reason must stick to array then Apache Commons ArrayUtils may help:

    int[] series = {4,2};
    series = ArrayUtils.add(series, 3); // series is now {4,2,3}
    series = ArrayUtils.add(series, 4); // series is now {4,2,3,4};
    

    Note that the add method creates a new array, copies the given array and appends the new element at the end, which may have impact on performance.

    Why Git is not allowing me to commit even after configuration?

    Do you have a local user.name or user.email that's overriding the global one?

    git config --list --global | grep user
      user.name=YOUR NAME
      user.email=YOUR@EMAIL
    git config --list --local | grep user
      user.name=YOUR NAME
      user.email=
    

    If so, remove them

    git config --unset --local user.name
    git config --unset --local user.email
    

    The local settings are per-clone, so you'll have to unset the local user.name and user.email for each of the repos on your machine.

    Multiline strings in VB.NET

    Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.

    Dim str As String
    str = "First line" & vbCrLf & "Second line"
    MsgBox(str)
    str = "First line" & vbNewLine & "Second line"
    MsgBox(str)
    

    It will show two identical MessageBoxes with 2 lines.

    Run R script from command line

    One more way of running an R script from the command line would be:

    R < scriptName.R --no-save  
    

    or with --save.

    See also What's the best way to use R scripts on the command line (terminal)?.

    Parameter "stratify" from method "train_test_split" (scikit Learn)

    For my future self who comes here via Google:

    train_test_split is now in model_selection, hence:

    from sklearn.model_selection import train_test_split
    
    # given:
    # features: xs
    # ground truth: ys
    
    x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                        test_size=0.33,
                                                        random_state=0,
                                                        stratify=ys)
    

    is the way to use it. Setting the random_state is desirable for reproducibility.

    If isset $_POST

    Most form inputs are always set, even if not filled up, so you must check for the emptiness too.

    Since !empty() is already checks for both, you can use this:

    if (!empty($_POST["mail"])) {
        echo "Yes, mail is set";    
    } else {  
        echo "No, mail is not set";
    }
    

    Get all parameters from JSP page

    The fastest way should be:

    <%@ page import="java.util.Map" %>
    Map<String, String[]> parameters = request.getParameterMap();
    for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
        if (entry.getKey().startsWith("question")) {
            String[] values = entry.getValue();
            // etc.
    

    Note that you can't do:

    for (Map.Entry<String, String[]> entry : 
         request.getParameterMap().entrySet()) { // WRONG!
    

    for reasons explained here.

    How to Correctly Use Lists in R?

    why do these two different operators, [ ], and [[ ]], return the same result?

    x = list(1, 2, 3, 4)
    
    1. [ ] provides sub setting operation. In general sub set of any object will have the same type as the original object. Therefore, x[1] provides a list. Similarly x[1:2] is a subset of original list, therefore it is a list. Ex.

      x[1:2]
      
      [[1]] [1] 1
      
      [[2]] [1] 2
      
    2. [[ ]] is for extracting an element from the list. x[[1]] is valid and extract the first element from the list. x[[1:2]] is not valid as [[ ]] does not provide sub setting like [ ].

       x[[2]] [1] 2 
      
      > x[[2:3]] Error in x[[2:3]] : subscript out of bounds
      

    This Row already belongs to another table error when trying to add rows?

    foreach (DataRow dr in dtSpecificOrders.rows)
    {
       dtSpecificOrders.Rows.Add(dr.ItemArray); 
    }
    

    asp:TextBox ReadOnly=true or Enabled=false?

    Readonly will not "grayout" the textbox and will still submit the value on a postback.

    Print empty line?

    Python 2.x: Prints a newline

    print      
    

    Python 3.x: You must call the function

    print() 
    

    Source: https://docs.python.org/3.0/whatsnew/3.0.html

    In Excel, sum all values in one column in each row where another column is a specific value

    You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

    =IF(B1="No", A1, 0)
    

    and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

    How can I print the contents of an array horizontally?

    namespace ReverseString
    {
        class Program
        {
            static void Main(string[] args)
            {
                string stat = "This is an example of code" +
                              "This code has written in C#\n\n";
    
                Console.Write(stat);
    
                char[] myArrayofChar = stat.ToCharArray();
    
                Array.Reverse(myArrayofChar);
    
                foreach (char myNewChar in myArrayofChar)
                    Console.Write(myNewChar); // You just need to write the function
                                              // Write instead of WriteLine
                Console.ReadKey();
            }
        }
    }
    

    This is the output:

    #C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT
    

    Return multiple values to a method caller

    In C#7 There is a new Tuple syntax:

    static (string foo, int bar) GetTuple()
    {
        return ("hello", 5);
    }
    

    You can return this as a record:

    var result = GetTuple();
    var foo = result.foo
    // foo == "hello"
    

    You can also use the new deconstructor syntax:

    (string foo) = GetTuple();
    // foo == "hello"
    

    Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple<string, int> (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.

    So, for serialisation declare a record class and return that instead.

    Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:

    if(int.TryParse("123", out int result)) {
        // Do something with result
    }
    

    However, mostly you'll use this in .NET's own libraries, rather than in you own functions.

    Find the version of an installed npm package

    npm info YOUR_PACKAGE version
    

    e.g.

    npm info grunt version
    0.4.5
    

    How do I auto-submit an upload form when a file is selected?

    HTML

    <form id="xtarget" action="upload.php">
    <input type="file" id="xfilename">
    </form>
    

    JAVASCRIPT PURE

    <script type="text/javascript">
    window.onload = function() {
        document.getElementById("xfilename").onchange = function() {
            document.getElementById("xtarget").submit();
        }
    };
    </script>
    

    Changing Tint / Background color of UITabBar

    Swift 3.0 answer: (from Vaibhav Gaikwad)

    For changing color of unselect icons of tabbar:

    if #available(iOS 10.0, *) {
            UITabBar.appearance().unselectedItemTintColor = UIColor.white
        } else {
            // Fallback on earlier versions
            for item in self.tabBar.items! {
                item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
            }
    }
    

    For changing text color only:

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal)
    
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red, for: .selected)
    

    SQL Error with Order By in Subquery

    This is the error you get (emphasis mine):

    The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

    So, how can you avoid the error? By specifying TOP, would be one possibility, I guess.

    SELECT (
      SELECT TOP 100 PERCENT
      COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
      GROUP BY refKlinik_id
      ORDER BY refKlinik_id
    ) as dorduncuay
    

    TypeError: 'float' object is not callable

    You have forgotten a * between -3.7 and (prof[x]).

    Thus:

    for x in range(len(prof)):
        PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))
    

    Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

    Sequel Pro Alternative for Windows

    Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).

    From the website:

    Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.

    onchange event for html.dropdownlist

    If you have a list view you can do this:

    1. Define a select list:

      @{
         var Acciones = new SelectList(new[]
         {
        new SelectListItem { Text = "Modificar", Value = 
         Url.Action("Edit", "Countries")},
        new SelectListItem { Text = "Detallar", Value = 
        Url.Action("Details", "Countries") },
        new SelectListItem { Text = "Eliminar", Value = 
        Url.Action("Delete", "Countries") },
       }, "Value", "Text");
      }
      
    2. Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):

      @Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id = 
      item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
      
    3. onchange function can be something as:

      @section Scripts {
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>
      <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
      
      <script type="text/javascript">
      
      function RealizarAccion(accion, country)
      {
      
          var url = accion + '/' + country;
          if (url != null && url != '') {
              window.location.href = url ;
          }
      }
      </script>
      
      @Scripts.Render("~/bundles/jqueryval")
      }
      

    Copy folder recursively in Node.js

    The one with symbolic link support:

    import path from "path"
    import {
      existsSync, mkdirSync, readdirSync, lstatSync,
      copyFileSync, symlinkSync, readlinkSync
    } from "fs"
    
    
    export function copyFolderSync(src, dest) {
      if (!existsSync(dest)) mkdirSync(dest)
    
      readdirSync(src).forEach(dirent => {
        const [srcPath, destPath] = [src, dest].map(dirPath => path.join(dirPath, dirent))
        const stat = lstatSync(srcPath)
    
        switch (true) {
          case stat.isFile():
            copyFileSync(srcPath, destPath); break
          case stat.isDirectory():
            copyFolderSync(srcPath, destPath); break
          case stat.isSymbolicLink():
            symlinkSync(readlinkSync(srcPath), destPath); break
        }
      })
    }
    
    

    How do I install SciPy on 64 bit Windows?

    It is terrible to install such Python data science packages independently on Windows. Try Anaconda (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!

    Export data from Chrome developer tool

    To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.

    Better way to Format Currency Input editText?

    Here is how I was able to display a currency in an EditText that was easy to implement and works well for the user without the potential for crazy symbols all over the place. This will not try to do any formatting until the EditText no longer has focus. The user can still go back and make any edits without jeopardizing the formatting. I use the 'formattedPrice' variable for display only, and the 'itemPrice' variable as the value that I store/use for calculations.

    It seems to be working really well, but I've only been at this for a few weeks, so any constructive criticism is absolutely welcome!

    The EditText view in the xml has the following attribute:

    android:inputType="numberDecimal"
    

    Global variables:

    private String formattedPrice;
    private int itemPrice = 0;
    

    In the onCreate method:

    EditText itemPriceInput = findViewById(R.id.item_field_price);
    
    itemPriceInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            String priceString = itemPriceInput.getText().toString();
    
            if (! priceString.equals("")) {
                itemPrice = Double.parseDouble(priceString.replaceAll("[$,]", ""));
                formattedPrice = NumberFormat.getCurrencyInstance().format(itemPrice);
                itemPriceInput.setText(formattedPrice);
            }
        }
    });
    

    Getting Excel to refresh data on sheet from within VBA

    After a data connection update, some UDF's were not executing. Using a subroutine, I was trying to recalcuate a single column with:

    Sheets("mysheet").Columns("D").Calculate
    

    But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP "kluge" comment, it provided a fast/reliable solution to force recalculation of user-specified cells.

    Application.Calculation = xlManual
    DoEvents
    For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
        mycell.Formula = mycell.Formula
    Next
    DoEvents
    Application.Calculation = xlAutomatic
    

    Oracle SQL - DATE greater than statement

    As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

    SELECT * FROM OrderArchive
    WHERE OrderDate <= DATE '2015-12-31'
    

    If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

    SELECT * FROM OrderArchive
    WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                               'NLS_DATE_LANGUAGE = American');
    

    What are bitwise shift (bit-shift) operators and how do they work?

    The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue. Both operands have the same precedence and are left-to-right associative.

    Operator     Usage
    
     <<           Indicates the bits are to be shifted to the left.
    
     >>           Indicates the bits are to be shifted to the right.
    

    Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int. The result has the same type as the left operand (after the arithmetic conversions).

    The right operand should not have a negative value or a value that is greater than or equal to the width in bits of the expression being shifted. The result of bitwise shifts on such values is unpredictable.

    If the right operand has the value 0, the result is the value of the left operand (after the usual arithmetic conversions).

    The << operator fills vacated bits with zeros. For example, if left_op has the value 4019, the bit pattern (in 16-bit format) of left_op is:

    0000111110110011
    

    The expression left_op << 3 yields:

    0111110110011000
    

    The expression left_op >> 3 yields:

    0000000111110110
    

    Syntax of for-loop in SQL Server

    While Loop example in T-SQL which list current month's beginning to end date.

    DECLARE @Today DATE= GETDATE() ,
    @StartOfMonth DATE ,
    @EndOfMonth DATE;
    
    DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
    SET @EndOfMonth = EOMONTH(GETDATE());
    SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);
    
    WHILE @StartOfMonth <= @EndOfMonth
    BEGIN
        INSERT  INTO @DateList
        VALUES  ( @StartOfMonth );
        SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
    END;
    
    SELECT  DateLabel
    FROM    @DateList;  
    

    How to check if String is null

    You can check with null or Number.

    First, add a reference to Microsoft.VisualBasic in your application.

    Then, use the following code:

    bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
    bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
    

    In the above, b and c should both be false.

    How to list all databases in the mongo shell?

    Couple of commands are there to list all dbs in MongoDB shell.

    first , launch Mongodb shell using 'mongo' command.

    mongo

    Then use any of the below commands to list all the DBs.

    • show dbs
    • show databases
    • db.adminCommand( { listDatabases: 1 , nameOnly : true} )

    A snap shot

    For more details please check here

    Thank you.

    invalid_client in google oauth2

    None of the following were my issue - I resolved this by opening an incognito window. Something was obviously being cached somewhere, no amount of changing auth client settings helped and there were never any trailing or leading spaces in config values.

    Pass request headers in a jQuery AJAX GET call

    As of jQuery 1.5, there is a headers hash you can pass in as follows:

    $.ajax({
        url: "/test",
        headers: {"X-Test-Header": "test-value"}
    });
    

    From http://api.jquery.com/jQuery.ajax:

    headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

    If file exists then delete the file

    IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat
    

    android - save image into gallery

    Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:

    storageDir = new File(
        Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES
        ), 
        getAlbumName()
    );
    

    The picture doesn't go to the album. To do this, you need to call a scan:

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }
    

    You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery

    "NODE_ENV" is not recognized as an internal or external command, operable command or batch file

    It sounds like your error comes from an attempt to run something like this (which works in Linux)

    NODE_ENV=development node foo.js
    

    the equivalent in Windows would be

    SET NODE_ENV=development
    node foo.js
    

    running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.

    Dynamically add item to jQuery Select2 control that uses AJAX

    In case of Select2 Version 4+

    it has changed syntax and you need to write like this:

    // clear all option
    $('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
    
    // clear and add new option
    $("#select_with_data").html('').select2({data: [
     {id: '', text: ''},
     {id: '1', text: 'Facebook'},
     {id: '2', text: 'Youtube'},
     {id: '3', text: 'Instagram'},
     {id: '4', text: 'Pinterest'}]});
    
    
    
    //  append option
    $("#select_with_data").append('<option value="5">Twitter</option>');
    $("#select_with_data").val('5');
    $("#select_with_data").trigger('change');
    

    malloc for struct and pointer in C

    First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.

    JavaScript string encryption and decryption?

    _x000D_
    _x000D_
     var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");_x000D_
    //U2FsdGVkX18ZUVvShFSES21qHsQEqZXMxQ9zgHy+bu0=_x000D_
    _x000D_
    var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");_x000D_
    //4d657373616765_x000D_
    _x000D_
    _x000D_
    document.getElementById("demo1").innerHTML = encrypted;_x000D_
    document.getElementById("demo2").innerHTML = decrypted;_x000D_
    document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
    _x000D_
    Full working sample actually is:_x000D_
    _x000D_
        <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>_x000D_
    _x000D_
    <br><br>_x000D_
    <label>encrypted</label>_x000D_
    <div id="demo1"></div>_x000D_
    <br>_x000D_
    _x000D_
    <label>decrypted</label>_x000D_
    <div id="demo2"></div>_x000D_
    _x000D_
    <br>_x000D_
    <label>Actual Message</label>_x000D_
    <div id="demo3"></div>
    _x000D_
    _x000D_
    _x000D_

    Tab key == 4 spaces and auto-indent after curly braces in Vim

    The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

    As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

    You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

    How do I generate random number for each row in a TSQL Select?

    If you don't need it to be an integer, but any random unique identifier, you can use newid()

    SELECT table_name, newid() magic_number 
    FROM information_schema.tables
    

    CSS Box Shadow - Top and Bottom Only

    After some experimentation I found that a fourth value in the line controls the spread (at least in FF 10). I opposed the vertical offsets and gave them a negative spread.

    Here's the working pen: http://codepen.io/gillytech/pen/dlbsx

    <html>
    <head>
    <style type="text/css">
    
    #test {
        width: 500px;
        border: 1px  #CCC solid;
        height: 200px;
    
        box-shadow: 
            inset 0px 11px 8px -10px #CCC,
            inset 0px -11px 8px -10px #CCC; 
    }
    </style>
    </head>
    <body>
        <div id="test"></div>
    </body>
    </html>
    

    This works perfectly for me!

    How to force a WPF binding to refresh?

    MultiBinding friendly version...

    private void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
    }
    

    Count lines in large files

    On a multi-core server, use GNU parallel to count file lines in parallel. After each files line count is printed, bc sums all line counts.

    find . -name '*.txt' | parallel 'wc -l {}' 2>/dev/null | paste -sd+ - | bc
    

    To save space, you can even keep all files compressed. The following line uncompresses each file and counts its lines in parallel, then sums all counts.

    find . -name '*.xz' | parallel 'xzcat {} | wc -l' 2>/dev/null | paste -sd+ - | bc
    

    How to get datetime in JavaScript?

    function pad_2(number)
    {
         return (number < 10 ? '0' : '') + number;
    }
    
    function hours(date)
    {
        var hours = date.getHours();
        if(hours > 12)
            return hours - 12; // Substract 12 hours when 13:00 and more
        return hours;
    }
    
    function am_pm(date)
    {
        if(date.getHours()==0 && date.getMinutes()==0 && date.getSeconds()==0)
            return ''; // No AM for MidNight
        if(date.getHours()==12 && date.getMinutes()==0 && date.getSeconds()==0)
            return ''; // No PM for Noon
        if(date.getHours()<12)
            return ' AM';
        return ' PM';
    }
    
    function date_format(date)
    {
         return pad_2(date.getDate()) + '/' +
                pad_2(date.getMonth()+1) + '/' +
                (date.getFullYear() + ' ').substring(2) +
                pad_2(hours(date)) + ':' +
                pad_2(date.getMinutes()) +
                am_pm(date);
    }
    

    Code corrected as of Sep 3 '12 at 10:11

    How to run java application by .bat file

    @echo off
    echo You Are going to creata Java Class
    set /p Name=Enter your Class Name?:
    echo Your class Name is %Name% & pause
    echo To creat a Notepad
    pause
    notepad %Name%.java
    set path=%PATH%;C:\Program Files\Java\jdk1.6.0_14\bin
    pause
    javac
    echo Your java Path succsussfully set.
    javac %Name%.java
    pause
    echo Successfully Compiled
    java %Name%
    pause
    

    1)open a notpad 2)copy and past this code and save this file as ex: test.bat 3)Double Click tha batch file. 4)put your java codes into the notepad and save it as N.B.:- save this java file same folder that your batch file exists.

    Spring Boot Java Config Set Session Timeout

    • Spring Boot version 1.0: server.session.timeout=1200
    • Spring Boot version 2.0: server.servlet.session.timeout=10m
      NOTE: If a duration suffix is not specified, seconds will be used.

    Are email addresses case sensitive?

    From RFC 5321, section 2.3.11:

    The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

    So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

    The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

    "Name servers and resolvers must compare [domains] in a case-insensitive manner"

    In short, you are safe to treat email addresses as case-insensitive.

    How to convert a Hibernate proxy to a real entity object

    Thank you for the suggested solutions! Unfortunately, none of them worked for my case: receiving a list of CLOB objects from Oracle database through JPA - Hibernate, using a native query.

    All of the proposed approaches gave me either a ClassCastException or just returned java Proxy object (which deeply inside contained the desired Clob).

    So my solution is the following (based on several above approaches):

    Query sqlQuery = manager.createNativeQuery(queryStr);
    List resultList = sqlQuery.getResultList();
    for ( Object resultProxy : resultList ) {
        String unproxiedClob = unproxyClob(resultProxy);
        if ( unproxiedClob != null ) {
           resultCollection.add(unproxiedClob);
        }
    }
    
    private String unproxyClob(Object proxy) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
            for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                Method readMethod = property.getReadMethod();
                if ( readMethod.getName().contains("getWrappedClob") ) {
                    Object result = readMethod.invoke(proxy);
                    return clobToString((Clob) result);
                }
            }
        }
        catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException e) {
            LOG.error("Unable to unproxy CLOB value.", e);
        }
        return null;
    }
    
    private String clobToString(Clob data) throws SQLException, IOException {
        StringBuilder sb = new StringBuilder();
        Reader reader = data.getCharacterStream();
        BufferedReader br = new BufferedReader(reader);
    
        String line;
        while( null != (line = br.readLine()) ) {
            sb.append(line);
        }
        br.close();
    
        return sb.toString();
    }
    

    Hope this will help somebody!

    How to compare two JSON have the same properties without order?

    lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/

    var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": 
       "CAN_REQUEST_TO_JOIN"};
    var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", 
      "allowExternalMembers": "false"};
    
     if(_.isEqual(remoteJSON, localJSON)){
         //TODO
        }
    

    it works, for installation in angular, follow this

    How to get Tensorflow tensor dimensions (shape) as int values?

    for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:

    rows, columns = map(lambda i: i.value, tensor.get_shape())
    

    Alternative for <blink>

    can use this

    @keyframes blinkingText
    {
        0%{     opacity: 1;    }
        40%{    opacity: 0; }
        60%{    opacity: 0; }
        100%{   opacity: 1;    }
    }
    
    .blinking
    {
        animation:blinkingText 2s reverse infinite;
    }
    

    How to show Page Loading div until the page has finished loading?

    I've needed this and after some research I came up with this (jQuery needed):

    First, right after the <body> tag add this:

    <div id="loading">
      <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
    </div>
    

    Then add the style class for the div and image to your CSS:

    #loading {
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      position: fixed;
      display: block;
      opacity: 0.7;
      background-color: #fff;
      z-index: 99;
      text-align: center;
    }
    
    #loading-image {
      position: absolute;
      top: 100px;
      left: 240px;
      z-index: 100;
    }
    

    Then, add this javascript to your page (preferably at the end of your page, before your closing </body> tag, of course):

    <script>
      $(window).load(function() {
        $('#loading').hide();
      });
    </script>
    

    Finally, adjust the position of the loading image and the background-colour of the loading div with the style class.

    This is it, should work just fine. But of course you have to have an ajax-loader.gif somewhere. Freebies here. (Right-click > Save Image As...)

    Using Java generics for JPA findAll() query with WHERE clause

    I found this page very useful

    https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

    public abstract class GenericDAOWithJPA<T, ID extends Serializable> {
    
        private Class<T> persistentClass;
    
        //This you might want to get injected by the container
        protected EntityManager entityManager;
    
        @SuppressWarnings("unchecked")
        public GenericDAOWithJPA() {
                this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    
        @SuppressWarnings("unchecked")
        public List<T> findAll() {
                return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
        }
    }
    

    Django values_list vs values

    You can get the different values with:

    set(Article.objects.values_list('comment_id', flat=True))
    

    Android Fragments and animation

    As for me, i need the view diraction:

    in -> swipe from right

    out -> swipe to left

    Here works for me code:

    slide_in_right.xml

    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="50%p" android:toXDelta="0"
                android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
                android:duration="@android:integer/config_mediumAnimTime" />
    </set>
    

    slide_out_left.xml

     <set xmlns:android="http://schemas.android.com/apk/res/android">
            <translate android:fromXDelta="0" android:toXDelta="-50%p"
                    android:duration="@android:integer/config_mediumAnimTime"/>
            <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
                    android:duration="@android:integer/config_mediumAnimTime" />
        </set>
    

    transaction code:

    inline fun FragmentActivity.setContentFragment(
            containerViewId: Int,
            backStack: Boolean = false,
            isAnimate: Boolean = false,
            f: () -> Fragment
    
    ): Fragment? {
        val manager = supportFragmentManager
        return f().apply {
            manager.beginTransaction().let {
                if (isAnimate)
                    it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
    
                if (backStack) {
                    it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
                } else {
                    it.replace(containerViewId, this, "Fr").commit()
                }
            }
        }
    }
    

    Image encryption/decryption using AES256 symmetric block ciphers

    To add bouncy castle to Android project: https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16/1.45

    Add this line in your Main Activity:

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    

    public class AESHelper {
    
        private static final String TAG = "AESHelper";
    
        public static byte[] encrypt(byte[] data, String initVector, String key) {
            try {
                IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
                Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                SecretKeySpec k = new SecretKeySpec(Base64.decode(key, Base64.DEFAULT), "AES");
                c.init(Cipher.ENCRYPT_MODE, k, iv);
                return c.doFinal(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        public static byte[] decrypt(byte[] data, String initVector, String key) {
            try {
                IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
                Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                SecretKeySpec k = new SecretKeySpec(Base64.decode(key, Base64.DEFAULT), "AES");
                c.init(Cipher.DECRYPT_MODE, k, iv);
                return c.doFinal(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        public static String keyGenerator() throws NoSuchAlgorithmException {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(192);
    
            return Base64.encodeToString(keyGenerator.generateKey().getEncoded(),
                    Base64.DEFAULT);
        }
    }
    

    laravel throwing MethodNotAllowedHttpException

    My suspicion is the problem lies in your route definition.

    You defined the route as a GET request but the form is probably sending a POST request. Change your route definition to match the form's request method.

    Route::post('/validate', [MemberController::class, 'validateCredentials']);
    

    It's generally better practice to use named routes (helps to scale if the controller method/class changes).

    Route::post('/validate', [MemberController::class, 'validateCredentials'])
        ->name('member.validateCredentials');
    

    In the view, use the validation route as the form's action.

    <form action="{{ route('member.validateCredentials') }}" method="POST">
      @csrf
    ...
    </form>
    

    R: rJava package install failing

    What worked for me was changing JAVA_HOME from file /usr/lib/R/etc/javaconf

    I first checked what was my version of Java enabled : sudo update-alternatives --config java. In my case, it was java-8-oracle

    I opened the file /usr/lib/R/etc/javaconf and replaced default-java by java-8-oracle :

    ${JAVA_HOME=/usr/lib/jvm/default-java}
    

    replaced by :

    ${JAVA_HOME=/usr/lib/jvm/java-8-oracle}
    

    And then sudo R CMD javareconf

    I restarted RStudio, and could then install rJava.

    jQuery toggle animation

    onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 
    
    onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"
    

    Just put two stops -- one onmouseover and one onmouseout.

    How to convert comma-separated String to List?

    List<String> items = Arrays.asList(commaSeparated.split(","));
    

    That should work for you.

    Radio Buttons "Checked" Attribute Not Working

    I could repro this by setting the name of input tag the same for two groups of input like below:

    <body>
      <div>
          <div>
            <h3>Header1</h3>
          </div>
          <div>
              <input type="radio" name="gender" id="male_1" value="male"> Male<br>
              <input type="radio" name="gender" id="female_1" value="female" checked="checked"> Female<br>
              <input type="submit" value="Submit">
          </div>
      </div>
    
    
      <div>
          <div>
            <h3>Header2</h3>
          </div>
          <div>
              <input type="radio" name="gender" id="male_2" value="male"> Male<br>
              <input type="radio" name="gender" id="female_2" value="female" checked="checked"> Female<br>
              <input type="submit" value="Submit">
          </div>
      </div>
    </body>
    

    (To see this running, click here)

    The following two solutions both fix the problem:

    1. Use different names for the inputs in the second group
    2. Use form tag instead of div tag for one of the groups (can't really figure out the real reason why this would solve the problem. Would love to hear some opinions on this!)

    How can I reduce the waiting (ttfb) time

    I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)

    A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.

    Equivalent to AssemblyInfo in dotnet core/csproj

    I do the following for my .NET Standard 2.0 projects.

    Create a Directory.Build.props file (e.g. in the root of your repo) and move the properties to be shared from the .csproj file to this file.

    MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs.

    They also get applied to the nuget package when building one with dotnet pack or via the UI in Visual Studio 2017.

    See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build

    Example:

    <Project>
        <PropertyGroup>
            <Company>Some company</Company>
            <Copyright>Copyright © 2020</Copyright>
            <AssemblyVersion>1.0.0.1</AssemblyVersion>
            <FileVersion>1.0.0.1</FileVersion>
            <Version>1.0.0.1</Version>
            <!-- ... -->
        </PropertyGroup>
    </Project>
    

    JQuery/Javascript: check if var exists

    To test for existence there are two methods.

    a. "property" in object

    This method checks the prototype chain for existence of the property.

    b. object.hasOwnProperty( "property" )

    This method does not go up the prototype chain to check existence of the property, it must exist in the object you are calling the method on.

    var x; // variable declared in global scope and now exists
    
    "x" in window; // true
    window.hasOwnProperty( "x" ); //true
    

    If we were testing using the following expression then it would return false

    typeof x !== 'undefined'; // false
    

    What is Node.js?

    Also, do not forget to mention that Google's V8 is VERY fast. It actually converts the JavaScript code to machine code with the matched performance of compiled binary. So along with all the other great things, it's INSANELY fast.

    How to update Python?

    • Official Python .msi installers are designed to replace:

      • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
      • a "snapshot" (built from source) installation with any micro version
    • A snapshot installer is designed to replace any snapshot with a lower micro version.

    (See responsible code for 2.x, for 3.x)

    Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

    • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
    • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
    • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

    How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

    If you want to avoid the error message and you are not using Bootstrap tool tips, you can define window.Tether before loading Bootstrap.

    <script>
      window.Tether = {};
    </script>
    <script src="js/bootstrap.min.js"></script>
    

    java - path to trustStore - set property doesn't work?

    Both

    -Djavax.net.ssl.trustStore=path/to/trustStore.jks
    

    and

    System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
    

    do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

    update query with join on two tables

    Using table aliases in the join condition:

    update addresses a
    set cid = b.id 
    from customers b 
    where a.id = b.id
    

    Creating temporary files in Android

    This is what I typically do:

    File outputDir = context.getCacheDir(); // context being the Activity pointer
    File outputFile = File.createTempFile("prefix", "extension", outputDir);
    

    As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

    How to increment variable under DOS?

    I've found my own solution.

    Download FreeDOS from here: http://chtaube.eu/computers/freedos/bootable-usb/

    Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:

    Set /P Variable =< Counter.txt
    

    Then, I can check if it has run 250 cycles by doing:

    if %variable%==250 echo PASS
    

    BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.

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

    This is a very common question seen on Stackoverflow.

    The important part here is not the command displayed in the error, but what the actual error tells you instead.

    a Quick breakdown on why this error is received.

    cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

    How do I fix this:

    When Actual Command/executable fails

    First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

    If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

    1. specify the full path to the file.

      "C:\My_Files\mycommand.exe"

    2. Add the location of the file to your environment Variables.

    Goto:
    ------> Control Panel-> System-> Advanced System Settings->Environment Variables

    In the System Variables Window, locate path and select edit

    Now simply add your path to the end of the string, seperated by a semicolon ; as:

    ;C:\My_Files\
    

    Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

    When C:\Program or Similar fails

    This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

    So to execute C:\Program Files\My-App\Mobile.exe simply run as:

    "C:\Program Files\My-App\Mobile.exe"
    

    How can I clone a JavaScript object except for one key?

    What about this? I never found this patter around but I was just trying to exclude one or more properties without the need of creating an extra object. This seems to do the job but there are some side effects I'm not able to see. For sure is not very readable.

    const postData = {
       token: 'secret-token',
       publicKey: 'public is safe',
       somethingElse: true,
    };
    
    const a = {
       ...(({token, ...rest} = postData) => (rest))(),
    }
    
    /**
    a: {
       publicKey: 'public is safe',
       somethingElse: true,
    }
    */
    

    Making Python loggers output all messages to stdout in addition to log file

    I simplified my source code (whose original version is OOP and uses a configuration file), to give you an alternative solution to @EliasStrehle's one, without using the dictConfig (thus easiest to integrate with existing source code):

    import logging
    import sys
    
    
    def create_stream_handler(stream, formatter, level, message_filter=None):
        handler = logging.StreamHandler(stream=stream)
        handler.setLevel(level)
        handler.setFormatter(formatter)
        if message_filter:
            handler.addFilter(message_filter)
        return handler
    
    
    def configure_logger(logger: logging.Logger, enable_console: bool = True, enable_file: bool = True):
        if not logger.handlers:
            if enable_console:
                message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
                date_format: str = '%Y/%m/%d %H:%M:%S'
                level: int = logging.DEBUG
                formatter = logging.Formatter(message_format, date_format, '{')
    
                # Configures error output (from Warning levels).
                error_output_handler = create_stream_handler(sys.stderr, formatter,
                                                             max(level, logging.WARNING))
                logger.addHandler(error_output_handler)
    
                # Configures standard output (from configured Level, if lower than Warning,
                #  and excluding everything from Warning and higher).
                if level < logging.WARNING:
                    standard_output_filter = lambda record: record.levelno < logging.WARNING
                    standard_output_handler = create_stream_handler(sys.stdout, formatter, level,
                                                                    standard_output_filter)
                    logger.addHandler(standard_output_handler)
    
            if enable_file:
                message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
                date_format: str = '%Y/%m/%d %H:%M:%S'
                level: int = logging.DEBUG
                output_file: str = '/tmp/so_test.log'
    
                handler = logging.FileHandler(output_file)
                formatter = logging.Formatter(message_format, date_format, '{')
                handler.setLevel(level)
                handler.setFormatter(formatter)
                logger.addHandler(handler)
    

    This is a very simple way to test it:

    logger: logging.Logger = logging.getLogger('MyLogger')
    logger.setLevel(logging.DEBUG)
    configure_logger(logger, True, True)
    logger.debug('Debug message ...')
    logger.info('Info message ...')
    logger.warning('Warning ...')
    logger.error('Error ...')
    logger.fatal('Fatal message ...')
    

    RegEx to parse or validate Base64 data

    From the RFC 4648:

    Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

    So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

    But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

    ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
    

    The infamous java.sql.SQLException: No suitable driver found

    I encountered this issue by putting a XML file into the src/main/resources wrongly, I deleted it and then all back to normal.

    Can't build create-react-app project with custom PUBLIC_URL

    This problem becomes apparent when you try to host a react app in github pages.

    How I fixed this,

    In in my main application file, called app.tsx, where I include the router. I set the basename, eg, <BrowserRouter basename="/Seans-TypeScript-ReactJS-Redux-Boilerplate/">

    Note that it is a relative url, this completely simplifies the ability to run locally and hosted. The basename value, matches the repository title on GitHub. This is the path that GitHub pages will auto create.

    That is all I needed to do.

    See working example hosted on GitHub pages at

    https://sean-bradley.github.io/Seans-TypeScript-ReactJS-Redux-Boilerplate/

    Delete a row in Excel VBA

    Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

    dim rng as range
    dim rDel as range
    
    for each rng in {the range you're searching}
       if {Conditions to be met} = true then
          if not rDel is nothing then
             set rDel = union(rng,rDel)
          else
             set rDel = rng
          end if
       end if
     next
     
     rDel.entirerow.delete
    

    That way you don't have to worry about sorting or things being at the bottom.

    TypeError: $ is not a function WordPress

    If you have included jQuery, there may be a conflict. Try using jQuery instead of $.

    File Explorer in Android Studio

    it has changed and its docked to the right bottom of your android studio by default.

    enter image description here

    if you dont have that you can open it through view -> tool windows -> device file explorer

    enter image description here

    How to create a temporary directory and get the path / file name in Python

    If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

    import os
    import tempfile
    
    with tempfile.TemporaryDirectory() as tmp_dir:
        # generate some random files in it
         files_in_dir = os.listdir(tmp_dir)
    

    Fit cell width to content

    Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

    One option is to replace table with CSS4 flex divs:

    https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    That works in new browsers i.e. IE11+ see table at the bottom of the article.

    Twitter Bootstrap onclick event on buttons-radio

    I needed to do the same thing for a chart where you could select the period of the data that should be displayed.

    Therefore I introduced the CSS class 'btn-group-radio' and used the following unobtrusive javascript one-liner:

    // application.js
    $(document).ready(function() {
      $('.btn-group-radio .btn').click(function() {
        $(this).addClass('active').siblings('.btn').removeClass('active');
      });
    });
    

    And here is the HTML:

    <!-- some arbitrary view -->
    <div class="btn-group btn-group-radio">
      <%= link_to '1W', charts_path('1W'), class: 'btn btn-default active', remote: true %>
      <%= link_to '1M', charts_path('1M'), class: 'btn btn-default', remote: true %>
      <%= link_to '3M', charts_path('3M'), class: 'btn btn-default', remote: true %>
      <%= link_to '6M', charts_path('6M'), class: 'btn btn-default', remote: true %>
      <%= link_to '1Y', charts_path('1Y'), class: 'btn btn-default', remote: true %>
      <%= link_to 'All', charts_path('all'), class: 'btn btn-default', remote: true %>
    </div>
    

    Sending SMS from PHP

    Clickatell is a popular SMS gateway. It works in 200+ countries.

    Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

    The HTTP/S method is as simple as this:

    http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

    The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

    user: xxxxx
    password: xxxxx
    api_id: xxxxx
    to: 448311234567
    text: Meet me at home
    

    You can also test the gateway (incoming and outgoing) for free from your browser

    What's "P=NP?", and why is it such a famous question?

    1. A yes-or-no problem is in P (Polynomial time) if the answer can be computed in polynomial time.
    2. A yes-or-no problem is in NP (Non-deterministic Polynomial time) if a yes answer can be verified in polynomial time.

    Intuitively, we can see that if a problem is in P, then it is in NP. Given a potential answer for a problem in P, we can verify the answer by simply recalculating the answer.

    Less obvious, and much more difficult to answer, is whether all problems in NP are in P. Does the fact that we can verify an answer in polynomial time mean that we can compute that answer in polynomial time?

    There are a large number of important problems that are known to be NP-complete (basically, if any these problems are proven to be in P, then all NP problems are proven to be in P). If P = NP, then all of these problems will be proven to have an efficient (polynomial time) solution.

    Most scientists believe that P!=NP. However, no proof has yet been established for either P = NP or P!=NP. If anyone provides a proof for either conjecture, they will win US $1 million.

    How to return a boolean method in java?

    try this:

    public boolean verifyPwd(){
            if (!(pword.equals(pwdRetypePwd.getText()))){
                      txtaError.setEditable(true);
                      txtaError.setText("*Password didn't match!");
                      txtaError.setForeground(Color.red);
                      txtaError.setEditable(false);
                      return false;
               }
            else {
                return true;
            }
    
    }
    
    if (verifyPwd()==true){
        addNewUser();
    }
    else {
        // passwords do not match
    }
    

    @UniqueConstraint and @Column(unique = true) in hibernate annotation

    As said before, @Column(unique = true) is a shortcut to UniqueConstraint when it is only a single field.

    From the example you gave, there is a huge difference between both.

    @Column(unique = true)
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private ProductSerialMask mask;
    
    @Column(unique = true)
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private Group group;
    

    This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

    On the other hand,

    @Table(
       name = "product_serial_group_mask", 
       uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
    )
    

    Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.

    If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:

    @Table(
            name = "product_serial_group_mask",
            uniqueConstraints = {
                    @UniqueConstraint(columnNames = "mask"),
                    @UniqueConstraint(columnNames = "group")
            }
    )
    

    This has the same effect as the first code block.

    Fast way to get the min/max values among properties of object

    var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
    var maxValue = Math.max(...Object.values(newObj))
    var minValue = Math.min(...Object.values(newObj))
    

    How to do something before on submit?

    If you have a form as such:

    <form id="myform">
    ...
    </form>
    

    You can use the following jQuery code to do something before the form is submitted:

    $('#myform').submit(function() {
        // DO STUFF...
        return true; // return false to cancel form action
    });
    

    Python write line by line to a text file

    You may want to look into os dependent line separators, e.g.:

    import os
    
    with open('./output.txt', 'a') as f1:
        f1.write(content + os.linesep)
    

    How to get terminal's Character Encoding

    To see the current locale information use locale command. Below is an example on RHEL 7.8

    [usr@host ~]$ locale
    LANG=en_US.UTF-8
    LC_CTYPE="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_PAPER="en_US.UTF-8"
    LC_NAME="en_US.UTF-8"
    LC_ADDRESS="en_US.UTF-8"
    LC_TELEPHONE="en_US.UTF-8"
    LC_MEASUREMENT="en_US.UTF-8"
    LC_IDENTIFICATION="en_US.UTF-8"
    LC_ALL=
    

    ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

    I was able to toggle this error by changing a single thing. In my ASP.Net Core 1.0 RC2 Web Application project's launchSettings.json file:

      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "https://localhost:18177/",
          "sslPort": 0
        }
      },
    

    to

      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:18177/",
          "sslPort": 0
        }
      },
    

    I had changed to https in an attempt to run the project using that protocol. Apparently this is not the place to make that change. I suspect it is creating multiple bindings on the same port, and IIS Express doesn't like that.

    How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

    You'd have to test it but if you embedded an iframe within your page then used CSS to absolutely position the 1st row & column at 0,0 in the iframe page would that solve your problem?

    Table row and column number in jQuery

    You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

    $('td').click(function(){
      var col = $(this).parent().children().index($(this));
      var row = $(this).parent().parent().children().index($(this).parent());
      alert('Row: ' + row + ', Column: ' + col);
    });
    

    Check a running example here.

    Enable binary mode while restoring a Database from an SQL dump

    Extract your file with Tar archiving tool. you can use it in this way:

    tar xf example.sql.gz
    

    How do I add multiple conditions to "ng-disabled"?

    this way worked for me

    ng-disabled="(user.Role.ID != 1) && (user.Role.ID != 2)"

    Finding the median of an unsorted array

    The quick select algorithm can find the k-th smallest element of an array in linear (O(n)) running time. Here is an implementation in python:

    import random
    
    def partition(L, v):
        smaller = []
        bigger = []
        for val in L:
            if val < v: smaller += [val]
            if val > v: bigger += [val]
        return (smaller, [v], bigger)
    
    def top_k(L, k):
        v = L[random.randrange(len(L))]
        (left, middle, right) = partition(L, v)
        # middle used below (in place of [v]) for clarity
        if len(left) == k:   return left
        if len(left)+1 == k: return left + middle
        if len(left) > k:    return top_k(left, k)
        return left + middle + top_k(right, k - len(left) - len(middle))
    
    def median(L):
        n = len(L)
        l = top_k(L, n / 2 + 1)
        return max(l)
    

    Horizontal swipe slider with jQuery and touch devices support?

    Have you seen FlexSlider from WooThemes? I've used it on several recent projects with great success. It's touch enabled too so it will work on both mouse-based browsers as well as touch-based browsers in iOS and Android.

    No module named 'pymysql'

    1. Make sure that you're working with the version of Python that think you are. Within Python run import sys and print(sys.version).

    2. Select the correct package manager to install pymysql with:

      • For Python 2.x sudo pip install pymysql.
      • For Python 3.x sudo pip3 install pymysql.
      • For either running on Anaconda: sudo conda install pymysql.
      • If that didn't work try APT: sudo apt-get install pymysql.
    3. If all else fails, install the package directly:

      • Go to the PyMySQL page and download the zip file.
      • Then, via the terminal, cd to your Downloads folder and extract the folder.
      • cd into the newly extracted folder.
      • Install the setup.py file with: sudo python3 setup.py install.

    This answer is a compilation of suggestions. Apart from the other ones proposed here, thanks to the comment by @cmaher on this related thread.

    Content Type text/xml; charset=utf-8 was not supported by service

    First Google hit says:

    this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.

    It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.

    PostgreSQL database default location on Linux

    Default in Debian 8.1 and PostgreSQL 9.4 after the installation with the package manager apt-get

    ps auxw |  grep postgres | grep -- -D
    postgres 17340  0.0  0.5 226700 21756 ?        S    09:50   0:00 /usr/lib/postgresql/9.4/bin/postgres -D /var/lib/postgresql/9.4/main -c config_file=/etc/postgresql/9.4/main/postgresql.conf
    

    so apparently /var/lib/postgresql/9.4/main.

    Running Facebook application on localhost

    Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.

    Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000 for whatever reason. However, you can use a completely made-up domain name like yoursite.dev by running a local server and pointing yoursite.dev to 127.0.0.1:3000 or wherever your localhost was pointing to.

    Step 1: Install or update Nginx

    $ brew install nginx (install) or $ brew upgrade nginx (update)

    Step 2: Open up your nginx config file

    /usr/local/etc/nginx/nginx.conf (usually here)

    /opt/boxen/config/nginx/nginx.conf(if you use Boxen)

    Step 3 Add this bit of code into your http {} block

    Replace proxy_pass with wherever you want to point yoursite.dev to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000

    server {
      listen       yoursite.dev:80;
      server_name  yoursite.dev;
      location / {
        proxy_pass http://127.0.0.1:3000;
      }
    }
    

    Step 4: Edit your hosts file, in /etc/hosts on Mac to include

    127.0.0.1   yoursite.dev
    

    This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.

    Step 5: Every time you use your dev environment going forward, you use the yoursite.dev in the address bar instead of localhost:3000 so Facebook logs you in correctly.

    Create a 3D matrix

    Create a 3D matrix

    A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix
    

    Add a 3rd dimension to a matrix

    B = zeros(4,4);  
    C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
    C(:,:,1) = B;                        %# Copy the content of B into C's first set of values
    

    zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

    There is no explicit bound on the number of dimensions a matrix may have.

    In C#, how to check whether a string contains an integer?

    This work for me.

    ("your string goes here").All(char.IsDigit)
    

    How to add additional fields to form before submit?

    Try this:

    $('#form').submit(function(eventObj) {
        $(this).append('<input type="hidden" name="field_name" value="value" /> ');
        return true;
    });
    

    How to get an HTML element's style values in javascript?

    You can make function getStyles that'll take an element and other arguments are properties that's values you want.

    const convertRestArgsIntoStylesArr = ([...args]) => {
        return args.slice(1);
    }
    
    const getStyles = function () {
        const args = [...arguments];
        const [element] = args;
    
        let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
    
        const styles = window.getComputedStyle(element);
        const stylesObj = stylesProps.reduce((acc, v) => {
            acc[v] = styles.getPropertyValue(v);
            return acc;
        }, {});
    
        return stylesObj;
    };
    

    Now, you can use this function like this:

    const styles = getStyles(document.body, "height", "width");
    

    OR

    const styles = getStyles(document.body, ["height", "width"]);
    

    How to change int into int64?

    i := 23
    i64 := int64(i)
    fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
    

    Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

    If anyone is still experiencing this issue, I found that it related to a difference in Oracle Client versions.

    I have posted my full experience and solution here: https://stackoverflow.com/a/43806765/923177

    Make a td fixed size (width,height) while rest of td's can expand

    just set the width of the td/column you want to be fixed and the rest will expand.

    <td width="200"></td>
    

    Style jQuery autocomplete in a Bootstrap input field

    The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2

    When using jQuery version 3.1.1 it seem to not happen.

    Possible reason is the notable update in v3.2.0 related to a bug fix on .width() and .height(). Check out the jQuery release notes for further details: v3.2.0 / v3.1.1

    Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used

    Strip double quotes from a string in .NET

    s = s.Replace("\"", "");
    

    You need to use the \ to escape the double quote character in a string.

    Get ASCII value at input word

    char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

    System.out.println("char " + ch + " has the following value : " + (int) ch);
    

    Convert InputStream to BufferedReader

    A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

    Reader reader = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(reader);
    

    Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

    Find document with array that contains a specific value

    There is no $contains operator in mongodb.

    You can use the answer from JohnnyHK as that works. The closest analogy to contains that mongo has is $in, using this your query would look like:

    PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
    

    how to implement Pagination in reactJs

    Here is a way to create your Custom Pagination Component from react-bootstrap lib and this component you can use Throughout your project enter image description here

    Your Pagination Component (pagination.jsx or js)

    import React, { Component } from "react"; 
    import { Pagination } from "react-bootstrap"; 
    import PropTypes from "prop-types";
    
    export default class PaginationHandler extends Component {  
    
       constructor(props) {
        super(props);
        this.state = {
          paging: {
            offset: 0,
            limit: 10
          },
          active: 0
        };  
        }
    
      pagingHandler = () => {
        let offset = parseInt(event.target.id);
        this.setState({
          active: offset
        });
        this.props.pageHandler(event.target.id - 1);   };
    
      nextHandler = () => {
        let active = this.state.active;
        this.setState({
          active: active + 1
        });
        this.props.pageHandler(active + 1);   };
    
      backHandler = () => {
        let active = this.state.active;
        this.setState({
          active: active - 1
        });
        this.props.pageHandler(active - 1);   };
    
      renderPageNumbers = (pageNumbers, totalPages) => {
        let { active } = this.state;
        return (
          <Pagination>
            <Pagination.Prev disabled={active < 5} onClick={ active >5 && this.backHandler} />
    
            {
          pageNumbers.map(number => {
                  if (
                    number >= parseInt(active) - 3 &&
                    number <= parseInt(active) + 3 
                  ) {
                    return (
                      <Pagination.Item
                        id={number}
                        active={number == active}
                        onClick={this.pagingHandler}
                      >
                        {number}
                      </Pagination.Item>
                    );
                  } else {
                    return null;
                  }
            })}
            <Pagination.Next onClick={ active <= totalPages -4 && this.nextHandler} />
          </Pagination>
        );   };
    
      buildComponent = (props, state) => {
        const { totalPages } = props;
        const pageNumbers = [];
        for (let i = 1; i <= totalPages; i++) {
          pageNumbers.push(i);
        }
        return (
          <div className="pull-right">
          {this.renderPageNumbers(pageNumbers ,totalPages)}
          </div>
        );   
    };
    
      render() {
        return this.buildComponent(this.props, this.state);
      } 
    
    } 
       PaginationHandler.propTypes = 
       {
        paging: PropTypes.object,
        pageHandler: PropTypes.func,
        totalPages: PropTypes.object 
       };
    

    Use of Above Component in your Component

    import Pagination from "../pagination";
    
    pageHandler = (offset) =>{
          this.setState(({ paging }) => ({
            paging: { ...paging, offset: offset }
          }));
       }
       render() {
        return (
          <div>
             <Pagination
              paging = {paging}
              pageHandler = {this.pageHandler}
              totalPages = {totalPages}>
              </Pagination>
          </div>
        );
      }
    

    Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

    I ran into this and it was caused by the entity's ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity's ID has been set.

    From Paul Bellora's comment

    I had this exact issue, caused by forgetting to include the hidden ID input in the .cshtml edit page

    Stopping a JavaScript function when a certain condition is met

    Try using a return statement. It works best. It stops the function when the condition is met.

    function anything() {
        var get = document.getElementsByClassName("text ").value;
        if (get == null) {
            alert("Please put in your name");
        }
    
        return;
    
        var random = Math.floor(Math.random() * 100) + 1;
        console.log(random);
    }
    

    powerpoint loop a series of animation

    Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

    First, click Slide Show > Set Up Show.

    Put a checkmark to Loop continuously until 'Esc'.

    Click Ok. Now, Click Slide Show > Custom Shows. Click New.

    Select the slide you are looping, click Add. Click Ok and Close.

    Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

    Right click on the thumbnail of the current slide, select Hide Slide.

    Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

    This has worked for me.

    Retrieve data from website in android app

    You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

    Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

    To install in Eclipse:

    1. Right Click on project
    2. BuildPath
    3. Add External Archives
    4. select the .jar file

    You can parse according to tag/parent/child very comfortably

    What is the difference between a static and a non-static initialization code block

    This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/

    1. Execution Order

    Look at the following class, do you know which one gets executed first?

    public class Foo {
     
        //instance variable initializer
        String s = "abc";
     
        //constructor
        public Foo() {
            System.out.println("constructor called");
        }
     
        //static initializer
        static {
            System.out.println("static initializer called");
        }
     
        //instance initializer
        {
            System.out.println("instance initializer called");
        }
     
        public static void main(String[] args) {
            new Foo();
            new Foo();
        }
    }
    

    Output:

    static initializer called

    instance initializer called

    constructor called

    instance initializer called

    constructor called

    2. How do Java instance initializer work?

    The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

    Instead of

    int b = 0, you could write

    int b;
    b = 0;
    

    Therefore, instance initializers and instance variable initializers are pretty much the same.

    3. When are instance initializers useful?

    The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

    1. Initializer code must handle exceptions
    2. Perform calculations that can’t be expressed with an instance variable initializer.

    Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

    With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

    Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)

    Thanks to Derhein.

    Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.

    Clicking HTML 5 Video element to play, pause video, breaks play button

    Not to bring up an old post but I landed on this question in my search for the same solution. I ended up coming up with something of my own. Figured I'd contribute.

    HTML:

    <video class="video"><source src=""></video>
    

    JAVASCRIPT: "JQUERY"

    $('.video').click(function(){this.paused?this.play():this.pause();});
    

    How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

    Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.

    private func collectionViewLayout() -> UICollectionViewLayout {
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionHeadersPinToVisibleBounds = true
        // Important: if direction is horizontal use minimumItemSpacing instead. 
        layout.scrollDirection = .vertical
        
        let itemHeight: CGFloat = 240
        let minCellWidth :CGFloat = 130.0
        let minItemSpacing: CGFloat = 10
        let containerWidth: CGFloat = self.view.bounds.width
        let maxCellCountPerRow: CGFloat =  floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
        
        let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow  ) )
        // Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
        let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )
    
        
        layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        layout.minimumInteritemSpacing = min(minItemSpacing,inset)
        layout.minimumLineSpacing = minItemSpacing
        layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)
    
        
        return layout
    }
    

    Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

    If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

    Populating spinner directly in the layout xml

    In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!

    Example -Before :

    <string-array name="roomSize">
        <item>Small(0-4)</item>
        <item>Medium(4-8)</item>
        <item>Large(9+)</item>
    </string-array>
    

    Example - After:

    <string-array android:name="roomSize">
        <item>Small(0-4)</item>
        <item>Medium(4-8)</item>
        <item>Large(9+)</item>
    </string-array>
    

    How to browse localhost on Android device?

    I had similar issue but I could not resolve it using static ip address or changing firewall settings. I found a useful utility which can be configured in a minute.

    We can host our local web server on cloud for free. On exposing it on cloud we get a different URL which we can use instead of localhost and access the webserver from anywhere.

    The utility is ngrok https://ngrok.com/download Steps:

    1. Signup
    2. Download
    3. Extract the file and double click to run it, this will open a command prompt
    4. Type "ngrok.exe http 80" without quotes to host for example XAMPP apache server which runs on port 80.
    5. Copy the new url name generated on the cmd prompt for e.g. if it is like this "fafb42f.ngrok.io"

    URL like : http://localhost/php/test.php Should be modified like this : http://fafb42f.ngrok.io/php/test.php

    Now this URL can be accessed from phone.

    Regex match one of two words

    This will do:

    /^(apple|banana)$/
    

    to exclude from captured strings (e.g. $1,$2):

    (?:apple|banana)
    

    Convert a string to integer with decimal in Python

    What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

    s = '234.67'
    i = int(round(float(s)))
    

    Otherwise, just do:

    s = '234.67'
    i = int(float(s))
    

    mysql_fetch_array() expects parameter 1 to be resource problem

    You are using this :

    mysql_fetch_array($result)
    

    To get the error you're getting, it means that $result is not a resource.


    In your code, $result is obtained this way :

    $result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
    

    If the SQL query fails, $result will not be a resource, but a boolean -- see mysql_query.

    I suppose there's an error in your SQL query -- so it fails, mysql_query returns a boolean, and not a resource, and mysql_fetch_array cannot work on that.


    You should check if the SQL query returns a result or not :

    $result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
    if ($result !== false) {
        // use $result
    } else {
        // an error has occured
        echo mysql_error();
        die;    // note : echoing the error message and dying 
                // is OK while developping, but not in production !
    }
    

    With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)


    Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !

    For example, here, you should make sure that $_GET['id'] contains nothing else than an integer, using something like this :

    $result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
    

    Or you should check this before trying to execute the query, to display a nicer error message to the user.

    Find out who is locking a file on a network share

    PsFile does work on remote machines. If my login account already has access to the remote share, I can just enter:

    psfile \\remote-share
    

    (replace "remote-share" with the name of your file server) and it will list every opened document on that share, along with who has it open, and the file ID if I want to force the file closed. For me, this is a really long list, but it can be narrowed down by entering part of a path:

    psfile \\remote-share I:\\Human_Resources
    

    This is kind of tricky, since in my case this remote share is mounted as Z: on my local machine, but psfile identifies paths as they are defined on the remote file server, which in my case is I: (yours will be different). I just had to comb through the results of my first psfile run to see some of the paths it returned and then run it again with a partial path to narrow down the results.

    Optionally, PsFile will let you specify credentials for the remote share if you need to supply them for access.

    Lastly, a little known tip: if someone clicks on a file in Windows Explorer and cuts or copies the file with the intent to paste it somewhere else, that act also places a lock on the file.

    Sending images using Http Post

    The loopj library can be used straight-forward for this purpose:

    SyncHttpClient client = new SyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("text", "some string");
    params.put("image", new File(imagePath));
    
    client.post("http://example.com", params, new TextHttpResponseHandler() {
      @Override
      public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        // error handling
      }
    
      @Override
      public void onSuccess(int statusCode, Header[] headers, String responseString) {
        // success
      }
    });
    

    http://loopj.com/

    In Angular, how to redirect with $location.path as $http.post success callback

    Instead of using success, I change it to then and it works.

    here is the code:

    lgrg.controller('login', function($scope, $window, $http) {
        $scope.loginUser = {};
    
        $scope.submitForm = function() {
            $scope.errorInfo = null
    
            $http({
                method  : 'POST',
                url     : '/login',
                headers : {'Content-Type': 'application/json'}
                data: $scope.loginUser
            }).then(function(data) {
                if (!data.status) {
                    $scope.errorInfo = data.info
                } else {
                    //page jump
                    $window.location.href = '/admin';
                }
            });
        };
    });
    

    Find closest previous element jQuery

    see http://api.jquery.com/prev/

    var link = $("#me").parent("div").prev("h3").find("b");
    alert(link.text());
    

    see http://jsfiddle.net/gBwLq/

    Wheel file installation

    You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

    For this to work, you do need to install the wheel package:

    pip install wheel
    

    You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

    pip install project_name  # discover, download and install
    pip install wheel_file.whl  # directly install the wheel
    

    The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

    python -m wheel install wheel_file.whl
    

    Also see the wheel project documentation.

    Java Generate Random Number Between Two Given Values

    Use Random.nextInt(int).

    In your case it would look something like this:

    a[i][j] = r.nextInt(101);
    

    How to print a stack trace in Node.js?

    For what I know printing the complete stack trace in nodejs is not possible, you can just print a "partial" stack trace, you can not see from where you came from in the code, just where the Exception occur. That's what Ryan Dahl explains in this youtube video. http://youtu.be/jo_B4LTHi3I at min 56:30 for being precise. Hope this helps

    Ways to eliminate switch in code

    I think that what you are looking for is the Strategy Pattern.

    This can be implemented in a number of ways, which have been mentionned in other answers to this question, such as:

    • A map of values -> functions
    • Polymorphism. (the sub-type of an object will decide how it handles a specific process).
    • First class functions.

    extract digits in a simple way from a python string

    If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).

    def unit_value(str):
        m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
        if m:
            g = m.groups()
            return ' '.join((g[0], g[2])).strip(), float(g[1])
        else:
            return int(str)
    

    PHP multiline string with PHP

    You don't need to output php tags:

    <?php 
        if ( has_post_thumbnail() ) 
        {
            echo '<div class="gridly-image"><a href="'. the_permalink() .'">'. the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )) .'</a></div>';
        }
    
        echo '<div class="date">
                  <span class="day">'. the_time('d') .'</span>
                  <div class="holder">
                    <span class="month">'. the_time('M') .'</span>
                    <span class="year">'. the_time('Y') .'</span>
                  </div>
              </div>';
    ?>
    

    Difference between numpy dot() and Python 3.5+ matrix multiplication @

    The @ operator calls the array's __matmul__ method, not dot. This method is also present in the API as the function np.matmul.

    >>> a = np.random.rand(8,13,13)
    >>> b = np.random.rand(8,13,13)
    >>> np.matmul(a, b).shape
    (8, 13, 13)
    

    From the documentation:

    matmul differs from dot in two important ways.

    • Multiplication by scalars is not allowed.
    • Stacks of matrices are broadcast together as if the matrices were elements.

    The last point makes it clear that dot and matmul methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:

    For matmul:

    If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

    For np.dot:

    For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

    How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

    // The answer that I was looking for when searching
    public void Answer()
    {
        IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
        // Assign to empty list so we can use later
        IEnumerable<YourClass> second = new List<YourClass>();
    
        if (IwantToUseSecondList)
        {
            second = this.GetSecondIEnumerableList();  
        }
        IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
    }
    

    phpmailer error "Could not instantiate mail function"

    Try using SMTP to send email:-

    $mail->IsSMTP();
    $mail->Host = "smtp.example.com";
    
    // optional
    // used only when SMTP requires authentication  
    $mail->SMTPAuth = true;
    $mail->Username = 'smtp_username';
    $mail->Password = 'smtp_password';
    

    How to link to a named anchor in Multimarkdown?

    The best way to create internal links (related with sections) is create list but instead of link, put #section or #section-title if the header includes spaces.

    Markdown

    Go to section
    * [Hello](#hello)  
    * [Hello World](#hello-world)
    * [Another section](#new-section) <-- it's called 'Another section' in this list but refers to 'New section'
    
    
    ## Hello
    ### Hello World
    ## New section
    

    List preview

    Go to section
    Hello           <-- [Hello](#hello)                 -- go to `Hello` section
    Hello World     <-- [Hello World](#hello world)     -- go to `Hello World` section
    Another section <-- [Another section](#new-section) -- go to `New section`
    

    HTML

    <p>Go to section</p>
    <ul>
        <li><a href="#hello">Hello</a></li>
        <li><a href="#hello-world">Hello World</a></li>
        <li><a href="#new-section">Another section</a> &lt;– it’s called ‘Another section’ in this list but refers to ‘New section’</li>
    </ul>
    <h2 id="hello">Hello</h2>
    <h3 id="hello-world">Hello World</h3>
    <h2 id="new-section">New section</h2>
    

    It doesn't matter whether it's h1, h2, h3, etc. header, you always refer to it using just one #.
    All references in section list should be converted to lowercase text as it is shown in the example above.

    The link to the section should be lowercase. It won't work otherwise. This technique works very well for all Markdown variants, also MultiMarkdown.

    Currently I'm using the Pandoc to convert documents format. It's much better than MultiMarkdown.
    Test Pandoc here

    How can I use an ES6 import in Node.js?

    Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.

    TLDR;

    Node.js >= v13

    It's very simple in Node.js 13 and above. You need to either:

    • Save the file with .mjs extension, or
    • Add { "type": "module" } in the nearest package.json.

    You only need to do one of the above to be able to use ECMAScript modules.

    Node.js <= v12

    If you are using Node.js version 8-12, save the file with ES6 modules with .mjs extension and run it like:

    node --experimental-modules my-app.mjs
    

    Knockout validation

    Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

    Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

    Android SQLite SELECT Query

    Try trimming the string to make sure there is no extra white space:

    Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
    

    Also use c.moveToFirst() like @thinksteep mentioned.


    This is a complete code for select statements.

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
    if (c.moveToFirst()){
        do {
            // Passing values 
            String column1 = c.getString(0);
            String column2 = c.getString(1);
            String column3 = c.getString(2); 
            // Do something Here with values
        } while(c.moveToNext());
    }
    c.close();
    db.close();
    

    ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

    When trying to set up a .NET Core 1.0 website I got this error, and tried everything else I could find with no luck, including checking the web.config file, IIS_IUSRS permissions, IIS URL rewrite module, etc. In the end, I installed DotNetCore.1.0.0-WindowsHosting.exe from this page: https://www.microsoft.com/net/download and it started working right away.

    Specific link to download: https://go.microsoft.com/fwlink/?LinkId=817246

    How to remove all elements in String array in java?

    example = new String[example.length];
    

    If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

    How to use group by with union in t-sql

    Identifying the column is easy:

    SELECT  *
    FROM    ( SELECT    id,
                        time
              FROM      dbo.a
              UNION
              SELECT    id,
                        time
              FROM      dbo.b
            )
    GROUP BY id
    

    But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION rather than UNION ALL, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).

    So, for example, change the first line to SELECT id, MAX(time) or the like!

    How to read specific lines from a file (by line number)?

    If you don't mind importing then fileinput does exactly what you need (this is you can read the line number of the current line)

    How to get index in Handlebars each helper?

    I know this is too late. But i solved this issue with following Code:

    Java Script:

    Handlebars.registerHelper('eachData', function(context, options) {
          var fn = options.fn, inverse = options.inverse, ctx;
          var ret = "";
    
          if(context && context.length > 0) {
            for(var i=0, j=context.length; i<j; i++) {
              ctx = Object.create(context[i]);
              ctx.index = i;
              ret = ret + fn(ctx);
            }
          } else {
            ret = inverse(this);
          }
          return ret;
    }); 
    

    HTML:

    {{#eachData items}}
     {{index}} // You got here start with 0 index
    {{/eachData}}
    

    if you want start your index with 1 you should do following code:

    Javascript:

    Handlebars.registerHelper('eachData', function(context, options) {
          var fn = options.fn, inverse = options.inverse, ctx;
          var ret = "";
    
          if(context && context.length > 0) {
            for(var i=0, j=context.length; i<j; i++) {
              ctx = Object.create(context[i]);
              ctx.index = i;
              ret = ret + fn(ctx);
            }
          } else {
            ret = inverse(this);
          }
          return ret;
        }); 
    
    Handlebars.registerHelper("math", function(lvalue, operator, rvalue, options) {
        lvalue = parseFloat(lvalue);
        rvalue = parseFloat(rvalue);
    
        return {
            "+": lvalue + rvalue
        }[operator];
    });
    

    HTML:

    {{#eachData items}}
         {{math index "+" 1}} // You got here start with 1 index
     {{/eachData}}
    

    Thanks.

    Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

    Old answer (applicable till 2016)

    Here's an Apple developer link that explicitly says that -

    on iPhone and iPod touch, which are small screen devices, "Video is NOT presented within the Web Page"

    Safari Device-Specific Considerations

    Your options:

    • The webkit-playsinline attribute works for HTML5 videos on iOS but only when you save the webpage to your home screen as a webapp - Not if opened a page in Safari
    • For a native app with a WebView (or a hybrid app with HTML, CSS, JS) the UIWebView allows to play the video inline, but only if you set the allowsInlineMediaPlayback property for the UIWebView class to true

    Git Clone: Just the files, please?

    git archive --format=tar --remote=<repository URL> HEAD | tar xf -
    

    taken from here

    Git update submodules recursively

    As it may happens that the default branch of your submodules are not master (which happens a lot in my case), this is how I automate the full Git submodules upgrades:

    git submodule init
    git submodule update
    git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'
    

    How to output a multiline string in Bash?

    Use the -e argument and the escape character \n:

    echo -e "This will generate a next line \nThis new line is the result"
    

    Apache2: 'AH01630: client denied by server configuration'

    Ensure that any user-specific configs are included!

    If none of the other answers on this page for you work, here's what I ran into after hours of floundering around.

    I used user-specific configurations, with Sites specified as my UserDir in /private/etc/apache2/extra/httpd-userdir.conf. However, I was forbidden access to the endpoint http://localhost/~jwork/.

    I could see in /var/log/apache2/error_log that access to /Users/jwork/Sites/ was being blocked. However, I was permitted to access the DocumentRoot, via http://localhost/. This suggested that I didn't have rights to view the ~jwork user. But as far as I could tell by ps aux | egrep '(apache|httpd)' and lsof -i :80, Apache was running for the jwork user, so something was clearly not write with my user configuration.

    Given a user named jwork, here was my config file:

    /private/etc/apache2/users/jwork.conf

    <Directory "/Users/jwork/Sites/">
        Require all granted
    </Directory>
    

    This config is perfectly valid. However, I found that my user config wasn't being included:

    /private/etc/apache2/extra/httpd-userdir.conf

    ## Note how it's commented out by default.
    ## Just remove the comment to enable your user conf.
    #Include /private/etc/apache2/users/*.conf
    

    Note that this is the default path to the userdir conf file, but as you'll see below, it's configurable in httpd.conf. Ensure that the following lines are enabled:

    /private/etc/apache2/httpd.conf

    Include /private/etc/apache2/extra/httpd-userdir.conf
    
    # ...
    
    LoadModule userdir_module libexec/apache2/mod_userdir.so
    

    Alternate output format for psql

    Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.

    How can I get the current time in C#?

    DateTime.Now.ToString("HH:mm:ss tt");
    

    this gives it to you as a string.

    uncaught syntaxerror unexpected token U JSON

    I was getting this error, when I was using the same variable for json string and parsed json:

    var json = '{"1":{"url":"somesite1","poster":"1.png","title":"site title"},"2":{"url":"somesite2","poster":"2.jpg","title":"site 2 title"}}'
    
    function usingjson(){
        var json = JSON.parse(json);
    }
    

    I changed function to:

    function usingjson(){
        var j = JSON.parse(json);
    }
    

    Now this error went away.

    Timing Delays in VBA

    With Due credits and thanks to Steve Mallroy.

    I had midnight issues in Word and the below code worked for me

    Public Function Pause(NumberOfSeconds As Variant)
     '   On Error GoTo Error_GoTo
    
        Dim PauseTime, Start
        Dim objWord As Word.Document
    
        'PauseTime = 10 ' Set duration in seconds
        PauseTime = NumberOfSeconds
        Start = Timer ' Set start time.
    
        If Start + PauseTime > 86399 Then 'playing safe hence 86399
    
        Start = 0
    
        Do While Timer > 1
            DoEvents ' Yield to other processes.
        Loop
    
        End If
    
        Do While Timer < Start + PauseTime
            DoEvents ' Yield to other processes.
        Loop
    
    End Function
    

    What's the safest way to iterate through the keys of a Perl hash?

    Using the each syntax will prevent the entire set of keys from being generated at once. This can be important if you're using a tie-ed hash to a database with millions of rows. You don't want to generate the entire list of keys all at once and exhaust your physical memory. In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.

    So, the only place "each" is of real use is when the hash is very large (compared to the memory available). That is only likely to happen when the hash itself doesn't live in memory itself unless you're programming a handheld data collection device or something with small memory.

    If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.

    how to fire event on file select

    This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses jquery:

    //the HTML
    <input type="file" id="file" name="file" />
    
    
    
    //the JavaScript
    
    /*resets the value to address navigating away from the page 
    and choosing to upload the same file */ 
    
    $('#file').on('click touchstart' , function(){
        $(this).val('');
    });
    
    
    //Trigger now when you have selected any file 
    $("#file").change(function(e) {
        //do whatever you want here
    });