Programs & Examples On #Owasp

The Open Web Application Security Project (OWASP) is an organization that wants to inform people about application security. Website at http://owasp.org.

Why is it common to put CSRF prevention tokens in cookies?

My best guess as to the answer: Consider these 3 options for how to get the CSRF token down from the server to the browser.

  1. In the request body (not an HTTP header).
  2. In a custom HTTP header, not Set-Cookie.
  3. As a cookie, in a Set-Cookie header.

I think the 1st one, request body (while demonstrated by the Express tutorial I linked in the question), is not as portable to a wide variety of situations; not everyone is generating every HTTP response dynamically; where you end up needing to put the token in the generated response might vary widely (in a hidden form input; in a fragment of JS code or a variable accessible by other JS code; maybe even in a URL though that seems generally a bad place to put CSRF tokens). So while workable with some customization, #1 is a hard place to do a one-size-fits-all approach.

The second one, custom header, is attractive but doesn't actually work, because while JS can get the headers for an XHR it invoked, it can't get the headers for the page it loaded from.

That leaves the third one, a cookie carried by a Set-Cookie header, as an approach that is easy to use in all situations (anyone's server will be able to set per-request cookie headers, and it doesn't matter what kind of data is in the request body). So despite its downsides, it was the easiest method for frameworks to implement widely.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

As Mike has noted below, HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

What is "X-Content-Type-Options=nosniff"?

It prevents the browser from doing MIME-type sniffing. Most browsers are now respecting this header, including Chrome/Chromium, Edge, IE >= 8.0, Firefox >= 50 and Opera >= 13. See :

https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx?Redirected=true

Sending the new X-Content-Type-Options response header with the value nosniff will prevent Internet Explorer from MIME-sniffing a response away from the declared content-type.

EDIT:

Oh and, that's an HTTP header, not a HTML meta tag option.

See also : http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx

How to reload the datatable(jquery) data?

// Get the url from the Settings of the table: oSettings.sAjaxSource

function refreshTable(oTable) {
    table = oTable.dataTable();
    oSettings = table.fnSettings();

    //Retrieve the new data with $.getJSON. You could use it ajax too
    $.getJSON(oSettings.sAjaxSource, null, function( json ) {
        table.fnClearTable(this);

        for (var i=0; i<json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}

PDO mysql: How to know if insert was successful

If an update query executes with values that match the current database record then $stmt->rowCount() will return 0 for no rows were affected. If you have an if( rowCount() == 1 ) to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.

$stmt->execute();
if( $stmt ) return "success";

This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.

filtering NSArray into a new NSArray in Objective-C

There are loads of ways to do this, but by far the neatest is surely using [NSPredicate predicateWithBlock:]:

NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
    return [object shouldIKeepYou];  // Return YES for each object you want in filteredArray.
}]];

I think that's about as concise as it gets.


Swift:

For those working with NSArrays in Swift, you may prefer this even more concise version:

let filteredArray = array.filter { $0.shouldIKeepYou() }

filter is just a method on Array (NSArray is implicitly bridged to Swift’s Array). It takes one argument: a closure that takes one object in the array and returns a Bool. In your closure, just return true for any objects you want in the filtered array.

What is cardinality in Databases?

A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.

In data modelling terms, cardinality is how one table relates to another.

  • 1-1 (one row in table A relates to one row in tableB)
  • 1-Many (one row in table A relates to many rows in tableB)
  • Many-Many (Many rows in table A relate to many rows in tableB)

There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).

See Wikipedia on Cardinality (data modelling).


When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.

See Wikipedia on Cardinality (SQL statements).

How do you check that a number is NaN in JavaScript?

I use underscore's isNaN function because in JavaScript:

isNaN(undefined) 
-> true

At the least, be aware of that gotcha.

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Get checkbox values using checkbox name using jquery

$('[name="CheckboxName"]:checked').each(function () {
    // do stuff
});

Send email using java

The short answer - No.

The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.

Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain gmail.com, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.

If you read the JavaMail FAQ on using JavaMail to accessing GMail, you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.

You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the Wikipedia article on SMTP, but any further progress will actually necessitate programming against a SMTP server.

How to align text below an image in CSS?

Best way is to wrap the Image and Paragraph text with a DIV and assign a class.

Example:

<div class="image1">
    <div class="imgWrapper">
        <img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
        <p>It's my first Image</p>
    </div>
    ...
    ...
    ...
    ...
</div>

Scripting SQL Server permissions

Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:

SELECT
  CASE
      WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'DATABASE' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'SCHEMA' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'TYPE' THEN
        dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS + 
        ' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
            + ' TO [' + dpr.name + ']'
      WHEN dp.class_desc = 'CERTIFICATE' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']' 
      WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
      ' TO ' + '[' + dpr.name + ']' 
      ELSE 
        'ERROR: Unhandled class_desc: ' + dp.class_desc
  END
 AS GRANT_STMT
FROM sys.database_permissions AS dp 
  JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
  LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
  LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE 
dpr.name NOT IN ('public','guest') 
--  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
--  AND (o.name NOT IN ('My_Procedure') or o.name is null)  -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
--  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
--  AND dpr.name LIKE '%user_name%'     -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name

Python: Converting from ISO-8859-1/latin1 to UTF-8

For Python 3:

bytes(apple,'iso-8859-1').decode('utf-8')

I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.

Explain the concept of a stack frame in a nutshell

Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.

There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.

Moving up one directory in Python

Use the os module:

import os
os.chdir('..')

should work

Getting "type or namespace name could not be found" but everything seems ok?

You might also try eliminating the code you think you're having problems with and seeing if it compiles with no references to that code. If not, fix things until it compiles again, and then work your suspected problem code back in. Sometimes I get strange errors about classes or methods that I know are correct when the compiler doesn't like something else. Once I fix the thing that it's really getting hung up on, these 'phantom' errors disappear.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

What does OpenCV's cvWaitKey( ) function do?

cvWaitKey(x) / cv::waitKey(x) does two things:

  1. It waits for x milliseconds for a key press on a OpenCV window (i.e. created from cv::imshow()). Note that it does not listen on stdin for console input. If a key was pressed during that time, it returns the key's ASCII code. Otherwise, it returns -1. (If x is zero, it waits indefinitely for the key press.)
  2. It handles any windowing events, such as creating windows with cv::namedWindow(), or showing images with cv::imshow().

A common mistake for opencv newcomers is to call cv::imshow() in a loop through video frames, without following up each draw with cv::waitKey(30). In this case, nothing appears on screen, because highgui is never given time to process the draw requests from cv::imshow().

Laravel Check If Related Model Exists

As Hemerson Varela already said in Php 7.1 count(null) will throw an error and hasOne returns null if no row exists. Since you have a hasOnerelation I would use the empty method to check:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
   $option = $model->option;

   if(empty($option)){
      $option = $model->option()->create();
   }

   $option->someAttribute = temp;
   $option->save();
};

But this is superfluous. There is no need to check if the relation exists, to determine if you should do an update or a create call. Simply use the updateOrCreate method. This is equivalent to the above:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {  
   $model->option()
         ->updateOrCreate(['repair_item_id' => $model->id],
                          ['option' => $temp]);
}

How to find the most recent file in a directory using .NET, and without looping?

A non-LINQ version:

/// <summary>
/// Returns latest writen file from the specified directory.
/// If the directory does not exist or doesn't contain any file, DateTime.MinValue is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static DateTime GetLatestWriteTimeFromFileInDirectory(DirectoryInfo directoryInfo)
{
    if (directoryInfo == null || !directoryInfo.Exists)
        return DateTime.MinValue;

    FileInfo[] files = directoryInfo.GetFiles();
    DateTime lastWrite = DateTime.MinValue;

    foreach (FileInfo file in files)
    {
        if (file.LastWriteTime > lastWrite)
        {
            lastWrite = file.LastWriteTime;
        }
    }

    return lastWrite;
}

/// <summary>
/// Returns file's latest writen timestamp from the specified directory.
/// If the directory does not exist or doesn't contain any file, null is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <returns></returns>
private static FileInfo GetLatestWritenFileFileInDirectory(DirectoryInfo directoryInfo)
{
    if (directoryInfo == null || !directoryInfo.Exists)
        return null;

    FileInfo[] files = directoryInfo.GetFiles();
    DateTime lastWrite = DateTime.MinValue;
    FileInfo lastWritenFile = null;

    foreach (FileInfo file in files)
    {
        if (file.LastWriteTime > lastWrite)
        {
            lastWrite = file.LastWriteTime;
            lastWritenFile = file;
        }
    }
    return lastWritenFile;
}

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

