Programs & Examples On #Gridviewheader

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

Detect end of ScrollView

To determine if you are at the end of your custom ScrollView you could also use a member variable and store the last y-position. Then you can compare the last y-position with the current scroll position.

private int scrollViewPos;

...

@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {

   //reached end of scrollview
   if (y > 0 && scrollViewPos == y){
      //do something
   }

   scrollViewPos = y;
}

Why do I get "MismatchSenderId" from GCM server side?

Please run below script in your terminal

curl -X POST \
-H "Authorization: key=  write here api_key" \
-H "Content-Type: application/json" \
-d '{ 
"registration_ids": [ 
"write here reg_id generated by gcm"
], 
"data": { 
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send

it will give the message if it is succeeded or failed

Android Webview - Completely Clear the Cache

CookieSyncManager.createInstance(this);    
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.removeAllCookie();

It can clear google account in my webview

How create table only using <div> tag and Css

If there is anything in <table> you don't like, maybe you could use reset file?

or

if you need this for layout of the page check out the cssplay layout examples for designing websites without tables.

Can't connect Nexus 4 to adb: unauthorized

I was facing same, issue, I found I was using a simple usb cable which was meant for only charge and not data copy. using good usb cable solved my problem !

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

For Android 3+:

  • In the Project window, select the Android view.

  • Right-click the res folder and select New > Image Asset.

  • If your app supports Android 8.0, create adaptive and legacy launcher icons.

  • If your app supports versions no higher than Android 7.1, create a legacy launcher icon only.

  • In the Icon Type field, select Launcher Icons (Legacy Only) .

  • Select an Asset Type, and then specify the asset in the field underneath.

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

How do I find the mime-type of a file with php?

If you are working with Images only and you need mime type (e.g. for headers), then this is the fastest and most direct answer:

$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));

It will output true image mime type even if you rename your image file

How to run Nginx within a Docker container without halting?

To add Tomer and Charles answers,

Syntax to run nginx in forground in Docker container using Entrypoint:

ENTRYPOINT nginx -g 'daemon off;' 

Not directly related but to run multiple commands with Entrypoint:

ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;' 

Java 8 Stream and operation on arrays

You can turn an array into a stream by using Arrays.stream():

int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);

Once you've got your stream, you can use any of the methods described in the documentation, like sum() or whatever. You can map or filter like in Python by calling the relevant stream methods with a Lambda function:

Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);

Once you're done modifying your stream, you then call toArray() to convert it back into an array to use elsewhere:

int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I am assuming Basic authentication here.

$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred

You can get your credential through other means (Import-Clixml, etc.), but it does have to be a [PSCredential] object.

Edit based on comments:

GitHub is breaking RFC as they explain in the link you provided:

The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.

Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.

Manually build the headers

Instead you'll have to create the basic auth headers yourself.

Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that.

Code like this should work:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

You could combine some of the string concatenation but I wanted to break it out to make it clearer.

Handling warning for possible multiple enumeration of IEnumerable

If the aim is really to prevent multiple enumerations than the answer by Marc Gravell is the one to read, but maintaining the same semantics you could simple remove the redundant Any and First calls and go with:

public List<object> Foo(IEnumerable<object> objects)
{
    if (objects == null)
        throw new ArgumentNullException("objects");

    var first = objects.FirstOrDefault();

    if (first == null)
        throw new ArgumentException(
            "Empty enumerable not supported.", 
            "objects");

    var list = DoSomeThing(first);  

    var secondList = DoSomeThingElse(objects);

    list.AddRange(secondList);

    return list;
}

Note, that this assumes that you IEnumerable is not generic or at least is constrained to be a reference type.

How to remove focus from input field in jQuery?

Use .blur().

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

$("#myInputID").blur(); 

How to print formatted BigDecimal values?

 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

How to change Navigation Bar color in iOS 7?

For swift change navigation bar color:

self.navigationController?.navigationBar.barTintColor = UIColor.red

change title font,size, color:

self.title = "title"
self.navigationController?.navigationBar.titleTextAttributes = [
        NSAttributedString.Key.foregroundColor : UIColor.white,
        NSAttributedString.Key.font : UIFont(name: "Futura", size: 30)!
    ]

Calling jQuery method from onClick attribute in HTML

I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:

function showMessage(msg) {
   alert(msg);
};

<input type="button" value="ahaha" onclick="showMessage('msg');" />

UPDATE: With a small change to how your method is defined I can get it to work:

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script language="javascript">
    // define the function within the global scope
    $.fn.MessageBox = function(msg) {
        alert(msg);
    };

    // or, if you want to encapsulate variables within the plugin
    (function($) {
        $.fn.MessageBoxScoped = function(msg) {
            alert(msg);
        };
    })(jQuery); //<-- make sure you pass jQuery into the $ parameter
 </script>
</head>
<body>
 <div class="Title">Welcome!</div>
 <input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>

Fuzzy matching using T-SQL

I've found that the stuff SQL Server gives you to do fuzzy matching is pretty clunky. I've had really good luck with my own CLR functions using the Levenshtein distance algorithm and some weighting. Using that algorithm, I've then made a UDF called GetSimilarityScore that takes two strings and returns a score between 0.0 and 1.0. The closer to 1.0 the match is, the better. Then, query with a threshold of >=0.8 or so to get the most likely matches. Something like this:

if object_id('tempdb..#similar') is not null drop table #similar
select a.id, (
    select top 1 x.id
   from MyTable x
   where x.id <> a.id
   order by dbo.GetSimilarityScore(a.MyField, x.MyField) desc
) as MostSimilarId
into #similar
from MyTable a

select *, dbo.GetSimilarityScore(a.MyField, c.MyField)
from MyTable a
join #similar b on a.id = b.id
join MyTable c on b.MostSimilarId = c.id

Just don't do it with really large tables. It's a slow process.

Here's the CLR UDFs:

''' <summary>
''' Compute the distance between two strings.
''' </summary>
''' <param name="s1">The first of the two strings.</param>
''' <param name="s2">The second of the two strings.</param>
''' <returns>The Levenshtein cost.</returns>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function ComputeLevenstheinDistance(ByVal string1 As SqlString, ByVal string2 As SqlString) As SqlInt32
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null
    Dim s1 As String = string1.Value
    Dim s2 As String = string2.Value

    Dim n As Integer = s1.Length
    Dim m As Integer = s2.Length
    Dim d As Integer(,) = New Integer(n, m) {}

    ' Step 1
    If n = 0 Then Return m
    If m = 0 Then Return n

    ' Step 2
    For i As Integer = 0 To n
        d(i, 0) = i
    Next

    For j As Integer = 0 To m
        d(0, j) = j
    Next

    ' Step 3
    For i As Integer = 1 To n
        'Step 4
        For j As Integer = 1 To m
            ' Step 5
            Dim cost As Integer = If((s2(j - 1) = s1(i - 1)), 0, 1)

            ' Step 6
            d(i, j) = Math.Min(Math.Min(d(i - 1, j) + 1, d(i, j - 1) + 1), d(i - 1, j - 1) + cost)
        Next
    Next
    ' Step 7
    Return d(n, m)
End Function

''' <summary>
''' Returns a score between 0.0-1.0 indicating how closely two strings match.  1.0 is a 100%
''' T-SQL equality match, and the score goes down from there towards 0.0 for less similar strings.
''' </summary>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function GetSimilarityScore(string1 As SqlString, string2 As SqlString) As SqlDouble
    If string1.IsNull OrElse string2.IsNull Then Return SqlInt32.Null

    Dim s1 As String = string1.Value.ToUpper().TrimEnd(" "c)
    Dim s2 As String = string2.Value.ToUpper().TrimEnd(" "c)
    If s1 = s2 Then Return 1.0F ' At this point, T-SQL would consider them the same, so I will too

    Dim flatLevScore As Double = InternalGetSimilarityScore(s1, s2)

    Dim letterS1 As String = GetLetterSimilarityString(s1)
    Dim letterS2 As String = GetLetterSimilarityString(s2)
    Dim letterScore As Double = InternalGetSimilarityScore(letterS1, letterS2)

    'Dim wordS1 As String = GetWordSimilarityString(s1)
    'Dim wordS2 As String = GetWordSimilarityString(s2)
    'Dim wordScore As Double = InternalGetSimilarityScore(wordS1, wordS2)

    If flatLevScore = 1.0F AndAlso letterScore = 1.0F Then Return 1.0F
    If flatLevScore = 0.0F AndAlso letterScore = 0.0F Then Return 0.0F

    ' Return weighted result
    Return (flatLevScore * 0.2F) + (letterScore * 0.8F)