The first answer covers it.

Im guessing that somewhere down the line you may decide to store your info in a different class/structure. In that case you probably wouldn't want the results going in to an array from the split() method.

You didn't ask for it, but I'm bored, so here is an example, hope it's helpful.

This might be the class you write to represent a single person:


class Person {
            public String firstName;
            public String lastName;
            public int id;
            public int age;

      public Person(String firstName, String lastName, int id, int age) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.id = id;
         this.age = age;
      }  
      // Add 'get' and 'set' method if you want to make the attributes private rather than public.
} 

Then, the version of the parsing code you originally posted would look something like this: (This stores them in a LinkedList, you could use something else like a Hashtable, etc..)


try 
{
    String ruta="entrada.al";
    BufferedReader reader = new BufferedReader(new FileReader(ruta));

    LinkedList<Person> list = new LinkedList<Person>();

    String line = null;         
    while ((line=reader.readLine())!=null)
    {
        if (!(line.equals("%")))
        {
            StringTokenizer st = new StringTokenizer(line, "*");
            if (st.countTokens() == 4)          
                list.add(new Person(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken)));         
            else            
                // whatever you want to do to account for an invalid entry
                  // in your file. (not 4 '*' delimiters on a line). Or you
                  // could write the 'if' clause differently to account for it          
        }
    }
    reader.close();
}

How to set TLS version on apache HttpClient

If you have a javax.net.ssl.SSLSocket class reference in your code, you can set the enabled TLS protocols by a call to SSLSocket.setEnabledProtocols():

import javax.net.ssl.*;
import java.net.*; 
...
Socket socket = SSLSocketFactory.getDefault().createSocket();
...
if (socket instanceof SSLSocket) {
   // "TLSv1.0" gives IllegalArgumentException in Java 8
   String[] protos = {"TLSv1.2", "TLSv1.1"}
   ((SSLSocket)socket).setEnabledProtocols(protos);
}

Qt Creator color scheme

I found some trick for your problem! Here you can see it: Habrahabr -- Redesigning Qt Creator by your hands (russian lang.)

According to that article, that trick is kind of not so dirty, but "hack" (probably it wouldn't harm your system, but it can leave some artifacts on your interface).

You don't need to patch something (there is possibility, but I don't recommend).

Main idea is to use stylesheet like this stylesheet.css:

// on Linux
qtcreator -stylesheet='.qt-stylesheet.css' 
// on Windows
[pathToQt]\QtCreator\bin\qtcreator.exe -stylesheet [pathToStyleSheet]

To get such effect: QtCreator before and after

To customize by your needs, you may need to read documentation: Qt Style Sheets Reference, Qt Style Sheets Examples and so on.

This wiki page is dedicated to custom Qt Creator styling.

P.S. If you'll got better stylesheet, share it, I'll be happy! :)


UPD (10.12.2014): Hopefully, now we can close this topic. Thanks, Simon G., Things have changed once again. Users may use custom themes since QtCreator 3.3. So hacky stylesheets are no longer needed.

Everyone can take a look at todays update: Qt 5.4 released. There you can find information that Qt 5.4, also comes with a brand new version of Qt Creator 3.3. Just take a look at official video at Youtube.

So, to apply dark theme you need go to "Tools" -> "Options" -> "Environment" -> "General" tab, and there you need to change "Theme".

See more information about its configuring here: Configuring Qt Creator.

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

Gradle, Android and the ANDROID_HOME SDK location

i encountered the same error but in my case i was cloning a project, the cloned project was built with Android API 22 which i did not install at the time(i had API 24 and 25 installed)........so i had to download the sdk tools for API 22

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Returning a stream from File.OpenRead()

Try changing your code to this:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());

    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

How do I print the type or class of a variable in Swift?

let i: Int = 20


  func getTypeName(v: Any) -> String {
    let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
    if let range = fullName.rangeOfString(".") {
        return fullName.substringFromIndex(range.endIndex)
    }
    return fullName
}

println("Var type is \(getTypeName(i)) = \(i)")

get string value from HashMap depending on key name

If you are storing keys/values as strings, then this will work:

HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("my_code", "shhh_secret");
String value = newMap.get("my_code");

The question is what gets populated in the HashMap (key & value)

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

The answer is no.

The main purpose of the hash is to scroll to a certain part of the page where you have defined a bookmark. e.g. Scroll to this Part when page loads.

The browse will scroll such that this line is the first visible content in the page, depending on how much content follows below the line.

Yes javascript can acces it, and then a simple ajax call will do the magic

Is there a free GUI management tool for Oracle Database Express?

Try odbTools at http://odbtools.software.informer.com - it is free.

odbTools is set of integrated GUI tools to manage, administer, monitor and tune the Oracle database.

How to square all the values in a vector in R?

This will also work

newData <- data*data

Can a foreign key be NULL and/or duplicate?

Short answer: Yes, it can be NULL or duplicate.

I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.

Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.

Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.

Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.

CSS getting text in one line rather than two

Add white-space: nowrap;:

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

jsFiddle

How can I show the table structure in SQL Server query?

sp_help tablename in sql server

desc tablename in oracle

What is the Java ?: operator called and what does it do?

It's the conditional operator, and it's more than just a concise way of writing if statements.

Since it is an expression that returns a value it can be used as part of other expressions.

Remove "whitespace" between div element

Although probably not the best method you could add:

#div1 {
    ...
    font-size:0;
}

What is a predicate in c#?

The Predicate will always return a boolean, by definition.

Predicate<T> is basically identical to Func<T,bool>.

Predicates are very useful in programming. They are often used to allow you to provide logic at runtime, that can be as simple or as complicated as necessary.

For example, WPF uses a Predicate<T> as input for Filtering of a ListView's ICollectionView. This lets you write logic that can return a boolean determining whether a specific element should be included in the final view. The logic can be very simple (just return a boolean on the object) or very complex, all up to you.

How do I find out what version of Sybase is running

There are two ways to know the about Sybase version,

1) Using this System procedure to get the information about Sybase version

> sp_version
> go

2) Using this command to get Sybase version

> select @@version
> go

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

Remove part of string in Java

Using StringBuilder, you can replace the following way.

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");

How to do a GitHub pull request

In order to make a pull request you need to do the following steps:

  1. Fork a repository (to which you want to make a pull request). Just click the fork button the the repository page and you will have a separate github repository preceded with your github username.
  2. Clone the repository to your local machine. The Github software that you installed on your local machine can do this for you. Click the clone button beside the repository name.
  3. Make local changes/commits to the files
  4. sync the changes
  5. go to your github forked repository and click the "Compare & Review" green button besides the branch button. (The button has icon - no text)
  6. A new page will open showing your changes and then click the pull request link, that will send the request to the original owner of the repository you forked.

It took me a while to figure this, hope this will help someone.

Use 'import module' or 'from module import'?

My own answer to this depends mostly on first, how many different modules I'll be using. If i'm only going to use one or two, I'll often use from ... import since it makes for fewer keystrokes in the rest of the file, but if I'm going to make use of many different modules, I prefer just import because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.

Usuaully I prefer the self documenting style of plain import and only change to from.. import when the number of times I have to type the module name grows above 10 to 20, even if there's only one module being imported.

Animate scroll to ID on page load

There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check this link.

In your case the code is

$("#title1").animatedScroll({easing: "easeOutExpo"});

show loading icon until the page is load?

firstly, in your main page use a loading icon

then, delete your </body> and </HTML> from your main page and replace it by

<?php include('footer.php');?>

in the footer.php file type :

<?php
    $iconPath="myIcon.ico" // myIcon is the final icon
    echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
    echo '</body>';
    echo '</HTML>';
?>

How to Generate unique file names in C#

If readability doesn't matter, use GUIDs.

E.g.:

var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());

or shorter:

var myUniqueFileName = $@"{Guid.NewGuid()}.txt";

In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png"…"Image10.png") and if that fails (because the file already exists), I fall back to GUIDs.

Update:

Recently, I've also use DateTime.Now.Ticks instead of GUIDs:

var myUniqueFileName = string.Format(@"{0}.txt", DateTime.Now.Ticks);

or

var myUniqueFileName = $@"{DateTime.Now.Ticks}.txt";

The benefit to me is that this generates a shorter and "nicer looking" filename, compared to GUIDs.

Please note that in some cases (e.g. when generating a lot of random names in a very short time), this might make non-unique values.

Stick to GUIDs if you want to make really sure that the file names are unique, even when transfering them to other computers.

What is a Python egg?

"Egg" is a single-file importable distribution format for Python-related projects.

"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."

Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

From $album->getTrackList() you will alwas get "AlbumTrackReference" entities back, so what about adding methods from the Track and proxy?

class AlbumTrackReference
{
    public function getTitle()
    {
        return $this->getTrack()->getTitle();
    }

    public function getDuration()
    {
        return $this->getTrack()->getDuration();
    }
}

This way your loop simplifies considerably, aswell as all other code related to looping the tracks of an album, since all methods are just proxied inside AlbumTrakcReference:

foreach ($album->getTracklist() as $track) {
    echo sprintf("\t#%d - %-20s (%s) %s\n", 
        $track->getPosition(),
        $track->getTitle(),
        $track->getDuration()->format('H:i:s'),
        $track->isPromoted() ? ' - PROMOTED!' : ''
    );
}

Btw You should rename the AlbumTrackReference (for example "AlbumTrack"). It is clearly not only a reference, but contains additional logic. Since there are probably also Tracks that are not connected to an album but just available through a promo-cd or something this allows for a cleaner separation also.

Is there such a thing as min-font-size and max-font-size?

This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

What is the difference between a URI, a URL and a URN?

Another example I like to use when thinking about URIs is the xmlns attribute of an XML document:

<rootElement xmlns:myPrefix="com.mycompany.mynode">
    <myPrefix:aNode>some text</myPrefix:aNode>
</rootElement>

In this case com.mycompany.mynode would be a URI that uniquely identifies the "myPrefix" namespace for all of the elements that use it within my XML document. This is NOT a URL because it is only used to identify, not to locate something per se.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

1- close the project

2- close Android Studio IDE

3- delete the .idea directory

4- delete all .iml files

5- open Android Studio IDE and import the project

How can I simulate an anchor click via jquery?

Do you need to fake an anchor click? From the thickbox site:

ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

Edit:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

How to Install gcc 5.3 with yum on CentOS 7.2?

You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.

sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;

Display exact matches only with grep

Try the below command, because it works perfectly:

grep -ow "yourstring"

crosscheck:-

Remove the instance of word from file, then re-execute this command and it should display empty result.

grid controls for ASP.NET MVC?

You can use also the Insert/update/delete datagrid of my MVC Controls Toolkit available here on codeplex: http://mvccontrolstoolkit.codeplex.com/. Here you can download a complete example, here the datagrid working and here and here tutorials. The DataGrid works completely client side and mantains thechange set between posts. Yes it mantains Changeset, this means, you can access both old version and modified version of each record to see what changes to pass to the DB(what need to be modified deleted or inserted). This Changeset is mantained after several posts till you either confirm or cancel the modifications on the server side.

how does Request.QueryString work?

Request.QueryString["pID"];

Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.

READ MORE@ http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

How can I map True/False to 1/0 in a Pandas DataFrame?

I had to map FAKE/REAL to 0/1 but couldn't find proper answer.

Please find below how to map column name 'type' which has values FAKE/REAL to 0/1
(Note: similar can be applied to any column name and values)

df.loc[df['type'] == 'FAKE', 'type'] = 0
df.loc[df['type'] == 'REAL', 'type'] = 1

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

check out distributionUrl setting in gradle-wrapper.properties. I changed https to http, then my problem was solved.

WSDL validator?

If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.

Cloning an array in Javascript/Typescript

It looks like you may have made a mistake as to where you are doing the copy of an Array. Have a look at my explanation below and a slight modification to the code which should work in helping you reset the data to its previous state.

In your example i can see the following taking place:

  • you are doing a request to get generic items
  • after you get the data you set the results to the this.genericItems
  • directly after that you set the backupData as the result

Am i right in thinking you don't want the 3rd point to happen in that order?

Would this be better:

  • you do the data request
  • make a backup copy of what is current in this.genericItems
  • then set genericItems as the result of your request

Try this:

getGenericItems(selected: Item) {
  this.itemService.getGenericItems(selected).subscribe(
    result => {
       // make a backup before you change the genericItems
       this.backupData = this.genericItems.slice();

       // now update genericItems with the results from your request
       this.genericItems = result;
    });
  }

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

How can I get javascript to read from a .json file?

Assuming you mean "file on a local filesystem" when you say .json file.

You'll need to save the json data formatted as jsonp, and use a file:// url to access it.

Your HTML will look like this:

<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var activity=jsonstr;
    foreach (i in activity) {
        date = document.getElementById(i.date).innerHTML = activity.date;
        event = document.getElementById(i.event).innerHTML = activity.event;
    }
  }
</script>

And the file c:\data\activity.jsonp contains the following line:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];

How to trigger Jenkins builds remotely and to pass parameters

To add to this question, I found out that you don't have to use the /buildWithParameters endpoint.

In my scenario, I have a script that triggers Jenkins to run tests after a deployment. Some of these tests require extra info about the deployment to work correctly.

If I tried to use /buildWithParameters on a job that does not expect parameters, the job would not run. I don't want to go in and edit every job to require fake parameters just to get the jobs to run.

Instead, I found you can pass parameters like this:

curl -X POST --data-urlencode "token=${TOKEN}" --data-urlencode json='{"parameter": [{"name": "myParam", "value": "TEST"}]}' https://jenkins.corp/job/$JENKINS_JOB/build

With this json=... it will pass the param myParam with value TEST to the job whenever the call is made. However, the Jenkins job will still run even if it is not expecting the parameter myParam.

The only scenario this does not cover is if the job has a parameter that is NOT passed in the json. Even if the job has a default value set for the parameter, it will fail to run the job. In this scenario you will run into the following error message / stack trace when you call /build:

java.lang.IllegalArgumentException: No such parameter definition: myParam

I realize that this answer is several years late, but I hope this may be useful info for someone else!

Note: I am using Jenkins v2.163

How-to turn off all SSL checks for postman for a specific site

There is an option in Postman if you download it from https://www.getpostman.com instead of the chrome store (most probably it has been introduced in the new versions and the chrome one will be updated later) not sure about the old ones.

In the settings, turn off the SSL certificate verification option enter image description here

Be sure to remember to reactivate it afterwards, this is a security feature.

If you really want to use the chrome app, you could always add an exception to chrome for the url: Enter the url you would like to open in the chrome browser, you'll get a warning with a link at the bottom of the page to add an exception, which if you do, it will also allow postman to access your url. But the first option of using the postman stand-alone app is much better.

I hope this can help.

Delete rows with foreign key in PostgreSQL

You can't delete a foreign key if it still references another table. First delete the reference

delete from kontakty
where id_osoby = 1;

DELETE FROM osoby 
WHERE id_osoby = 1;

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

How do I put two increment statements in a C++ 'for' loop?

Try not to do it!

From http://www.research.att.com/~bs/JSF-AV-rules.pdf:

AV Rule 199
The increment expression in a for loop will perform no action other than to change a single loop parameter to the next value for the loop.

Rationale: Readability.

How to work with complex numbers in C?

For convenience, one may include tgmath.h library for the type generate macros. It creates the same function name as the double version for all type of variable. For example, For example, it defines a sqrt() macro that expands to the sqrtf() , sqrt() , or sqrtl() function, depending on the type of argument provided.

So one don't need to remember the corresponding function name for different type of variables!

#include <stdio.h>
#include <tgmath.h>//for the type generate macros. 
#include <complex.h>//for easier declare complex variables and complex unit I

int main(void)
{
    double complex z1=1./4.*M_PI+1./4.*M_PI*I;//M_PI is just pi=3.1415...
    double complex z2, z3, z4, z5; 

    z2=exp(z1);
    z3=sin(z1);
    z4=sqrt(z1);
    z5=log(z1);

    printf("exp(z1)=%lf + %lf I\n", creal(z2),cimag(z2));
    printf("sin(z1)=%lf + %lf I\n", creal(z3),cimag(z3));
    printf("sqrt(z1)=%lf + %lf I\n", creal(z4),cimag(z4));
    printf("log(z1)=%lf + %lf I\n", creal(z5),cimag(z5));

    return 0;
}

Using Regular Expressions to Extract a Value in Java

Sometimes you can use simple .split("REGEXP") method available in java.lang.String. For example:

String input = "first,second,third";

//To retrieve 'first' 
input.split(",")[0] 
//second
input.split(",")[1]
//third
input.split(",")[2]

What happens if you don't commit a transaction to a database (say, SQL Server)?

As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks.

If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.

PuTTY scripting to log onto host

entering a command after you logged in can be done by going through SSH section at the bottom of putty and you should have an option Remote command (data to send to the server) separate the two commands with ;

Text size and different android screen sizes

You can also use weightSum and layout_weight property to adjust your different screen.

For that, you have to make android:layout_width = 0dp, and android:layout_width = (whatever you want);

How to concatenate text from multiple rows into a single text string in SQL server?

SELECT PageContent = Stuff(
    (   SELECT PageContent
        FROM dbo.InfoGuide
        WHERE CategoryId = @CategoryId
          AND SubCategoryId = @SubCategoryId
        for xml path(''), type
    ).value('.[1]','nvarchar(max)'),
    1, 1, '')
FROM dbo.InfoGuide info

How to edit binary file on Unix systems

For small changes, I have used hexedit:

http://rigaux.org/hexedit.html

Simple but fast and useful.

JAVA_HOME should point to a JDK not a JRE

Windows 10 Home for me:

I'm studying maven through a udemy course. First time environment variables were ok. I had on JAVA_HOME on SYSTEM VARIABLE like this:

D:\Install\Java\jdk-12.0.1;D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4

After some days, don't know what's happened, I began to receive:

C:\Users\Franco>mvn -version

The JAVA_HOME environment variable is not defined correctly

This environment variable is needed to run this program

NB: JAVA_HOME should point to a JDK not a JRE

After trying all above, I tried to delete jdk the entry on SYSTEM VARIABLES, and putting it on USER VARIABLES, so now I have:

JAVA_HOME on USER VARIABLES: D:\Install\Java\jdk-12.0.1

JAVA_HOME on SYSTEM VARIABLES: D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4

now restarting CMD I have:

C:\Users\Franco>mvn -version

Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)

Maven home: D:\Install\apache-maven-3.5.4-bin\apache-maven-3.5.4\bin\..

Java version: 12.0.1, vendor: Oracle Corporation, runtime: D:\Install\Java\jdk-12.0.1

Default locale: en_US, platform encoding: Cp1252

OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

Map over object preserving keys

I managed to find the required function in lodash, a utility library similar to underscore.

http://lodash.com/docs#mapValues

_.mapValues(object, [callback=identity], [thisArg])

Creates an object with the same keys as object and values generated by running each own enumerable property of object through the callback. The callback is bound to thisArg and invoked with three arguments; (value, key, object).

How can I use goto in Javascript?

In classic JavaScript you need to use do-while loops to achieve this type of code. I presume you are maybe generating code for some other thing.

The way to do it, like for backending bytecode to JavaScript is to wrap every label target in a "labelled" do-while.

LABEL1: do {
  x = x + 2;
  ...
  // JUMP TO THE END OF THE DO-WHILE - A FORWARDS GOTO
  if (x < 100) break LABEL1;
  // JUMP TO THE START OF THE DO WHILE - A BACKWARDS GOTO...
  if (x < 100) continue LABEL1;
} while(0);

Every labelled do-while loop you use like this actually creates the two label points for the one label. One at the the top and one at the end of the loop. Jumping back uses continue and jumping forwards uses break.

// NORMAL CODE

MYLOOP:
  DoStuff();
  x = x + 1;
  if (x > 100) goto DONE_LOOP;
  GOTO MYLOOP;


// JAVASCRIPT STYLE
MYLOOP: do {
  DoStuff();
  x = x + 1;
  if (x > 100) break MYLOOP;
  continue MYLOOP;// Not necessary since you can just put do {} while (1) but it     illustrates
} while (0)

Unfortunately there is no other way to do it.

Normal Example Code:

while (x < 10 && Ok) {
  z = 0;
  while (z < 10) {
    if (!DoStuff()) {
      Ok = FALSE;
      break;
    }
    z++;
  }
  x++;
} 

So say the code gets encoded to bytecodes so now you must put the bytecodes into JavaScript to simulate your backend for some purpose.

JavaScript style:

LOOP1: do {
  if (x >= 10) break LOOP1;
  if (!Ok) break LOOP1;
  z = 0;
  LOOP2: do {
    if (z >= 10) break LOOP2;
    if (!DoStuff()) {
      Ok = FALSE;
      break LOOP2;
    }
    z++;
  } while (1);// Note While (1) I can just skip saying continue LOOP2!
  x++;
  continue LOOP1;// Again can skip this line and just say do {} while (1)
} while(0)

So using this technique does the job fine for simple purposes. Other than that not much else you can do.

For normal Javacript you should not need to use goto ever, so you should probably avoid this technique here unless you are specificaly translating other style code to run on JavaScript. I assume that is how they get the Linux kernel to boot in JavaScript for example.

NOTE! This is all naive explanation. For proper Js backend of bytecodes also consider examining the loops before outputting the code. Many simple while loops can be detected as such and then you can rather use loops instead of goto.

In a URL, should spaces be encoded using %20 or +?

When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.

Is Android using NTP to sync time?

I know about Android ICS that it uses a custom service called: NetworkTimeUpdateService. This service also implements a NTP time synchronization via the NtpTrustedTime singleton.

In NtpTrustedTime the default NTP server is requested from the Android system string source:

final Resources res = context.getResources();

final String defaultServer = res.getString(
                                com.android.internal.R.string.config_ntpServer);

If the automatic time sync option in the system settings is checked and no NITZ time service is available then the time will be synchronized with the NTP server from com.android.internal.R.string.config_ntpServer.

To get the value of com.android.internal.R.string.config_ntpServer you can use the following method:

    final Resources res = this.getResources();
    final int id = Resources.getSystem().getIdentifier(
                       "config_ntpServer", "string","android");
    final String defaultServer = res.getString(id);

How to append a date in batch files

There is a tech recipe available here that shows how to format it to MMDDYYYY, you should be able to adapt it for your needs.

echo on
@REM Seamonkey’s quick date batch (MMDDYYYY format)
@REM Setups %date variable
@REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%

echo %date%

EDIT: The reason did not work before was because of 'smartquotes' in the original text. I fixed them and the batch file will work if cut & pasted from this page.

Access nested dictionary items via a list of keys?

a method for concatenating strings:

def get_sub_object_from_path(dict_name, map_list):
    for i in map_list:
        _string = "['%s']" % i
        dict_name += _string
    value = eval(dict_name)
    return value
#Sample:
_dict = {'new': 'person', 'time': {'for': 'one'}}
map_list = ['time', 'for']
print get_sub_object_from_path("_dict",map_list)
#Output:
#one

How to change the status bar background color and text color on iOS 7?

1) set the UIViewControllerBasedStatusBarAppearance to YES in the plist

2) in viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate];

3) add the following method:

 -(UIStatusBarStyle)preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
 } 

UPDATE:
also check developers-guide-to-the-ios-7-status-bar

How to execute cmd commands via Java

Here is a simpler example that does not require multiple threads:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SimplePty
{
    public SimplePty(Process process) throws IOException
    {
        while (process.isAlive())
        {
            sync(process.getErrorStream(), System.err);
            sync(process.getInputStream(), System.out);
            sync(System.in, process.getOutputStream());
        }
    }
    
    private void sync(InputStream in, OutputStream out) throws IOException
    {
        while (in.available() > 0)
        {
            out.write(in.read());
            out.flush();
        }
    }
    
    public static void main( String[] args ) throws IOException
    {
        String os = System.getProperty("os.name").toLowerCase();
        String shell = os.contains("win") ? "cmd" : "bash";
        Process process = new ProcessBuilder(shell).start();
        new SimplePty(process);
    }
}

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

Android Call an method from another class

You should use the following code :

Class2 cls2 = new Class2();
cls2.UpdateEmployee();

In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.UpdateEmployee().

Copy to Clipboard for all Browsers using javascript

For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).

The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.

JSLint says "missing radix parameter"

Just put an empty string in the radix place, because parseInt() take two arguments:

parseInt(string, radix);

string The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.

radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above-mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.

imageIndex = parseInt(id.substring(id.length - 1))-1;
imageIndex = parseInt(id.substring(id.length - 1), '')-1;

How to change the size of the radio button using CSS?