End Function

Private Shared Function InternalGetSimilarityScore(s1 As String, s2 As String) As Double
    Dim dist As SqlInt32 = ComputeLevenstheinDistance(s1, s2)
    Dim maxLen As Integer = If(s1.Length > s2.Length, s1.Length, s2.Length)
    If maxLen = 0 Then Return 1.0F
    Return 1.0F - Convert.ToDouble(dist.Value) / Convert.ToDouble(maxLen)
End Function

''' <summary>
''' Sorts all the alpha numeric characters in the string in alphabetical order
''' and removes everything else.
''' </summary>
Private Shared Function GetLetterSimilarityString(s1 As String) As String
    Dim allChars = If(s1, "").ToUpper().ToCharArray()
    Array.Sort(allChars)
    Dim result As New StringBuilder()
    For Each ch As Char In allChars
        If Char.IsLetterOrDigit(ch) Then
            result.Append(ch)
        End If
    Next
    Return result.ToString()
End Function

''' <summary>
''' Removes all non-alpha numeric characters and then sorts
''' the words in alphabetical order.
''' </summary>
Private Shared Function GetWordSimilarityString(s1 As String) As String
    Dim words As New List(Of String)()
    Dim curWord As StringBuilder = Nothing
    For Each ch As Char In If(s1, "").ToUpper()
        If Char.IsLetterOrDigit(ch) Then
            If curWord Is Nothing Then
                curWord = New StringBuilder()
            End If
            curWord.Append(ch)
        Else
            If curWord IsNot Nothing Then
                words.Add(curWord.ToString())
                curWord = Nothing
            End If
        End If
    Next
    If curWord IsNot Nothing Then
        words.Add(curWord.ToString())
    End If

    words.Sort(StringComparer.OrdinalIgnoreCase)
    Return String.Join(" ", words.ToArray())
End Function

How do I manage conflicts with git submodules?

I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:

  1. Run git status - make a note of the submodule folder with conflicts
  2. Reset the submodule to the version that was last committed in the current branch:

    git reset HEAD path/to/submodule

  3. At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:

    cd path/to/submodule
    git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
  4. And now you can commit that and get back to work.

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

Copying PostgreSQL database to another server

Run this command with database name, you want to backup, to take dump of DB.

 pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

 eg. pg_dump -U postgres mydbname -f mydbnamedump.sql

Now scp this dump file to remote machine where you want to copy DB.

eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/

On remote machine run following command in ~/some/folder to restore the DB.

 psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}

 eg. psql -U postgres -d mynewdb -f mydbnamedump.sql

How can I break up this long line in Python?

You can use textwrap module to break it in multiple lines

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

From the documentation:

textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

Email Address Validation for ASP.NET

Validating that it is a real email address is much harder.

The regex to confirm the syntax is correct can be very long (see http://www.regular-expressions.info/email.html for example). The best way to confirm an email address is to email the user, and get the user to reply by clicking on a link to validate that they have recieved the email (the way most sign-up systems work).

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

I solved this using

$content = utf8_encode(file_get_contents('http://example.com/rss.xml'));
$xml = simplexml_load_string($content);

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

PostgreSQL query to list all table names?

select 
 relname as table 
from 
 pg_stat_user_tables 
where schemaname = 'public'

select 
  tablename as table 
from 
  pg_tables  
where schemaname = 'public'

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Where does MAMP keep its php.ini?

After going through all the solutions here, the easiest way to find the loaded php.ini file is to go into phpinfo on the loaded MAMP webpage, which will show you the loaded php.ini file.

This will also confirm if the parameters you change, like max_file_size, have updated correctly.

Can we cast a generic object to a custom object type in javascript?

This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :

var Foo = function(){
    this.bar = undefined;
    this.buzz = undefined;
}

var foo = Object.assign(new Foo(),{
    bar: "whatever",
    buzz: "something else"
});

I like it because it is the closest to the very neat object initialisation in .Net:

var foo = new Foo()
{
    bar: "whatever",
    ...

link_to image tag. how to add class to a tag

The whole :action =>, :controller => bit that I've seen around a lot didn't work for me.

Spent hours digging and this method definitely worked for me in a loop.

<%=link_to( image_tag(participant.user.profile_pic.url(:small)), user_path(participant.user), :class=>"work") %>

Ruby on Rails using link_to with image_tag

Also, I'm using Rails 4.

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Converting VS2012 Solution to VS2010

I also faced the similar problem. I googled but couldn't find the solution. So I tried on my own and here is my solution.

Open you solution file in notepad. Make 2 changes

  1. Replace "Format Version 12.00" with "Format Version 11.00" (without quotes.)
  2. Replace "# Visual Studio 2012" with "# Visual Studio 2010" (without quotes.)

Hope this helps u as well..........

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

When you export you use the compatibility system set to MYSQL40. Worked for me.

How do I PHP-unserialize a jQuery-serialized form?

You just need value attribute name in form. Example :

Form

<form id="login_form">
    <input type="text" name="username" id="a"/>
    <input type="password" name="password" id="b"/>
    <button type="button" onclick="login()">Submit</button>
</form>

Javascript

$(document).ready(function(){});
function login(){
  var obj = $('#login_form').serialize();
  $.post('index.php', obj, function(res){
    alert(res);
  })
}

PHP - index.php

<?php
if(!empty($POST['username']) && !empty($POST['password'])){
  $user = $POST['username'];
  $pass = $POST['password'];
  $res = "Username : ".$user." || Password : ".$pass;
  return $res;
}
?>

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

Git stash pop- needs merge, unable to refresh index

The stash has already been applied to other files.

It is only app.coffee that you have to merge manually. Afterwards just run

git reset

to unstage the changes and keep on hacking.

What are the differences in die() and exit() in PHP?

They are essentially the same, though this article suggest otherwise.

How to increase memory limit for PHP over 2GB?

For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

Error message "Strict standards: Only variables should be passed by reference"

$instance->find() returns a reference to a variable.

You get the report when you are trying to use this reference as an argument to a function, without storing it in a variable first.

This helps preventing memory leaks and will probably become an error in the next PHP versions.

Your second code block would throw an error if it wrote like (note the & in the function signature):

function &get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So a quick (and not so nice) fix would be:

$el = array_shift($tmp = $instance->find(..));

Basically, you do an assignment to a temporary variable first and send the variable as an argument.

SELECT query with CASE condition and SUM()

select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

Cheers -

Android Fragment onAttach() deprecated

This worked for me when i have userdefined Interface 'TopSectionListener', its object activitycommander:

  //This method gets called whenever we attach fragment to the activity
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    Activity a=getActivity();
    try {
        if(context instanceof Activity)
           this.activitycommander=(TopSectionListener)a;
    }catch (ClassCastException e){
        throw new ClassCastException(a.toString());}

}

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

log4j vs logback

In the logging world there are Facades (like Apache Commons Logging, slf4j or even the Log4j 2.0 API) and implementations (Log4j 1 + 2, java.util.logging, TinyLog, Logback).

Basically you should replace your selfmade wrapper with slf4j IF and only IF you are not happy with it for some reason. While Apache Commons Logging is not really providing a modern API, slf4j and the new Log4j 2 facade is providing that. Given that quite a bunch of apps use slf4j as a wrapper it might make sense to use that.

slf4j gives a number of nice API sugar, like this example from slf4j docs:

logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

It's variable substitution. This is also supported by Log4j 2.

However you need to be aware that slf4j is developed by QOS who also maintain logback. Log4j 2.0 is baked in the Apache Software Foundation. In the past three years a vibrant and active community has grown there again. If you appreciate Open Source as it is done by the Apache Software Foundation with all its guarantees you might reconsider using slf4j in favor to use Log4j 2 directly.

Please note:

In the past log4j 1 was not actively maintained while Logback was. But today things are different. Log4j 2 is actively maintained and releases on almost regular schedule. It also includes lot of modern features and -imho- makes a couple of things better than Logback. This is sometimes just a matter of taste and you should draw your own conclusions.

I wrote a quick overview on the new Features of Log4j 2.0: http://www.grobmeier.de/the-new-log4j-2-0-05122012.html

When reading you will see that Log4j 2 was inspired by Logback but also by other logging frameworks. But the code base is different; it shares almost nothing with Log4j 1 and zero with Logback. This lead to some improvements like in example Log4j 2 operates with bytestreams instead of Strings under the hood. Also it doesn't loose events while reconfiguring.

Log4j 2 can log with higher speed than other frameworks I know: http://www.grobmeier.de/log4j-2-performance-close-to-insane-20072013.html

And still the user community seems to be much bigger than Logbacks: http://www.grobmeier.de/apache-log4j-is-the-leading-logging-framework-06082013.html

That all said the best idea is you choose the logging frameworks which just fits best to what you want to achieve. I would not switch a full framework if I would disable logging in production environment and just perform basic logging in my app. However if you do a bit more with logging just look at the features which are provided by the frameworks and their developers. While you get commercial support for Logback through QOS (i heard) there is currently no commercial support for Log4j 2. On the other hand if you need to do audit logging and need high performance provided by the async appenders it makes a lot of sense to check log4j 2.

Please note despite all comfort they provide, facades always eat a little performance. It's maybe not affecting you at all, but if you are on low resources you may need to save everything you can have.

Without knowing you requirements better it is almost impossible to give a recommendation. Just: don't switch just because a lot of people switch. Switch only because you see value of it. And the argumentation that log4j is dead doesn't count anymore. It's alive, and it's hot.

DISCLAIMER: I am currently VP, Apache Logging Services and involved in log4j as well.

How to replace multiple substrings of a string?

In my case, I needed a simple replacing of unique keys with names, so I thought this up:

a = 'This is a test string.'
b = {'i': 'I', 's': 'S'}
for x,y in b.items():
    a = a.replace(x, y)
>>> a
'ThIS IS a teSt StrIng.'

How to create a fixed sidebar layout with Bootstrap 4?

Updated 2020

Here's an updated answer for the latest Bootstrap 4.0.0. This version has classes that will help you create a sticky or fixed sidebar without the extra CSS....

Use sticky-top:

<div class="container">
    <div class="row py-3">
        <div class="col-3 order-2" id="sticky-sidebar">
            <div class="sticky-top">
                ...
            </div>
        </div>
        <div class="col" id="main">
            <h1>Main Area</h1>
            ...   
        </div>
    </div>
</div>

Demo: https://codeply.com/go/O9GMYBer4l

or, use position-fixed:

<div class="container-fluid">
    <div class="row">
        <div class="col-3 px-1 bg-dark position-fixed" id="sticky-sidebar">
            ...
        </div>
        <div class="col offset-3" id="main">
            <h1>Main Area</h1>
            ...
        </div>
    </div>
</div>

Demo: https://codeply.com/p/0Co95QlZsH

Also see:
Fixed and scrollable column in Bootstrap 4 flexbox
Bootstrap col fixed position
How to use CSS position sticky to keep a sidebar visible with Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?

How to set enum to null

would it not be better to explicitly assign value 0 to None constant? Why?

Because default enum value is equal to 0, if You would call default(Color) it would print None.

Because it is at first position, assigning literal value 0 to any other constant would change that behaviour, also changing order of occurrence would change output of default(Color) (https://stackoverflow.com/a/4967673/8611327)

How to select option in drop down protractorjs e2e tests

I've been trawling the net for an answer on how to select an option in a model dropdown and i've used this combination which has helped me out with Angular material.

element(by.model("ModelName")).click().element(By.xpath('xpathlocation')).click();

it appears that when throwing the code all in one line it could find the element in the dropdown.

Took a lot of time for this solution I hope that this helps someone out.

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

Cast to generic type in C#

I struggled to solve a similar problem around data table classes instead of messages. The root issue mentioned above of casting a non-generic version of the class to a derived generic version was the same.

In order to allow injection into a portable class library which did not support database libraries, I introduced a set of interface classes, with the intent that I could pass a type and get a matching generic. It ended up needing to implement a generic method.

// Interface for injection
public interface IDatabase
{
    // Original, non-functional signature:
    IDatatable<object> GetDataTable(Type dataType);

    // Functional method using a generic method:
    IDatatable<T> GetDataTable<T>();
}

And this the whole implementation using the generic method above.

The generic class that will be cast from a dictionary.

// Non-generic base class allows listing tables together
abstract class Datatable
{
    Datatable(Type storedClass)
    {
      StoredClass = storedClass;
    }

    Type StoredClass { get; private set; }
}

// Generic inheriting class
abstract class Datatable<T>: Datatable, IDatatable<T>
{
    protected Datatable()
        :base(typeof(T))
    {
    }
}

This is the class that stores the generic class and casts it to satisfy the generic method in the interface

class Database
{
    // Dictionary storing the classes using the non-generic base class
    private Dictionary<Type, Datatable> _tableDictionary;

    protected Database(List<Datatable> tables)
    {
        _tableDictionary = new Dictionary<Type, Datatable>();
        foreach (var table in tables)
        {
            _tableDictionary.Add(table.StoredClass, table);
        }
    }

    // Interface implementation, casts the generic
    public IDatatable<T> GetDataTable<T>()
    {
        Datatable table = null;

        _tableDictionary.TryGetValue(typeof(T), out table);

        return table as IDatatable<T>;
    }
}

And finally the calling of the interface method.

IDatatable<CustomerAccount> table = _database.GetDataTable<CustomerAccount>();

Python: Number of rows affected by cursor.execute("SELECT ...)

The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python MySQLdb:

 def execute(self, query, args=None):

    """Execute a query.

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

    Note: If args is a sequence, then %s must be used as the
    parameter placeholder in the query. If a mapping is used,
    %(key)s must be used as the placeholder.

    Returns long integer rows affected, if any

    """

Count number of 1's in binary representation

Below are two simple examples (in C++) among many by which you can do this.

  1. We can simply count set bits (1's) using __builtin_popcount().

    int numOfOnes(int x) { return __builtin_popcount(x); }

  2. Loop through all bits in an integer, check if a bit is set and if it is then increment the count variable.

    int hammingDistance(int x) { int count = 0 for(int i = 0; i < 32; i++) if(x & (1 << i)) count++; return count; }

Hope this helps!

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

ERROR: Cannot open source file " "

Let Unreal do the job. Close all, Right click your Project File (.uproject),
"Generate VisualStudio Project Files".

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

Fragments onResume from back stack

This is the correct answer you can call onResume() providing the fragment is attached to the activity. Alternatively you can use onAttach and onDetach

What's default HTML/CSS link color?

Default html color code like this:

Red      #FF0000  rgb(255, 0, 0)
Maroon   #800000  rgb(128, 0, 0)
Yellow   #FFFF00  rgb(255, 255, 0)
Olive    #808000  rgb(128, 128, 0)
Blue     #0000FF  rgb(0, 0, 255)
Navy     #000080  rgb(0, 0, 128)
Fuchsia  #FF00FF  rgb(255, 0, 255)
Purple   #800080  rgb(128, 0, 128)

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

There is a line in wp-config.php:

define('DB_CHARSET', 'utf8mb4');

If you follow Markouver's / Evster's instructions, don't forget to change this line on production server to

define('DB_CHARSET', 'utf8');

in order to fix broken 4-byte characters

Convert NaN to 0 in javascript

Methods that use isNaN do not work if you're trying to use parseInt, for example:

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

But in the second case isNaN produces false (i.e. the null string is a number)

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.

Django CSRF check failing with an Ajax POST request

In my case the problem was with the nginx config that I've copied from main server to a temporary one with disabling https that is not needed on the second one in the process.

I had to comment out these two lines in the config to make it work again:

# uwsgi_param             UWSGI_SCHEME    https;
# uwsgi_pass_header       X_FORWARDED_PROTO;

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month! e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.

Predicate in Java

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true to a function instead of defining a named Tautology subclass like the above.

IO Error: The Network Adapter could not establish the connection

I was having issues with this as well. I was using the jdbc connection string to connect to the database. The hostname was incorrectly configured in the string. I am using Mac, and the same string was being used on Windows machines without an issue. On my connection string, I had to make sure that I had the full url with the appending "organizationname.com" to the end of the hostname.

Hope this helps.

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

How do you change the value inside of a textfield flutter?

You can use the text editing controller to manipulate the value inside a textfield.

var textController = new TextEditingController();

Now, create a new textfield and set textController as the controller for the textfield as shown below.

 new TextField(controller: textController)

Now, create a RaisedButton anywhere in your code and set the desired text in the onPressed method of the RaisedButton.

new RaisedButton(
       onPressed: () {
          textController.text = "New text";
       }
    ),

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

Invert match with regexp

Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...

Spring Boot @autowired does not work, classes in different package

For this kind of issue, I ended up in putting @Service annotation on the newly created service class then the autowire was picked up. So, try to check those classes which are not getting autowired, if they need the corresponding required annotations(like @Controller, @Service, etc.) applied to them and then try to build the project again.

Android emulator-5554 offline

Just Wipe user data from AVD manager and then enter adb kill-server and adb devices. Wiping data also saves lot of memory space in the System .

Producer/Consumer threads using a Queue

  1. Java code "BlockingQueue" which has synchronized put and get method.
  2. Java code "Producer" , producer thread to produce data.
  3. Java code "Consumer" , consumer thread to consume the data produced.
  4. Java code "ProducerConsumer_Main", main function to start the producer and consumer thread.

BlockingQueue.java

public class BlockingQueue 
{
    int item;
    boolean available = false;

    public synchronized void put(int value) 
    {
        while (available == true)
        {
            try 
            {
                wait();
            } catch (InterruptedException e) { 
            } 
        }

        item = value;
        available = true;
        notifyAll();
    }

    public synchronized int get()
    {
        while(available == false)
        {
            try
            {
                wait();
            }
            catch(InterruptedException e){
            }
        }

        available = false;
        notifyAll();
        return item;
    }
}

Consumer.java

package com.sukanya.producer_Consumer;

public class Consumer extends Thread
{
    blockingQueue queue;
    private int number;
    Consumer(BlockingQueue queue,int number)
    {
        this.queue = queue;
        this.number = number;
    }

    public void run()
    {
        int value = 0;

        for (int i = 0; i < 10; i++) 
        {
            value = queue.get();
            System.out.println("Consumer #" + this.number+ " got: " + value);
        }
    }
}

ProducerConsumer_Main.java

package com.sukanya.producer_Consumer;

public class ProducerConsumer_Main 
{
    public static void main(String args[])
    {
        BlockingQueue queue = new BlockingQueue();
        Producer producer1 = new Producer(queue,1);
        Consumer consumer1 = new Consumer(queue,1);
        producer1.start();
        consumer1.start();
    }
}

How do I view executed queries within SQL Server Management Studio?

More clear query, targeting Studio sql queries is :

SELECT text  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) 
  where program_name like '%Query'

How to replace (null) values with 0 output in PIVOT

SELECT CLASS,
isnull([AZ],0),
isnull([CA],0),
isnull([TX],0)
FROM #TEMP
PIVOT (SUM(DATA)
FOR STATE IN ([AZ], [CA], [TX])) AS PVT
ORDER BY CLASS

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

Python strptime() and timezones?

I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.

>>> from dateutil import parser
>>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
>>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400")
datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400))
>>> parser.parse("Sun")
datetime.datetime(2011, 12, 18, 0, 0)
>>> parser.parse("10-11-08")
datetime.datetime(2008, 10, 11, 0, 0)

and so on. No dealing with strptime() format nonsense... just throw a date at it and it Does The Right Thing.

Update: Oops. I missed in your original question that you mentioned that you used dateutil, sorry about that. But I hope this answer is still useful to other people who stumble across this question when they have date parsing questions and see the utility of that module.

Unescape HTML entities in Javascript?

Chris answer is nice & elegant but it fails if value is undefined. Just simple improvement makes it solid:

function htmlDecode(value) {
   return (typeof value === 'undefined') ? '' : $('<div/>').html(value).text();
}

Remove a HTML tag but keep the innerHtml

$('b').contents().unwrap();

This selects all <b> elements, then uses .contents() to target the text content of the <b>, then .unwrap() to remove its parent <b> element.


For the greatest performance, always go native:

var b = document.getElementsByTagName('b');

while(b.length) {
    var parent = b[ 0 ].parentNode;
    while( b[ 0 ].firstChild ) {
        parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
    }
     parent.removeChild( b[ 0 ] );
}

This will be much faster than any jQuery solution provided here.

Uncaught SyntaxError: Unexpected token :

This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

please try these

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "User_name" value= "<?php echo $row['User_name']; ?> "size=10>
Password
<input type="text" name= "User_password" value= "<?php echo $row['User_password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

How to find controls in a repeater header or footer

As noted in the comments, this only works AFTER you've DataBound your repeater.

To find a control in the header:

lblControl = repeater1.Controls[0].Controls[0].FindControl("lblControl");

To find a control in the footer:

lblControl = repeater1.Controls[repeater1.Controls.Count - 1].Controls[0].FindControl("lblControl");

With extension methods

public static class RepeaterExtensionMethods
{
    public static Control FindControlInHeader(this Repeater repeater, string controlName)
    {
        return repeater.Controls[0].Controls[0].FindControl(controlName);
    }

    public static Control FindControlInFooter(this Repeater repeater, string controlName)
    {
        return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
    }
}

Display unescaped HTML in Vue.js

Before using v-html, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.

More info here: https://vuejs.org/v2/guide/security.html

I highly encourage you that instead of using v-html to use this npm package

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

How can I make a JPA OneToOne relation lazy

First off, some clarifications to KLE's answer:

  1. Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a more detailed explanation.

  2. many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.

  3. Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.

Rob H. has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association is nullable).