Resizing the default widget doesn’t work in all browsers, but you can make custom radio buttons with JavaScript. One of the ways is to create hidden radio buttons and then place your own images on your page. Clicking on these images changes the images (replaces the clicked image with an image with a radio button in a selected state and replaces the other images with radio buttons in an unselected state) and selects the new radio button.

Anyway, there is documentation on this subject. For example, read this: Styling Checkboxes and Radio Buttons with CSS and JavaScript.

Difference between const reference and normal parameter

The difference is more prominent when you are passing a big struct/class.

struct MyData {
    int a,b,c,d,e,f,g,h;
    long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);

when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

in both cases, the original data cannot be modified from inside the function.

EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

Trigger event on body load complete js/jquery

When the page loads totally (dom, images, ...)

$(window).load(function(){
    // full load
});

When DOM elements load (not necessary all images will be loaded)

$(function(){
    // DOM Ready
});

Then you can trigger any event

$("element").trigger("event");

How to get the last day of the month?

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

Output:

31



This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

So:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

Output:

False

Unless it IS the last day of the month.

How does data binding work in AngularJS?

  1. The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.

  2. Data-binding in Angular apps is the automatic synchronisation of data between the model and view components.

Data binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. If the model is changed, the view reflects the change and vice versa.

Node.js console.log() not logging anything

Using modern --inspect with node the console.log is captured and relayed to the browser.

node --inspect myApp.js

or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...

node --inspect-brk myApp.js

How do I set a textbox's value using an anchor with jQuery?

Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.

How do I generate random integers within a specific range in Java?

public static Random RANDOM = new Random(System.nanoTime());

public static final float random(final float pMin, final float pMax) {
    return pMin + RANDOM.nextFloat() * (pMax - pMin);
}

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

Delete all data in SQL Server database

Usually I will just use the undocumented proc sp_MSForEachTable

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 

EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' 
GO 

-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 
GO

See also: Delete all data in database (when you have FKs)

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

Git add all files modified, deleted, and untracked?

From Git documentation starting from version 2.0:

To add content for the whole tree, run:

git add --all :/

or

git add -A :/

To restrict the command to the current directory, run:

git add --all .

or

git add -A .

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}

Bash Script : what does #!/bin/bash mean?

When the first characters in a script are #!, that is called the shebang. If your file starts with #!/path/to/something the standard is to run something and pass the rest of the file to that program as an input.

With that said, the difference between #!/bin/bash, #!/bin/sh, or even #!/bin/zsh is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash and sh are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh is a link to dash, and on traditional Unix systems (Solaris, Irix, etc) bash is usually a completely different program from sh.

Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python, #!/usr/bin/perl, or even #!/usr/local/bin/my_own_scripting_language.

Get and Set a Single Cookie with Node.js HTTP Server

If you don't care what's in the cookie and you just want to use it, try this clean approach using request (a popular node module):

var request = require('request');
var j = request.jar();
var request = request.defaults({jar:j});
request('http://www.google.com', function () {
  request('http://images.google.com', function (error, response, body){
     // this request will will have the cookie which first request received
     // do stuff
  });
});

Shell script to check if file exists

You can do it in one line:

ls /home/edward/bank1/fiche/Test* >/dev/null 2>&1 && echo "found one" || echo "found none"

To understand what it does you have to decompose the command and have a basic awareness of boolean logic.

Directly from bash man page:

[...]
expression1 && expression2
     True if both expression1 and expression2 are true.
expression1 || expression2
     True if either expression1 or expression2 is true.
[...]

In the shell (and in general in unix world), the boolean true is a program that exits with status 0.

ls tries to list the pattern, if it succeed (meaning the pattern exists) it exits with status 0, 2 otherwise (have a look at ls man page for details).

In our case there are actually 3 expressions, for the sake of clarity I will put parenthesis, although they are not needed because && has precedence on ||:

 (expression1 && expression2) || expression3

so if expression1 is true (ie: ls found the pattern) it evaluates expression2 (which is just an echo and will exit with status 0). In this case expression3 is never evaluate because what's on the left site of || is already true and it would be a waste of resources trying to evaluate what's on the right.

Otherwise, if expression1 is false, expression2 is not evaluated but in this case expression3 is.

Compare integer in bash, unary operator expected