Now, as far as original question goes:

A) @ManyToOne(fetch=FetchType.LAZY) should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify join fetch in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.

B) @OneToOne is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:

@OneToOne(optional = false, fetch = FetchType.LAZY)

Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
public OtherEntity getOther()

and in OtherEntity:

@OneToOne(mappedBy = "other")
public OwnerEntity getOwner()

If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with CPerkins, however - if you have 80!!! joins due to eager OneToOne associations, you've got bigger problems then this :-)

pdftk compression option

In case you want to compress a PDF which contains a lot of selectable text, on Windows you can use NicePDF Compressor - choose "Flate" option. After trying everything (cpdf, pdftk, gs) it finally helped me to compress my 1360 pages PDF from 500 MB down to 10 MB.

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

How do I add a simple jQuery script to WordPress?

**#Method 1:**Try to put your jquery code in a separate js file.

Now register that script in functions.php file.

function add_my_script() {
    wp_enqueue_script(
      'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
        array('jquery') 
    );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Now you are done.

Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.

How to change the floating label color of TextInputLayout

you should change your colour here

<style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#673AB7</item>
        <item name="colorPrimaryDark">#512DA8</item>
        <item name="colorAccent">#FF4081</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>

excel formula to subtract number of days from a date

Here is what worked for me (Excel 14.0 - aka MS Office Pro Plus 2010):

=DATE(YEAR(A1), MONTH(A1), DAY(A1) - 16)

This takes the date (format mm/dd/yyyy) in cell A1 and subtracts 16 days with output in format of mm/dd/yyyy.

mysql said: Cannot connect: invalid settings. xampp

I faced this problem as well but i could fix it by going to the folder /xampp/phpmyadmin/config.inc.php

Open config.inc.php, u will find (if no password) ['password']= '' or (if old password) ['password']= '123'

Change the password $cfg['Servers'][$i]['password'] = 'test' and u will be able to access phpmyadmin again :)

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

Return empty cell from formula in Excel

Yes, it is possible.

It is possible to have a formula returning a trueblank if a condition is met. It passes the test of the ISBLANK formula. The only inconvenience is that when the condition is met, the formula will evaporate, and you will have to retype it. You can design a formula immune to self-destruction by making it return the result to the adjacent cell. Yes, it is also possible. I refer you to this solution at the end of my answer.

enter image description here

All you need is to set up a named range, say GetTrueBlank, and you will be able to use the following pattern just like in your question:

=IF(A1 = "Hello world", GetTrueBlank, A1)

Step 1. Put this code in Module of VBA.

Function Delete_UDF(rng)
    ThisWorkbook.Application.Volatile
    rng.Value = ""
End Function

Step 2. In Sheet1 in A1 cell add named range GetTrueBlank with the following formula:

=EVALUATE("Delete_UDF("&CELL("address",Sheet1!A1)&")")

enter image description here

That's it. There are no further steps. Just use self-annihilating formula. Put in the cell, say B2, the following formula:

=IF(A2=0,GetTrueBlank,A2)

The above formula in B2 will evaluate to trueblank, if you type 0 in A2.

You can download a demonstration file here.

In the example above, evaluating the formula to trueblank results in an empty cell. Checking the cell with ISBLANK formula results positively in TRUE. This is hara-kiri. The formula disappears from the cell when a condition is met. The goal is reached, although you probably might want the formula not to disappear.

You may modify the formula to return the result in the adjacent cell so that the formula will not kill itself. See how to get UDF result in the adjacent cell.

adjacent cell

I have come across the examples of getting a trueblank as a formula result revealed by The FrankensTeam here: https://sites.google.com/site/e90e50/excel-formula-to-change-the-value-of-another-cell

what is difference between success and .done() method of $.ajax

success only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error fires if it fails and complete when the request finishes, regardless of success.

In jQuery 1.8 on the jqXHR object (returned by $.ajax) success was replaced with done, error with fail and complete with always.

However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:

// set success action before making the request
$.ajax({
  url: '...',
  success: function(){
    alert('AJAX successful');
  }
});

// set success action just after starting the request
var jqxhr = $.ajax( "..." )
  .done(function() { alert("success"); });

This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:

$.ajax("parent").
    done(function(p) { return $.ajax("child/" + p.id); }).
    done(someOtherDeferredFunction).
    done(function(c) { alert("success: " + c.name); });

This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success.

However, please note that done is now deprecated in favour of the Promise syntax that uses then instead:

$.ajax("parent").
    then(function(p) { return $.ajax("child/" + p.id); }).
    then(someOtherDeferredFunction).
    then(function(c) { alert("success: " + c.name); }).
    catch(function(err) { alert("error: " + err.message); });

This is worth adopting because async and await extend promises improved syntax (and error handling):

try {
    var p = await $.ajax("parent");
    var x = await $.ajax("child/" + p.id);
    var c = await someOtherDeferredFunction(x);
    alert("success: " + c.name);
}
catch(err) { 
    alert("error: " + err.message); 
}

How to easily initialize a list of Tuples?

    var colors = new[]
    {
        new { value = Color.White, name = "White" },
        new { value = Color.Silver, name = "Silver" },
        new { value = Color.Gray, name = "Gray" },
        new { value = Color.Black, name = "Black" },
        new { value = Color.Red, name = "Red" },
        new { value = Color.Maroon, name = "Maroon" },
        new { value = Color.Yellow, name = "Yellow" },
        new { value = Color.Olive, name = "Olive" },
        new { value = Color.Lime, name = "Lime" },
        new { value = Color.Green, name = "Green" },
        new { value = Color.Aqua, name = "Aqua" },
        new { value = Color.Teal, name = "Teal" },
        new { value = Color.Blue, name = "Blue" },
        new { value = Color.Navy, name = "Navy" },
        new { value = Color.Pink, name = "Pink" },
        new { value = Color.Fuchsia, name = "Fuchsia" },
        new { value = Color.Purple, name = "Purple" }
    };
    foreach (var color in colors)
    {
        stackLayout.Children.Add(
            new Label
            {
                Text = color.name,
                TextColor = color.value,
            });
        FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
    }

this is a Tuple<Color, string>

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

What does DIM stand for in Visual Basic and BASIC?

Variable declaration. Initially, it was short for "dimension", which is not a term that is used in programming (outside of this specific keyword) to any significant degree.

http://in.answers.yahoo.com/question/index?qid=20090310095555AANmiAZ

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this error because such DLL (and many others) were missing in bin folder when I pubished the web application. It seemed like a bug in Visual Studio publish function. Cleaning, recompiling and publishing it again, made such DLLs to be published correctly.

LINQ Group By into a Dictionary Object

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

pandas get column average/mean

You can also access a column using the dot notation (also called attribute access) and then calculate its mean:

df.your_column_name.mean()

Python module for converting PDF to text

Repurposing the pdf2txt.py code that comes with pdfminer; you can make a function that will take a path to the pdf; optionally, an outtype (txt|html|xml|tag) and opts like the commandline pdf2txt {'-o': '/path/to/outfile.txt' ...}. By default, you can call:

convert_pdf(path)

A text file will be created, a sibling on the filesystem to the original pdf.

def convert_pdf(path, outtype='txt', opts={}):
    import sys
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, process_pdf
    from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter, TagExtractor
    from pdfminer.layout import LAParams
    from pdfminer.pdfparser import PDFDocument, PDFParser
    from pdfminer.pdfdevice import PDFDevice
    from pdfminer.cmapdb import CMapDB

    outfile = path[:-3] + outtype
    outdir = '/'.join(path.split('/')[:-1])

    debug = 0
    # input option
    password = ''
    pagenos = set()
    maxpages = 0
    # output option
    codec = 'utf-8'
    pageno = 1
    scale = 1
    showpageno = True
    laparams = LAParams()
    for (k, v) in opts:
        if k == '-d': debug += 1
        elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )
        elif k == '-m': maxpages = int(v)
        elif k == '-P': password = v
        elif k == '-o': outfile = v
        elif k == '-n': laparams = None
        elif k == '-A': laparams.all_texts = True
        elif k == '-D': laparams.writing_mode = v
        elif k == '-M': laparams.char_margin = float(v)
        elif k == '-L': laparams.line_margin = float(v)
        elif k == '-W': laparams.word_margin = float(v)
        elif k == '-O': outdir = v
        elif k == '-t': outtype = v
        elif k == '-c': codec = v
        elif k == '-s': scale = float(v)
    #
    CMapDB.debug = debug
    PDFResourceManager.debug = debug
    PDFDocument.debug = debug
    PDFParser.debug = debug
    PDFPageInterpreter.debug = debug
    PDFDevice.debug = debug
    #
    rsrcmgr = PDFResourceManager()
    if not outtype:
        outtype = 'txt'
        if outfile:
            if outfile.endswith('.htm') or outfile.endswith('.html'):
                outtype = 'html'
            elif outfile.endswith('.xml'):
                outtype = 'xml'
            elif outfile.endswith('.tag'):
                outtype = 'tag'
    if outfile:
        outfp = file(outfile, 'w')
    else:
        outfp = sys.stdout
    if outtype == 'txt':
        device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
    elif outtype == 'xml':
        device = XMLConverter(rsrcmgr, outfp, codec=codec, laparams=laparams, outdir=outdir)
    elif outtype == 'html':
        device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale, laparams=laparams, outdir=outdir)
    elif outtype == 'tag':
        device = TagExtractor(rsrcmgr, outfp, codec=codec)
    else:
        return usage()

    fp = file(path, 'rb')
    process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password)
    fp.close()
    device.close()

    outfp.close()
    return

Typescript empty object for a typed variable

If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

type User = {
    Username?: string;
    Email?: string;
}

How to echo print statements while executing a sql script

What about using mysql -v to put mysql client in verbose mode ?

Ignore case in Python strings

There's no built in equivalent to that function you want.

You can write your own function that converts to .lower() each character at a time to avoid duplicating both strings, but I'm sure it will very cpu-intensive and extremely inefficient.

Unless you are working with extremely long strings (so long that can cause a memory problem if duplicated) then I would keep it simple and use

str1.lower() == str2.lower()

You'll be ok

File upload from <input type="file">

If you have a complex form with multiple files and other inputs here is a solution that plays nice with ngModel.

It consists of a file input component that wraps a simple file input and implements the ControlValueAccessor interface to make it consumable by ngModel. The component exposes the FileList object to ngModel.

This solution is based on this article.

The component is used like this:

<file-input name="file" inputId="file" [(ngModel)]="user.photo"></file-input>
<label for="file"> Select file </label>

Here's the component code:

import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => FileInputComponent),
    multi: true
};

@Component({
  selector: 'file-input',
  templateUrl: './file-input.component.html',
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class FileInputComponent {

  @Input()
  public name:string;

  @Input()
  public inputId:string;

  private innerValue:any;

  constructor() { }

  get value(): FileList {
    return this.innerValue;
  };

  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: FileList) => void = noop;

  set value(v: FileList) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChangeCallback(v);
    }
  }

  onBlur() {
    this.onTouchedCallback();
  }

  writeValue(value: FileList) {
    if (value !== this.innerValue) {
      this.innerValue = value;
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  changeFile(event) {
    this.value = event.target.files;
  }
}

And here's the component template:

<input type="file" name="{{ name }}" id="{{ inputId }}" multiple="multiple" (change)="changeFile($event)"/>

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:

https://stackoverflow.com/a/33481683/1897196

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))
));

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

Creating a LINQ select from multiple tables

change

select op) 

to

select new { op, pg })

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

"You tried to execute a query that does not include the specified aggregate function"

I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By clause at the end.enter image description here

How do I get the AM/PM value from a DateTime?

string.Format("{0:hh:mm:ss tt}", DateTime.Now)

This should give you the string value of the time. tt should append the am/pm.

You can also look at the related topic:

How do you get the current time of day?

Python - Create list with numbers between 2 values?

Try:

range(x1,x2+1)  

That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:

list(range(x1,x2+1))

chrome undo the action of "prevent this page from creating additional dialogs"

2 more solutions I had luck with when neither tab close + reopening the page in another tab nor closing all tabs in Chrome (and the browser) then restarting it didn't work:

1) I fixed it on my machine by closing the tab, force-closing Chrome, & restarting the browser without restoring tabs (Note: on a computer running CentOS Linux).

2) My boss (also on CentOS) had the same issue (alerts are a big part of my company's Javascript debugging process for numerous reasons e.g. legacy), but my 1st method didn't work for him. However, I managed to fix it for him with the following process:

  • a) Make an empty text file called FixChrome.sh, and paste in the following bash script:

    #! /bin/bash
    cd ~/.config/google-chrome/Default     //adjust for your Chrome install location
    rm Preferences
    rm 'Current Session'
    rm 'Current Tabs'
    rm 'Last Session'
    rm 'Last Tabs'
    
  • b) close Chrome, then open Terminal and run the script (bash FixChrome.sh).

It worked for him. Downside is that you lose all tabs from your current & previous session, but it's worth it if this matters to you.

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

Connecting to TCP Socket from browser using javascript

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

It should work like this

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads

Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

How to restart remote MySQL server running on Ubuntu linux?

sudo service mysql stop;
sudo service mysql start;

If the above process will not work let's check one the given code above you can stop Mysql server and again start server

Adding whitespace in Java

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

How can I list ALL DNS records?

When you query for ANY you will get a list of all records at that level but not below.

# try this
dig google.com any

This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly "google.com". However, it will not return child records (e.g., www.google.com). More precisely, you MAY get these records if they exist. The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response).

An AXFR is a zone transfer and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).

# This will return "Transfer failed"
dig @ns1.google.com google.com axfr

If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the the client can send to the server to authorize the transfer.

Video format or MIME type is not supported

For Ubuntu 14.04

Just removed the package Oxideqt-dodecs then install flash or ubuntu restricted extras

and you are good to go!!

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Notification Icon with the new Firebase Cloud Messaging system

There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.

There is method:

private void zzo(Intent intent) {
    Bundle bundle = intent.getExtras();
    bundle.remove("android.support.content.wakelockid");
    if (zza.zzac(bundle)) {  // true if msg is notification sent from FirebaseConsole
        if (!zza.zzdc((Context)this)) { // true if app is on foreground
            zza.zzer((Context)this).zzas(bundle); // create notification
            return;
        }
        // parse notification data to allow use it in onMessageReceived whe app is on foreground
        if (FirebaseMessagingService.zzav(bundle)) {
            zzb.zzo((Context)this, intent);
        }
    }
    this.onMessageReceived(new RemoteMessage(bundle));
}

This code is from version 9.4.0, method will have different names in different version because of obfuscation.

How do I get the last four characters from a string in C#?

Suggest using TakeLast method, for example: new String(text.TakeLast(4).ToArray())

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

EDIT: Thanks for the comments - I looked it up in the C99 standard, which says in section 6.5.3.4:

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers)

So, the size of size_t is not specified, only that it has to be an unsigned integer type. However, an interesting specification can be found in chapter 7.18.3 of the standard:

limit of size_t

SIZE_MAX 65535

Which basically means that, irrespective of the size of size_t, the allowed value range is from 0-65535, the rest is implementation dependent.

CSS text-overflow: ellipsis; not working?

I faced the same issue and it seems like none of the solution above works for Safari. For non-safari browser, this works just fine:

display: block; /* or in-line block according to your requirement */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

For Safari, this is the one that works for me. Note that the media query to check if the browser is Safari might change over time, so just tinker with the media query if it doesn't work for you. With line-clamp property, it would also be possible to have multiple lines in the web with ellipsis, see here.

// Media-query for Safari-only browser.
@media not all and (min-resolution: 0.001dpcm) {
  @media {
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    white-space: normal;
  }
}

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How to send only one UDP packet with netcat?

I did not find the -q1 option on my netcat. Instead I used the -w1 option. Below is the bash script I did to send an udp packet to any host and port:

#!/bin/bash

def_host=localhost
def_port=43211

HOST=${2:-$def_host}
PORT=${3:-$def_port}

echo -n "$1" | nc -4u -w1 $HOST $PORT

How to check sbt version?

sbt about then enter to get SBT version

enter image description here

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I am much late to the party but today I faced the same error and how I resolved was simple. My scenario was similar to this given code I was making DB transactions inside of nested for-each loops.

The problem is as a Single DB transaction takes a little bit time longer than for-each loop so once the earlier transaction is not complete then the new traction throws an exception, so the solution is to create a new object in the for-each loop where you are making a db transaction.

For the above mentioned scenarios the solution will be like this:

foreach (RivWorks.Model.Negotiation.AutoNegotiationDetails companyFeedDetail in companyFeedDetailList)
                {
private RivWorks.Model.Negotiation.RIV_Entities _dbRiv = RivWorks.Model.Stores.RivEntities(AppSettings.RivWorkEntities_connString);
                    if (companyFeedDetail.FeedSourceTable.ToUpper() == "AUTO")
                    {
                        var company = (from a in _dbRiv.Company.Include("Product") where a.CompanyId == companyFeedDetail.CompanyId select a).First();
                        foreach (RivWorks.Model.NegotiationAutos.Auto sourceProduct in client.Auto)
                        {
                            foreach (RivWorks.Model.Negotiation.Product targetProduct in company.Product)
                            {
                                if (targetProduct.alternateProductID == sourceProduct.AutoID)
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                var newProduct = new RivWorks.Model.Negotiation.Product();
                                newProduct.alternateProductID = sourceProduct.AutoID;
                                newProduct.isFromFeed = true;
                                newProduct.isDeleted = false;
                                newProduct.SKU = sourceProduct.StockNumber;
                                company.Product.Add(newProduct);
                            }
                        }
                        _dbRiv.SaveChanges();  // ### THIS BREAKS ### //
                    }
                }

How add unique key to existing table (with non uniques rows)

You can do as yAnTar advised

ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY

OR

You can add a constraint

ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)

But I think to not lose your existing data, you can add an indentity column and then make a composite key.

MySQL - select data from database between two dates

SELECT users.* FROM users WHERE created_at BETWEEN '2011-12-01' AND '2011-12-07';

Get last 30 day records from today date in SQL Server

I dont know why all these complicated answers are on here but this is what I would do

where pdate >= CURRENT_TIMESTAMP -30

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

Non-static variable cannot be referenced from a static context

  • The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.

  • Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class

  • As a corollary to the above

    1. variables within a method can not be static
    2. static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
  • The lifetime of a static field/method is equivalent to the lifetime of your application

E.g. Say, car has the property colour, and exhibits the behaviour 'motion'. An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.

Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.

HTH

convert ArrayList<MyCustomClass> to JSONArray

As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

Pandas groupby: How to get a union of strings

Following @Erfan's good answer, most of the times in an analysis of aggregate values you want the unique possible combinations of these existing character values:

unique_chars = lambda x: ', '.join(x.unique())
(df
 .groupby(['A'])
 .agg({'C': unique_chars}))

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

How to switch to new window in Selenium for Python?

for eg. you may take

driver.get('https://www.naukri.com/')

since, it is a current window ,we can name it

main_page = driver.current_window_handle

if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index

for handle in driver.window_handles:
    if handle != main_page:
        print(handle)
        login_page = handle
        break