I need to add my 5 cents. I see everybody use [ or [[, but it worth to mention that they are not part of if syntax.

For arithmetic comparisons, use ((...)) instead.

((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See: ArithmeticExpression

Convert Time DataType into AM PM Format:

Here are the various ways you may pull this (depending on your needs).

Using the Time DataType:

DECLARE @Time Time = '15:04:46.217'
SELECT --'3:04PM'
       CONVERT(VarChar(7), @Time, 0),

       --' 3:04PM' --Leading Space.
       RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' '),

       --'03:04 PM' --Leading Zero.  This answers the question above.
       STUFF(RIGHT('0' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(CAST(@Time as DateTime), 'hh:mm tt')--Comment out for SS08 or less.

Using the DateTime DataType:

DECLARE @Date DateTime = '2016-03-17 15:04:46.217'
SELECT --' 3:04PM' --No space before AM/PM.
       RIGHT(CONVERT(VarChar(19), @Date, 0), 7),

       --' 3:04 PM' --Space before AM/PM.
       STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' '),

       --'3:04 PM' --No Leading Space.
       LTRIM(STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' ')),

       --'03:04 PM' --Leading Zero.
       STUFF(REPLACE(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), ' ', '0'), 6, 0, ' ')

       --'03:04 PM' --This only works in SQL Server 2012 and above.  :)
       ,FORMAT(@Date, 'hh:mm tt')--Comment line out for SS08 or less.

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Using reCAPTCHA on localhost

As per Google recaptcha documentation

localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

Difference between Math.Floor() and Math.Truncate()

They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers.

For example:

Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2

Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2

MSDN links: - Math.Floor Method - Math.Truncate Method

P.S. Beware of Math.Round it may not be what you expect.

To get the "standard" rounding result use:

float myFloat = 4.5;
Console.WriteLine( Math.Round(myFloat) ); // writes 4
Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5
Console.WriteLine( myFloat.ToString("F0") ); // writes 5

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

What is the difference between Bootstrap .container and .container-fluid classes?

I think you are saying that a container vs container-fluid is the difference between responsive and non-responsive to the grid. This is not true...what is saying is that the width is not fixed...its full width!

This is hard to explain so lets look at the examples


Example one

container-fluid:

http://www.bootply.com/119981

So you see how the container takes up the whole screen...that's a container-fluid.

Now lets look at the other just a normal container and watch the edges of the preview

Example two

container

http://www.bootply.com/119982

Now do you see the white space in the example? That's because its a fixed width container ! It might make more sense to open both examples up in two different tabs and switch back and forth.

EDIT

Better yet here is an example with both containers at once! Now you can really tell the difference!

http://www.bootply.com/119983

I hope this helped clarify a little bit!

Finding and removing non ascii characters from an Oracle Varchar2

If you use the ASCIISTR function to convert the Unicode to literals of the form \nnnn, you can then use REGEXP_REPLACE to strip those literals out, like so...

UPDATE table SET field = REGEXP_REPLACE(ASCIISTR(field), '\\[[:xdigit:]]{4}', '')

...where field and table are your field and table names respectively.

Log exception with traceback

You can log all uncaught exceptions on the main thread by assigning a handler to sys.excepthook, perhaps using the exc_info parameter of Python's logging functions:

import sys
import logging

logging.basicConfig(filename='/tmp/foobar.log')

def exception_hook(exc_type, exc_value, exc_traceback):
    logging.error(
        "Uncaught exception",
        exc_info=(exc_type, exc_value, exc_traceback)
    )

sys.excepthook = exception_hook

raise Exception('Boom')

If your program uses threads, however, then note that threads created using threading.Thread will not trigger sys.excepthook when an uncaught exception occurs inside them, as noted in Issue 1230540 on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching Thread.__init__ to overwrite self.run with an alternative run method that wraps the original in a try block and calls sys.excepthook from inside the except block. Alternatively, you could just manually wrap the entry point for each of your threads in try/except yourself.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

First make sure the PHP files themselves are UTF-8 encoded.

The meta tag is ignored by some browser. If you only use ASCII-characters, it doesn't matter anyway.

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

header('Content-Type: text/html; charset=utf-8');

How do I use Comparator to define a custom sort order?

Using just simple loops:

public static void compareSortOrder (List<String> sortOrder, List<String> listToCompare){
        int currentSortingLevel = 0;
        for (int i=0; i<listToCompare.size(); i++){
            System.out.println("Item from list: " + listToCompare.get(i));
            System.out.println("Sorting level: " + sortOrder.get(currentSortingLevel));
            if (listToCompare.get(i).equals(sortOrder.get(currentSortingLevel))){

            } else {
                try{
                    while (!listToCompare.get(i).equals(sortOrder.get(currentSortingLevel)))
                        currentSortingLevel++;
                    System.out.println("Changing sorting level to next value: " + sortOrder.get(currentSortingLevel));
                } catch (ArrayIndexOutOfBoundsException e){

                }

            }
        }
    }

And sort order in List

public static List<String> ALARMS_LIST = Arrays.asList(
            "CRITICAL",
            "MAJOR",
            "MINOR",
            "WARNING",
            "GOOD",
            "N/A");

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I had the same issue on windows. I switched from SSH to HTTPS and ran a Git PUSH.

git push -u origin master
Username for 'https://github.com': <Github login email>
Password for <Github login>: xxx

Successful! hope this helps.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Another corner case that this could happen: if you read/write a JAR file through a URL and later try to delete the same file within the same JVM session.

File f = new File("/tmp/foo.jar");
URL j = f.toURI().toURL();

URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
URLConnection c = u.openConnection();

// open a Jar entry in auto-closing manner
try (InputStream i = c.getInputStream()) {

    // just read some stuff; for demonstration purposes only
    byte[] first16 = new byte[16];
    i.read(first16);
    System.out.println(new String(first16));
}

// ...

// i is now closed, so we should be good to delete the jar; but...
System.out.println(f.delete());     // says false!

Reason is that the internal JAR file handling logic of Java, tends to cache JarFile entries:

// inner class of `JarURLConnection` that wraps the actual stream returned by `getInputStream()`

class JarURLInputStream extends FilterInputStream {
    JarURLInputStream(InputStream var2) {
        super(var2);
    }

    public void close() throws IOException {
        try {
            super.close();
        } finally {

            // if `getUseCaches()` is set, `jarFile` won't get closed!

            if (!JarURLConnection.this.getUseCaches()) {
                JarURLConnection.this.jarFile.close();
            }
        }
    }
}

And each JarFile (rather, the underlying ZipFile structure) would hold a handle to the file, right from the time of construction up until close() is invoked:

public ZipFile(File file, int mode, Charset charset) throws IOException {
    // ...

    jzfile = open(name, mode, file.lastModified(), usemmap);

    // ...
}

// ...

private static native long open(String name, int mode, long lastModified,
                                boolean usemmap) throws IOException;

There's a good explanation on this NetBeans issue.


Apparently there are two ways to "fix" this:

  • You can disable the JAR file caching - for the current URLConnection, or for all future URLConnections (globally) in the current JVM session:

    URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
    URLConnection c = u.openConnection();
    
    // for only c
    c.setUseCaches(false);
    
    // globally; for some reason this method is not static,
    // so we still need to access it through a URLConnection instance :(
    c.setDefaultUseCaches(false);
    
  • [HACK WARNING!] You can manually purge the JarFile from the cache when you are done with it. The cache manager sun.net.www.protocol.jar.JarFileFactory is package-private, but some reflection magic can get the job done for you:

    class JarBridge {
    
        static void closeJar(URL url) throws Exception {
    
            // JarFileFactory jarFactory = JarFileFactory.getInstance();
            Class<?> jarFactoryClazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
            Method getInstance = jarFactoryClazz.getMethod("getInstance");
            getInstance.setAccessible(true);
            Object jarFactory = getInstance.invoke(jarFactoryClazz);
    
            // JarFile jarFile = jarFactory.get(url);
            Method get = jarFactoryClazz.getMethod("get", URL.class);
            get.setAccessible(true);
            Object jarFile = get.invoke(jarFactory, url);
    
            // jarFactory.close(jarFile);
            Method close = jarFactoryClazz.getMethod("close", JarFile.class);
            close.setAccessible(true);
            //noinspection JavaReflectionInvocation
            close.invoke(jarFactory, jarFile);
    
            // jarFile.close();
            ((JarFile) jarFile).close();
        }
    }
    
    // and in your code:
    
    // i is now closed, so we should be good to delete the jar
    JarBridge.closeJar(j);
    System.out.println(f.delete());     // says true, phew.
    

Please note: All this is based on Java 8 codebase (1.8.0_144); they may not work with other / later versions.

C# Iterating through an enum? (Indexing a System.Array)

Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.

Array.GetValue

getActionBar() returns null

This may also help some people.

In my case, it was because I had not defined a context in the menu.xml

Try this:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.ActionBarActivity">

Instead of this:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

Force Java timezone as GMT/UTC

You could change the timezone using TimeZone.setDefault():

TimeZone.setDefault(TimeZone.getTimeZone("GMT"))

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Conversion failed when converting the nvarchar value ... to data type int

I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.

Capture :

enter image description here

How to run console application from Windows Service?

Windows Services do not have UIs. You can redirect the output from a console app to your service with the code shown in this question.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.

And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.

Jenkins: Is there any way to cleanup Jenkins workspace?

IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!

NOTE: I am assuming your $JENKINS_HOME is set to the default: /var/jenkins_home.

Clean up one workspace

rm -rf /var/jenkins_home/workspaces/<workspace>

Clean up all workspaces

rm -rf /var/jenkins_home/workspaces/*

Clean up all workspaces with a few exceptions

This one uses grep to create a whitelist:

ls /var/jenkins_home/workspace \ 
  | grep -v -E '(job-to-skip|another-job-to-skip)$' \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

Clean up 10 largest workspaces

This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:

du -d 1 /var/jenkins_home/workspace \
  | sort -n -r \
  | head -n 10 \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

jQuery Set Selected Option Using Next

Find the row, then

var row = $('#yourTable');

the value you want to select

var theValue = "5";
row.find("select:eq(2)").find("option[value="+theValue+']').attr('selected','selected');

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

I was getting this error because of the new Google Universal Analytics code, particularly caused by using the Remarketing lists on Analytics.

Here's how I fixed it.
1) Log into Google Analytics
2) Click "Admin" in top menu
3) In "Property" column, click "Property Settings"
4) Make sure "Enable Display Advertiser Features" is "On"
5) Click "Save" at bottom
6) Click ".js Tracking Info" in left menu
7) Click "Tracking Code"
8) Update your website's tracking code


When you run the debugger again, hopefully it will be taken care of.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

It is not necessary to stop timer, see nice solution from this post:

"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."

private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

How to check if any flags of a flag combination are set?

There are a lot of answers on here but I think the most idiomatic way to do this with Flags would be Letters.AB.HasFlag(letter) or (Letters.A | Letters.B).HasFlag(letter) if you didn't already have Letters.AB. letter.HasFlag(Letters.AB) only works if it has both.

Can I create links with 'target="_blank"' in Markdown?

Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:

[link](url){:target="_blank"}

Spring Boot yaml configuration for a list of strings

use comma separated values in application.yml

ignoreFilenames: .DS_Store, .hg

java code for access

@Value("${ignoreFilenames}")    
String[] ignoreFilenames

It is working ;)

How to validate a url in Python? (Malformed or not)

Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.

def get_domain_suffixes():
    import requests
    res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
    lst=set()
    for line in res.text.split('\n'):
        if not line.startswith('//'):
            domains=line.split('.')
            cand=domains[-1]
            if cand:
                lst.add('.'+cand)
    return tuple(sorted(lst))

domain_suffixes=get_domain_suffixes()

def reminds_url(txt:str):
    """
    >>> reminds_url('yandex.ru.com/somepath')
    True
    
    """
    ltext=txt.lower().split('/')[0]
    return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)

How to apply CSS to iframe?

If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

Note that depending on what browser you use this might only work on pages served from the same domain.

How to do joins in LINQ on multiple fields in single join

Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.

How to change Angular CLI favicon

The ensure the browser downloads a new version of the favicon and does not use a cached version you can add a dummy parameter to the favicon url:

<link rel="icon" type="image/x-icon" href="favicon.ico?any=param">

window.open(url, '_blank'); not working on iMac/Safari

There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows: with a drop down with a few options. I'm thinking yours may be set to Always. Bottom line is you can't rely on a browser opening a new window.

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

Which version of MVC am I using?

In Solution Explorer open packages.config and find Microsoft.AspNet.MVC:

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net461"

From the above we can see it's an Asp.Net MVC 5.2.3 Version.

Moreover packages.config file also helps us to track all the installed packages with their respective versions.

uncaught syntaxerror unexpected token U JSON

This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..

We were using middleware for token based encryption - decryption and we encountered same error.

Following was our code in route file:

  router.route("/uploadVideoMessage")
  .post(
    middleware.checkToken,
    upload.single("video_file"),
    videoMessageController.uploadVideoMessage
  );

here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.

router.route("/uploadVideoMessage")
  .post(
    upload.single("video_file"),
    middleware.checkToken,
    videoMessageController.uploadVideoMessage
  );

How to delete an item in a list if it exists?

Eek, don't do anything that complicated : )

Just filter() your tags. bool() returns False for empty strings, so instead of

new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

you should write

new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))

or better yet, put this logic inside striplist() so that it doesn't return empty strings in the first place.

Java Date vs Calendar

I use Calendar when I need some specific operations over the dates like moving in time, but Date I find it helpful when you need to format the date to adapt your needs, recently I discovered that Locale has a lot of useful operations and methods.So I'm using Locale right now!

Difference between res.send and res.json in Express.js

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf8 charset and application/json content-type

Convert Java string to Time, NOT Date

try {

    SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
    // or
    SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format

    java.util.Date d1 =(java.util.Date)format.parse(your_Time);

    java.sql.Time ppstime = new java.sql.Time(d1.getTime());

} catch(Exception e) {

    Log.e("Exception is ", e.toString());
}

how much memory can be accessed by a 32 bit machine?

No your concepts are not right. And to set it right you need the answer to the question that you incorrectly answered:

What is meant by 32bit or 64 bit machine?

The answer to the question is "something significant in the CPU is 32bit or 64 bit". So the question is what is that something significant? Lot of people say the width of data bus that determine whether the machine is 32bit or 64 bit. But none of the latest 32 bit processors have 32 bit or 64 bit wide data buses. most 32 bit systems will have 36 bit at least to support more RAM. Most 64 bit processors have no more than 48bit wide data bus because that is hell lot of memory already.

So according to me a 32 bit or 64 bit machine is determined by the size of its general purpose registers used in computation or "the natural word size" used by the computer.

Note that a 32 bit OS is a different thing. You can have a 32 bit OS running on 64 bit computer. Additionally, you can have 32 bit application running on 64 bit OS. If you do not understand the difference, post another question.

So the maximum amount of RAM a processor can address is 2^(width of data bus in bits), given that the proper addressing mode is switched on in the processor.

Further note, there is nothing stopping someone to introduce a multiplex between data Bus and memory banks, that will select a bank and then address the RAM (in two steps). This way you can address even more RAM. But that is impractical, and highly inefficient.

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Check if a number is odd or even in python

The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.

Hint: all you need is a slight tweak to the following line to make this work for all word lengths:

secondHalf = word[finalWordLength + 1:]

P.S. If you insist on handling the two cases separately, if len(word) % 2: ... would tell you that the word has an odd number of characters.

How to copy Java Collections list

If you want to copy an ArrayList, copy it by using:

List b = new ArrayList();
b.add("aa");
b.add("bb");

List a = new ArrayList(b);

How to open a new HTML page using jQuery?

You need to use ajax.

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

<code>
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});
</code>

AutoComplete TextBox Control

You could attach to the KeyDown event and then query the database for that portion of the text that the user has already entered. For example, if the user enters "T", search for things that start with "T". Then, when they enter the next letter, for example "e", search for things in the table that start with "Te".

The available items could be displayed in a "floating" ListBox, for example. You would need to place the ListBox just beneath the TextBox so that they can see the entries available, then remove the ListBox when they're done typing.

Is there a way to make HTML5 video fullscreen?

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

Emulate Samsung Galaxy Tab

You can't.

"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."

The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.

You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.

Different color for each bar in a bar chart; ChartJS

Taking the other answer, here is a quick fix if you want to get a list with random colors for each bar:

function getRandomColor(n) {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    var colors = [];
    for(var j = 0; j < n; j++){
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        colors.push(color);
        color = '#';
    }
    return colors;
}

Now you could use this function in the backgroundColor field in data:

data: {
        labels: count[0],
        datasets: [{
            label: 'Registros en BDs',
            data: count[1],
            backgroundColor: getRandomColor(count[1].length)
        }]
}

Django MEDIA_URL and MEDIA_ROOT

This if for Django 1.10:

 if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

Need to combine lots of files in a directory

Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.

For example, in the directory with all the text files, execute the following:

for %f in (*.txt) do type "%f" >> combined.txt

This will merge all files matching *.txt into one file called combined.txt.

For more information:

http://www.howtogeek.com/howto/keyboard-ninja/keyboard-ninja-concatenate-multiple-text-files-in-windows/

How do I format currencies in a Vue component?

With vuejs 2, you could use vue2-filters which does have other goodies as well.

npm install vue2-filters


import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

Then use it like so:

{{ amount | currency }} // 12345 => $12,345.00

Ref: https://www.npmjs.com/package/vue2-filters

Is there a typical state machine implementation pattern?

there is also the logic grid which is more maintainable as the state machine gets bigger

Which Architecture patterns are used on Android?

Here is a great article on Common Design Patterns for Android:

Creational patterns:

  • Builder (e.g. AlertDialog.Builder)
  • Dependency Injection (e.g. Dagger 2)
  • Singleton

Structural patterns:

  • Adapter (e.g. RecyclerView.Adapter)
  • Facade (e.g. Retrofit)

Behavioral patterns:

  • Command (e.g. EventBus)
  • Observer (e.g. RxAndroid)
  • Model View Controller
  • Model View ViewModel (similar to the MVC pattern above)

java collections - keyset() vs entrySet() in map

Traversal over the large map entrySet() is much better than the keySet(). Check this tutorial how they optimise the traversal over the large object with the help of entrySet() and how it helps for performance tuning.

Google Chrome redirecting localhost to https

The issue could be replicated in VS 2019 also. This is caused due to "Enable Javascript debugging from Visual Studio IDE". The VS attaches to Chrome and it is a possibility that due to security or reasons known to Google and Microsoft, it sometimes fails to attach and you have this issue. I am able to run http and https with localhost from ASP net core 3.1 app. So while debugging in VS, go to the run with arrow -> IIS express, just below "Web Browser(Chrome)" select "Script Debugging (Disabled)".

See article: https://devblogs.microsoft.com/aspnet/client-side-debugging-of-asp-net-projects-in-google-chrome/

https://docs.microsoft.com/en-us/visualstudio/debugger/debugging-web-applications?view=vs-2019

Always fallback to Microsoft docs to get more clarity than googling an issue.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Install MySQL on Ubuntu without a password prompt

Another way to make it work:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes '', but this solution was sufficient for me.

Based on a solution here.

Return date as ddmmyyyy in SQL Server

select replace(convert(VARCHAR,getdate(),103),'/','')

select right(convert(VARCHAR,getdate(),112),2) + 
       substring(convert(VARCHAR,getdate(),112),5,2) + 
       left(convert(VARCHAR,getdate(),112),4)

What is the difference between a .cpp file and a .h file?

.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.

How do I set the timeout for a JAX-WS webservice client?

The properties in the accepted answer did not work for me, possibly because I'm using the JBoss implementation of JAX-WS?

Using a different set of properties (found in the JBoss JAX-WS User Guide) made it work:

//Set timeout until a connection is established
((BindingProvider)port).getRequestContext().put("javax.xml.ws.client.connectionTimeout", "6000");

//Set timeout until the response is received
((BindingProvider) port).getRequestContext().put("javax.xml.ws.client.receiveTimeout", "1000");

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

Get record counts for all tables in MySQL database

If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.

Install following Gems:

$> gem install dbi
$> gem install dbd-mysql

File: count_table_records.rb

require 'rubygems'
require 'dbi'

db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')

# Collect all Tables
sql_1 = db_handler.prepare('SHOW tables;')
sql_1.execute
tables = sql_1.map { |row| row[0]}
sql_1.finish

tables.each do |table_name|
  sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};")
  sql_2.execute
  sql_2.each do |row|
    puts "Table #{table_name} has #{row[0]} rows."
  end
  sql_2.finish
end

db_handler.disconnect

Go back to the command-line:

$> ruby count_table_records.rb

Output:

Table users has 7328974 rows.

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

How to easily duplicate a Windows Form in Visual Studio?

Secured way without problems is to make Template of your form You can use it in the same project or any other project. and you can add it very easily, such as adding a new form . Here's a way how make Template

1- from File Menu click Export Template

2- Choose Template Type (Choose item template ) and click next

3-Check Form that you want to make a template of it, and click next Twice

4-Rename your template and (put describe , choose icon image ,preview image if you want)

5-click finish

Now you can add new item and choose your template in any project

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

MongoDB: Combine data from multiple collections into one..how?

Starting Mongo 4.4, we can achieve this join within an aggregation pipeline by coupling the new $unionWith aggregation stage with $group's new $accumulator operator:

// > db.users.find()
//   [{ user: 1, name: "x" }, { user: 2, name: "y" }]
// > db.books.find()
//   [{ user: 1, book: "a" }, { user: 1, book: "b" }, { user: 2, book: "c" }]
// > db.movies.find()
//   [{ user: 1, movie: "g" }, { user: 2, movie: "h" }, { user: 2, movie: "i" }]
db.users.aggregate([
  { $unionWith: "books"  },
  { $unionWith: "movies" },
  { $group: {
    _id: "$user",
    user: {
      $accumulator: {
        accumulateArgs: ["$name", "$book", "$movie"],
        init: function() { return { books: [], movies: [] } },
        accumulate: function(user, name, book, movie) {
          if (name) user.name = name;
          if (book) user.books.push(book);
          if (movie) user.movies.push(movie);
          return user;
        },
        merge: function(userV1, userV2) {
          if (userV2.name) userV1.name = userV2.name;
          userV1.books.concat(userV2.books);
          userV1.movies.concat(userV2.movies);
          return userV1;
        },
        lang: "js"
      }
    }
  }}
])
// { _id: 1, user: { books: ["a", "b"], movies: ["g"], name: "x" } }
// { _id: 2, user: { books: ["c"], movies: ["h", "i"], name: "y" } }
  • $unionWith combines records from the given collection within documents already in the aggregation pipeline. After the 2 union stages, we thus have all users, books and movies records within the pipeline.

  • We then $group records by $user and accumulate items using the $accumulator operator allowing custom accumulations of documents as they get grouped:

    • the fields we're interested in accumulating are defined with accumulateArgs.
    • init defines the state that will be accumulated as we group elements.
    • the accumulate function allows performing a custom action with a record being grouped in order to build the accumulated state. For instance, if the item being grouped has the book field defined, then we update the books part of the state.
    • merge is used to merge two internal states. It's only used for aggregations running on sharded clusters or when the operation exceeds memory limits.

What does `dword ptr` mean?

The dword ptr part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.

Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp register and subtracting four with 0.

Altering a column to be nullable

for Oracle Database 10g users:

alter table mytable modify(mycolumn null);

You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

Create text file and fill it using bash

Assuming you mean UNIX shell commands, just run

echo >> file.txt

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn't already exist.

In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

echo > file.txt

EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do

test -e file.txt || echo > file.txt

At least that works in Bash, I'm not sure if it also does in other shells.

How to deploy a war file in JBoss AS 7?

open up console and navigate to bin folder and run

JBOSS_HOME/bin > stanalone.sh

Once it is up and running just copy past your war file in

standalone/deployments folder

Thats probably it for jboss 7.1

Request format is unrecognized for URL unexpectedly ending in

I use following line of code to fix this problem. Write the following code in web.config file

<configuration>
    <system.web.extensions>
       <scripting>
       <webServices>
       <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
     </scripting>
   </system.web.extensions>
</configuration>

Javascript Array inside Array - how can I call the child array name?

I would create an object like this:

var options = { 
    size: ["S", "M", "L", "XL", "XXL"],
    color: ["Red", "Blue", "Green", "White", "Black"]
};


alert(Object.keys(options));

To access the keys individualy:

for (var key in options) {
    alert(key);
}

P.S.: when you create a new array object do not use new Array use [] instead.

openCV video saving in python

This answer covers what's what in terms of variables and importantly, output size shall be same for input frame and video size.

import cv2

save_name = "output.mp4"
fps = 10
width = 600
height = 480
output_size = (width, height)
out = cv2.VideoWriter(save_name,cv2.VideoWriter_fourcc('M','J','P','G'), fps , output_size )

cap = cv2.VideoCapture(0) # 0 for webcam or you can put in videopath
while(True):
    _, frame = cap.read()
    cv2.imshow('Video Frame', frame)
    out.write(cv2.resize(frame, output_size ))
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()

Deleting all files from a folder using PHP?

Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.

https://gist.github.com/4689551

To use:

To copy (or move) a single file or a set of folders/files:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Delete a single file or all files and folders in a path:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calculate the size of a single file or a set of files in a set of folders:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

C/C++ NaN constant (literal)?

This can be done using the numeric_limits in C++:

http://www.cplusplus.com/reference/limits/numeric_limits/

These are the methods you probably want to look at:

infinity()  T   Representation of positive infinity, if available.
quiet_NaN() T   Representation of quiet (non-signaling) "Not-a-Number", if available.
signaling_NaN() T   Representation of signaling "Not-a-Number", if available.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.

Short

  • Simple way Change the Application Pool mode to one that has Classic pipeline enabled.
  • Correct way Your web.config / web app will need to be altered to support Integrated pipelines. Normally this is as simple as removing parts of your web.config.
  • Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation

     <system.webServer>
         <validation validateIntegratedModeConfiguration="false" />
     </system.webServer>
    

Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.

If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.

  • Go to the web server
  • Open the IIS Manager
  • Navigate to your site
  • Click Advanced Settings on the right Action pane
  • Under Application Pool, change it to an app pool that has classic enabled.

Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool

If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx

If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.

Feel free to ask questions.

Why does 2 mod 4 = 2?

mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.

Suppress/ print without b' prefix for bytes in Python 3

Use decode:

print(curses.version.decode())
# 2.2

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

If your page does not modify any session variables, you can opt out of most of this lock.

<% @Page EnableSessionState="ReadOnly" %>

If your page does not read any session variables, you can opt out of this lock entirely, for that page.

<% @Page EnableSessionState="False" %>

If none of your pages use session variables, just turn off session state in the web.config.

<sessionState mode="Off" />

I'm curious, what do you think "a ThreadSafe collection" would do to become thread-safe, if it doesn't use locks?

Edit: I should probably explain by what I mean by "opt out of most of this lock". Any number of read-only-session or no-session pages can be processed for a given session at the same time without blocking each other. However, a read-write-session page can't start processing until all read-only requests have completed, and while it is running it must have exclusive access to that user's session in order to maintain consistency. Locking on individual values wouldn't work, because what if one page changes a set of related values as a group? How would you ensure that other pages running at the same time would get a consistent view of the user's session variables?

I would suggest that you try to minimize the modifying of session variables once they have been set, if possible. This would allow you to make the majority of your pages read-only-session pages, increasing the chance that multiple simultaneous requests from the same user would not block each other.

How to make unicode string with python3

the easiest way in python 3.x

text = "hi , I'm text"
text.encode('utf-8')

C# Error: Parent does not contain a constructor that takes 0 arguments

You can use a constructor with no parameters in your Parent class :

public parent() { } 

From io.Reader to string in Go

I like the bytes.Buffer struct. I see it has ReadFrom and String methods. I've used it with a []byte but not an io.Reader.

How do I increase memory on Tomcat 7 when running as a Windows Service?

According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:

CATALINA_OPTS='-Xms512m -Xmx1024m'

My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.

Removing leading and trailing spaces from a string

Boost string trim algorithm

#include <boost/algorithm/string/trim.hpp>

[...]

std::string msg = "   some text  with spaces  ";
boost::algorithm::trim(msg);

How can I get the list of files in a directory using C or C++?

#include<iostream>
#include <dirent.h>
using namespace std;
char ROOT[]={'.'};

void listfiles(char* path){
    DIR * dirp = opendir(path);
    dirent * dp;
    while ( (dp = readdir(dirp)) !=NULL ) {
         cout << dp->d_name << " size " << dp->d_reclen<<std::endl;
    }
    (void)closedir(dirp);
}

int main(int argc, char **argv)
{
    char* path;
    if (argc>1) path=argv[1]; else path=ROOT;

    cout<<"list files in ["<<path<<"]"<<std::endl;
    listfiles(path);

    return 0;
}