driver.switch_to.window(login_page)

Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done

driver.switch_to.window(main_page)
sleep(10)

Pass data to layout that are common to all pages

Another option is to create a separate LayoutModel class with all the properties you will need in the layout, and then stuff an instance of this class into ViewBag. I use Controller.OnActionExecuting method to populate it. Then, at the start of layout you can pull this object back from ViewBag and continue to access this strongly typed object.

How to remove unused dependencies from composer?

following commands will do the same perfectly

rm -rf vendor

composer install 

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

Regular Expression to match string starting with a specific word

If you want to match anything after a word stop an not only at the start of the line you may use : \bstop.*\b - word followed by line

Word till the end of string

Or if you want to match the word in the string use \bstop[a-zA-Z]* - only the words starting with stop

Only the words starting with stop

Or the start of lines with stop ^stop[a-zA-Z]* for the word only - first word only
The whole line ^stop.* - first line of the string only

And if you want to match every string starting with stop including newlines use : /^stop.*/s - multiline string starting with stop

Position absolute and overflow hidden

Make outer <div> to position: relative and inner <div> to position: absolute. It should work for you.

How can I prevent the backspace key from navigating back?

Combining solutions given by "thetoolman" && "Biff MaGriff"

following code seems to work correctly in IE 8/Mozilla/Chrome

$(function () {
    var rx = /INPUT|TEXTAREA/i;
    var rxT = /RADIO|CHECKBOX|SUBMIT/i;

    $(document).bind("keydown keypress", function (e) {
        var preventKeyPress;
        if (e.keyCode == 8) {
            var d = e.srcElement || e.target;
            if (rx.test(e.target.tagName)) {
                var preventPressBasedOnType = false;
                if (d.attributes["type"]) {
                    preventPressBasedOnType = rxT.test(d.attributes["type"].value);
                }
                preventKeyPress = d.readOnly || d.disabled || preventPressBasedOnType;
            } else {preventKeyPress = true;}
        } else { preventKeyPress = false; }

        if (preventKeyPress) e.preventDefault();
    });
}); 

Email address validation using ASP.NET MVC data type attributes

If you are using .NET Framework 4.5, the solution is to use EmailAddressAttribute which resides inside System.ComponentModel.DataAnnotations.

Your code should look similar to this:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

Dynamically updating plot in matplotlib

In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw alone does not produce the plot (at least with the qt backend).

The following works for me:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

Python: How to keep repeating a program until a specific input is obtained?

Easier way:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

Loaded nib but the 'view' outlet was not set

The View Identity - Class Identity was not set. After setting it to the appropriate class, the issue was resolved.

How to change Screen buffer size in Windows Command Prompt from batch script

I created the following utility to set the console size and scroll buffers.

I compiled it using DEV C++ (http://www.bloodshed.net/devcpp.html).

An executable is included in https://sourceforge.net/projects/wa2l-wintools/.

#include <iostream>
#include <windows.h> 

using namespace std;


// SetWindow(Width,Height,WidthBuffer,HeightBuffer) -- set console size and buffer dimensions
//
void SetWindow(int Width, int Height, int WidthBuffer, int HeightBuffer) { 
    _COORD coord; 
    coord.X = WidthBuffer; 
    coord.Y = HeightBuffer; 

    _SMALL_RECT Rect; 
    Rect.Top = 0; 
    Rect.Left = 0; 
    Rect.Bottom = Height - 1; 
    Rect.Right = Width - 1; 

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);      // Get Handle 
    SetConsoleScreenBufferSize(Handle, coord);            // Set Buffer Size 
    SetConsoleWindowInfo(Handle, TRUE, &Rect);            // Set Window Size 
}  // SetWindow



// main(Width,Height,WidthBuffer,HeightBuffer) -- main
//
int main(int argc, char *argv[]) {     
    int width = 80;
    int height = 25;
    int wbuffer = width + 200;
    int hbuffer = height + 1000;

    if ( argc == 5 ){
        width = atoi(argv[1]);
        height = atoi(argv[2]);
        wbuffer = atoi(argv[3]);
        hbuffer = atoi(argv[4]);
    } else if ( argc > 1 ) {
        cout << "Usage: " << argv[0] << " [ width height bufferwidth bufferheight ]" << endl << endl;
        cout << "  Where" << endl;
        cout << "    width            console width" << endl;
        cout << "    height           console height" << endl;
        cout << "    bufferwidth      scroll buffer width" << endl;
        cout << "    bufferheight     scroll buffer height" << endl;
        return 4;
    }    

    SetWindow(width,height,wbuffer,hbuffer);
    return 0;
} 

How can I get the source directory of a Bash script from within the script itself?

The following will return the current directory of the script

  • works if it's sourced, or not sourced
  • works if run in the current directory, or some other directory.
  • works if relative directories are used.
  • works with bash, not sure of other shells.
/tmp/a/b/c $ . ./test.sh
/tmp/a/b/c

/tmp/a/b/c $ . /tmp/a/b/c/test.sh
/tmp/a/b/c

/tmp/a/b/c $ ./test.sh
/tmp/a/b/c

/tmp/a/b/c $ /tmp/a/b/c/test.sh
/tmp/a/b/c

/tmp/a/b/c $ cd

~ $ . /tmp/a/b/c/test.sh
/tmp/a/b/c

~ $ . ../../tmp/a/b/c/test.sh
/tmp/a/b/c

~ $ /tmp/a/b/c/test.sh
/tmp/a/b/c

~ $ ../../tmp/a/b/c/test.sh
/tmp/a/b/c

test.sh

#!/usr/bin/env bash

# snagged from: https://stackoverflow.com/a/51264222/26510
function toAbsPath {
    local target
    target="$1"

    if [ "$target" == "." ]; then
        echo "$(pwd)"
    elif [ "$target" == ".." ]; then
        echo "$(dirname "$(pwd)")"
    else
        echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
    fi
}

function getScriptDir(){
  local SOURCED
  local RESULT
  (return 0 2>/dev/null) && SOURCED=1 || SOURCED=0

  if [ "$SOURCED" == "1" ]
  then
    RESULT=$(dirname "$1")
  else
    RESULT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
  fi
  toAbsPath "$RESULT"
}

SCRIPT_DIR=$(getScriptDir "$0")
echo "$SCRIPT_DIR"

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

Change the image source on rollover using jQuery

$('img').mouseover(function(){
  var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
  $(this).attr("src", newSrc); 
});
$('img').mouseout(function(){
  var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
  $(this).attr("src", newSrc); 
});

Can you put two conditions in an xslt test attribute?

From XML.com:

Like xsl:if instructions, xsl:when elements can have more elaborate contents between their start- and end-tags—for example, literal result elements, xsl:element elements, or even xsl:if and xsl:choose elements—to add to the result tree. Their test expressions can also use all the tricks and operators that the xsl:if element's test attribute can use, such as and, or, and function calls, to build more complex boolean expressions.

How to vertically center a "div" element for all browsers using CSS?

The simplest way would be the following 3 lines of CSS:

1) position: relative;

2) top: 50%;

3) transform: translateY(-50%);

Following is an EXAMPLE:

_x000D_
_x000D_
div.outer-div {_x000D_
  height: 170px;_x000D_
  width: 300px;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
div.middle-div {_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  -webkit-transform: translateY(-50%);_x000D_
  -ms-transform: translateY(-50%);_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<div class='outer-div'>_x000D_
  <div class='middle-div'>_x000D_
    Test text_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to split a comma-separated string?

In Kotlin,

val stringArray = commasString.replace(", ", ",").split(",")

where stringArray is List<String> and commasString is String with commas and spaces

What is the difference between document.location.href and document.location?

document.location is an object, while document.location.href is a string. But the former has a toString method, so you can read from it as if it was a string and get the same value as document.location.href.

In some browsers - most modern ones, I think - you can also assign to document.location as if it were a string. According to the Mozilla documentation however, it is better to use window.location for this purpose as document.location was originally read-only and so may not be as widely supported.

How can I set the initial value of Select2 when using AJAX?

The issue of being forced to trigger('change') drove me nuts, as I had custom code in the change trigger, which should only trigger when the user changes the option in the dropdown. IMO, change should not be triggered when setting an init value at the start.

I dug deep and found the following: https://github.com/select2/select2/issues/3620

Example:

$dropDown.val(1).trigger('change.select2');

Check if boolean is true?

Both are correct.

You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

jQuery lose focus event

blur event: when the element loses focus.

focusout event: when the element, or any element inside of it, loses focus.

As there is nothing inside the filter element, both blur and focusout will work in this case.

$(function() {
  $('#filter').blur(function() {
    $('#options').hide();
  });
})

jsfiddle with blur: http://jsfiddle.net/yznhb8pc/

$(function() {
  $('#filter').focusout(function() {
    $('#options').hide();
  });
})

jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/

Hibernate show real SQL

select this_.code from true.employee this_ where this_.code=? is what will be sent to your database.

this_ is an alias for that instance of the employee table.

Conditional logic in AngularJS template

You could use the ngSwitch directive:

  <div ng-switch on="selection" >
    <div ng-switch-when="settings">Settings Div</div>
    <span ng-switch-when="home">Home Span</span>
    <span ng-switch-default>default</span>
  </div>

If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.

This is just an (untested) example. It can and should be optimized:

HTML:

<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>

Directive:

app.directive('conditionalTemplate', function($http, $compile) {
   return {
      restrict: 'E',
      require: '^ngModel',
      link: function(sope, element, attrs, ctrl) {
        // get template with $http
        // check model via ctrl.$viewValue
        // compile with $compile
        // replace element with element.replaceWith()
      }
   };
});

CSS two divs next to each other

You can use flexbox to lay out your items:

_x000D_
_x000D_
#parent {_x000D_
  display: flex;_x000D_
}_x000D_
#narrow {_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
  /* Just so it's visible */_x000D_
}_x000D_
#wide {_x000D_
  flex: 1;_x000D_
  /* Grow to rest of container */_x000D_
  background: lightgreen;_x000D_
  /* Just so it's visible */_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.


For older browser support, you can use CSS float and a width properties to solve it.

_x000D_
_x000D_
#narrow {_x000D_
  float: right;_x000D_
  width: 200px;_x000D_
  background: lightblue;_x000D_
}_x000D_
#wide {_x000D_
  float: left;_x000D_
  width: calc(100% - 200px);_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="wide">Wide (rest of width)</div>_x000D_
  <div id="narrow">Narrow (200px)</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I rename column in laravel using migration?

You need to create another migration file - and place it in there:

Run

Laravel 4:    php artisan migrate:make rename_stnk_column
Laravel 5:    php artisan make:migration rename_stnk_column

Then inside the new migration file place:

class RenameStnkColumn extends Migration
{

    public function up()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id', 'id_stnk');
        });
    }


    public function down()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id_stnk', 'id');
        });
    }

}

Finding what branch a Git commit came from

I think someone should face the same problem that can't find out the branch, although it actually exists in one branch.

You'd better pull all first:

git pull --all

Then do the branch search:

git name-rev <SHA>

or:

git branch --contains <SHA>

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Javascript loading CSV file into an array

This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.

$(document).ready(function() {
   "use strict";
    $.ajax({
        type: "GET",
        url: "../files/icd10List.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(icd10Codes) {
    "use strict";
    var input = $.csv.toArrays(icd10Codes);
    $("#test").append(input);
}

Used the jQuery-CSV Plug-in linked above.

VueJS conditionally add an attribute for an element

You can pass boolean by coercing it, put !! before the variable.

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

But I would like to pull your attention for the following case where the receiving component has defined type for props. In that case, if isRequired has defined type to be string then passing boolean make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined fallback and the prop will not sent to component

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

Explanation

I have been through the same problem, and tried above solutions !! Yes, I don't see the prop but that actually does not fulfils what required here.

My problem -

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

In the above case, what I expected is not having my-prop get passed to the child component - <any-conponent/> I don't see the prop in DOM but In my <any-component/> component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop to be a String but it is boolean.

myProp : {
 type: String,
 required: false,
 default: ''
}

Which means that child component did receive the prop even if it is false. Tweak here is to let the child component to take the default-value and also skip the check. Passed undefined works though!

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

This works and my child prop is having the default value.

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

How to install bcmath module?

apt repo have this extension, just run the below command from your terminal ::

sudo apt-get install php7.2-bcmath*

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

When incrementing time you should convert back to UTC and then add or subtract. Use the local time only for display.

This way you will be able to walk through any periods where hours or minutes happen twice.

If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.

How to scroll to an element inside a div?

To scroll an element into view of a div, only if needed, you can use this scrollIfNeeded function:

_x000D_
_x000D_
function scrollIfNeeded(element, container) {_x000D_
  if (element.offsetTop < container.scrollTop) {_x000D_
    container.scrollTop = element.offsetTop;_x000D_
  } else {_x000D_
    const offsetBottom = element.offsetTop + element.offsetHeight;_x000D_
    const scrollBottom = container.scrollTop + container.offsetHeight;_x000D_
    if (offsetBottom > scrollBottom) {_x000D_
      container.scrollTop = offsetBottom - container.offsetHeight;_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', ev => {_x000D_
  ev.preventDefault();_x000D_
  scrollIfNeeded(document.getElementById('goose'), document.getElementById('container'));_x000D_
});
_x000D_
.scrollContainer {_x000D_
  overflow-y: auto;_x000D_
  max-height: 100px;_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  width: 120px;_x000D_
}_x000D_
_x000D_
body {_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.box {_x000D_
  margin: 5px;_x000D_
  background-color: yellow;_x000D_
  height: 25px;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
#goose {_x000D_
  background-color: lime;_x000D_
}
_x000D_
<div id="container" class="scrollContainer">_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div id="goose" class="box">goose</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
</div>_x000D_
_x000D_
<button id="btn">scroll to goose</button>
_x000D_
_x000D_
_x000D_

Threads vs Processes in Linux

The decision between thread/process depends a little bit on what you will be using it to. One of the benefits with a process is that it has a PID and can be killed without also terminating the parent.

For a real world example of a web server, apache 1.3 used to only support multiple processes, but in in 2.0 they added an abstraction so that you can swtch between either. Comments seems to agree that processes are more robust but threads can give a little bit better performance (except for windows where performance for processes sucks and you only want to use threads).

map vs. hash_map in C++

They are implemented in very different ways.

hash_map (unordered_map in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.

map is implemented as a balanced binary search tree (usually a red/black tree).

An unordered_map should give slightly better performance for accessing known elements of the collection, but a map will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map will be faster on insert and delete than a map.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

Accessing the index in 'for' loops?

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:

So do this:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

phpmyadmin.pma_table_uiprefs doesn't exist

I had the same problem with latest Lampp with MariaDB on Ubuntu Server 14.04, and @iceberg's solution worked very well:

You just change following line in /etc/phpmyadmin/config.inc.php

$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

to

$ cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = ‘pma__table_uiprefs’;

And restart apache server with command,

sudo service apache2 restart

Lampp config.inc.php is located in /opt/lampp/phpmyadmin/config.inc.php and to make it work, I also needed to change

$ cfg ['Servers'] [$ i] ['tracking'] = ‘pma__tracking’;

to

$ cfg ['Servers'] [$ i] ['pma__tracking'] = ‘pma__tracking’;

and restart the lampp:

sudo /opt/lampp/lampp stop
sudo /opt/lampp/lampp start

line breaks in a textarea

<?php
$smarty = new Smarty;
$smarty->assign('test', "This is a \n Test");
$smarty->display('index.tpl');
?>

In index.tpl

{$test|nl2br}

In HTML

This is a<br />
test

How to generate the whole database script in MySQL Workbench?

Try the export function of phpMyAdmin.

I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.

Why catch and rethrow an exception in C#?

Most of answers talking about scenario catch-log-rethrow.

Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and IncludeThisArgument

Presto SQL - Converting a date string to date format

date_format requires first argument as timestamp so not the best way to convert a string. Use date_parse instead.

Also, use %c for non zero-padded month, %e for non zero-padded day of the month and %Y for four digit year.

SELECT date_parse('7/22/2016 6:05:04 PM', '%c/%e/%Y %r')

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

Adding this intent filter to one of the activities declared in app manifest fixed this for me.

<activity
    android:name=".MyActivity"
    android:screenOrientation="portrait"
    android:label="@string/app_name">

    <intent-filter>

       <action android:name="android.intent.action.VIEW" />

    </intent-filter>

</activity>