Programs & Examples On #Tla+

TLA+ is a language and toolchain for specifications based on TLA, the Temporal Logic of Actions. The TLA Toolbox includes a translator from PlusCal to TLA+, the TLC model checker, and an IDE.

Creating a Plot Window of a Particular Size

As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:

If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.

Java "user.dir" property - what exactly does it mean?

user.dir is the "User working directory" according to the Java Tutorial, System Properties

How do I see all foreign keys to a table or column?

If you use InnoDB and defined FK's you could query the information_schema database e.g.:

SELECT * FROM information_schema.TABLE_CONSTRAINTS 
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' 
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

How do I read configuration settings from Symfony2 config.yml?

In order to be able to expose some configuration parameters for your bundle you should consult the documentation for doing so. It's fairly easy to do :)

Here's the link: How to expose a Semantic Configuration for a Bundle

How to add a column in TSQL after a specific column?

You have to rebuild the table. Luckily, the order of the columns doesn't matter at all!

Watch as I magically reorder your columns:

SELECT ID, Newfield, FieldA, FieldB FROM MyTable

Also this has been asked about a bazillion times before.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

After trying different things. This worked.

Delete your node modules folder and run

npm i

Full Screen DialogFragment in Android

In case anyone else comes across this, I had a similar experience to this but it turns out that the issue was that I had forgotten to return the inflated view from onCreateView (instead returning the default super.onCreateView). I simply returned the correct inflated view and that solved the problem.

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

Validation of file extension before uploading file

This is the best solution in my opinion, which is by far much shorter than the other ones:

function OnSelect(e) {
    var acceptedFiles = [".jpg", ".jpeg", ".png", ".gif"];
    var isAcceptedImageFormat = ($.inArray(e.files[0].extension, acceptedFiles)) != -1;

    if (!isAcceptedImageFormat) {
        $('#warningMessage').show();
    }
    else {
        $('#warningMessage').hide();
    }
}

In this case, the function is called from a Kendo Upload control with this setting:

.Events(e => e.Select("OnSelect")).

Setting up Gradle for api 26 (Android)

you must add in your MODULE-LEVEL build.gradle file with:

//module-level build.gradle file
repositories {
    maven {
        url 'https://maven.google.com'

    }
}

see: Google's Maven repository

I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:

//project-level build.gradle file
allprojects {
 repositories {
    jcenter()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
  }
}

UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0

Call method in directive controller from other controller

You can also use events to trigger the Popdown.

Here's a fiddle based on satchmorun's solution. It dispenses with the PopdownAPI, and the top-level controller instead $broadcasts 'success' and 'error' events down the scope chain:

$scope.success = function(msg) { $scope.$broadcast('success', msg); };
$scope.error   = function(msg) { $scope.$broadcast('error', msg); };

The Popdown module then registers handler functions for these events, e.g:

$scope.$on('success', function(event, msg) {
    $scope.status = 'success';
    $scope.message = msg;
    $scope.toggleDisplay();
});

This works, at least, and seems to me to be a nicely decoupled solution. I'll let others chime in if this is considered poor practice for some reason.

Displaying the Error Messages in Laravel after being Redirected from controller

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

Instantiating a generic class in Java

And this is the Factory implementation, as Jon Skeet suggested:

interface Factory<T> {
    T factory();
}

class Araba {
    //static inner class for Factory<T> implementation
    public static class ArabaFactory implements Factory<Araba> {
        public Araba factory() {
            return new Araba();
        }
    }
    public String toString() { return "Abubeee"; }
}

class Generic<T> {
    private T var;

    Generic(Factory<T> fact) {
        System.out.println("Constructor with Factory<T> parameter");
        var = fact.factory();
    }
    Generic(T var) {
        System.out.println("Constructor with T parameter");
        this.var = var;
    }
    T get() { return var; }
}

public class Main {
    public static void main(String[] string) {
        Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
        System.out.print(gen.get());
    }
}

Output:

Constructor with Factory<T> parameter
Abubeee

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

Installing packages in Sublime Text 2

You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).

Then please check Package Docs Control Usage for Basic Functionality:

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

The command pallete will now show a number of commands. Most users will be interested in the following:

Install Package

Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.

How to Store Historical Data

In SQL Server 2016 and above, there is a new feature called Temporal Tables that aims to solve this challenge with minimal effort from developer. The concept of temporal table is similar to Change Data Capture (CDC), with the difference that temporal table has abstracted most of the things that you had to do manually if you were using CDC.

How to remove files from git staging area?

If you've already committed a bunch of unwanted files, you can unstage them and tell git to mark them as deleted (without actually deleting them) with

git rm --cached -r .

--cached tells it to remove the paths from staging and the index without removing the files themselves and -r operates on directories recursively. You can then git add any files that you want to keep tracking.

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

Check if a specific tab page is selected (active)

I think that using the event tabPage1.Enter is more convenient.

tabPage1.Enter += new System.EventHandler(tabPage1_Enter);

private void tabPage1_Enter(object sender, EventArgs e)
{
    MessageBox.Show("you entered tabPage1");
}

This is better than having nested if-else statement when you have different logic for different tabs. And more suitable in case new tabs may be added in the future.

Note that this event fires if the form loads and tabPage1 is opened by default.

Add CSS class to a div in code behind

To ADD classes to html elements see how to add css class to html generic control div?. There are answers similar to those given here but showing how to add classes to html elements.

What is the point of WORKDIR on Dockerfile?

Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.

FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]

We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish

FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]

So it acts like a cd and sets the tone for the upcoming statements.

How to convert index of a pandas dataframe into a column?

df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123

Where is debug.keystore in Android Studio

The default keystore file: debug.keystore is present in the folder .android which is usually located in the default home folder of your operating system of the user who installed that Android SDK.

In my Ubuntu PC, it's location is /home/dhananjay/.android

Whereas in the Windows PC it is located at C:\Users\dhananjay\.android

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

I read all answers that said: No, Swift does not work with less than iOS 7. But I said YES, I just created a Swift project that does run in Xcode 5 with 6.0 deployment target.

  • I just create a demo project in Xcode 6 BETA with the Swift programming language selected.
  • Close Xcode 6 beta, and I open this demo project in Xcode 5 with deployment target 6.0
  • And also select simulator 6.1.

Then that project runs well in simulator 6.1. My MacOS X is 10.9.3, so I said yes, that runs in lower than iOS 7. with 10.9.3 Mac OS X.

Here it is a screenshot of the simulator:

Enter image description here

Here is a demo as well

Validate date in dd/mm/yyyy format using JQuery Validate

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

So the simplest way is,

alter table table_name change column_name column_name int(11) NULL;

How to get root access on Android emulator?

I just replaced and assigned attributes for su to ~/Android/Sdk/system-images/android-22/google_apis/x86/system.img and now on android 5 I always have root even for new systems, it’s enough to install SuperSu.apk

Android 6 is necessary only
adb root
adb shell
>/system/xbin/su --daemon &
>setenfoce 0

after that, SuperSu.apk sees root. But I do not update the binary file

What is the best way to dump entire objects to a log in C#?

You could use Visual Studio Immediate Window

Just paste this (change actual to your object name obviously):

Newtonsoft.Json.JsonConvert.SerializeObject(actual);

It should print object in JSON enter image description here

You should be able to copy it over textmechanic text tool or notepad++ and replace escaped quotes (\") with " and newlines (\r\n) with empty space, then remove double quotes (") from beginning and end and paste it to jsbeautifier to make it more readable.

UPDATE to OP's comment

public static class Dumper
{
    public static void Dump(this object obj)
    {
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); // your logger
    }
}

this should allow you to dump any object.

Hope this saves you some time.

How to get name of calling function/method in PHP?

Best answer of that question I've seen is:

list(, $caller) = debug_backtrace(false);

Short and clean

How do I remove an array item in TypeScript?

let a: number[] = [];

a.push(1);
a.push(2);
a.push(3);

let index: number = a.findIndex(a => a === 1);

if (index != -1) {
    a.splice(index, 1);
}

console.log(a);

Why can't I see the "Report Data" window when creating reports?

If the report designer is opened, Report Data Pane can be enabled using view menu.

 View -> Report Data

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

SQL Server: Maximum character length of object names

You can also use this script to figure out more info:

EXEC sp_server_info

The result will be something like that:

attribute_id | attribute_name        | attribute_value
-------------|-----------------------|-----------------------------------
           1 | DBMS_NAME             | Microsoft SQL Server
           2 | DBMS_VER              | Microsoft SQL Server 2012 - 11.0.6020.0
          10 | OWNER_TERM            | owner
          11 | TABLE_TERM            | table
          12 | MAX_OWNER_NAME_LENGTH | 128
          13 | TABLE_LENGTH          | 128
          14 | MAX_QUAL_LENGTH       | 128
          15 | COLUMN_LENGTH         | 128
          16 | IDENTIFIER_CASE       | MIXED
           ?  ?                       ?
           ?  ?                       ?
           ?  ?                       ?

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

How to configure Fiddler to listen to localhost?

Rather than configure the application server and client to use another domain, you may want to configure the client application to use a proxy. Fiddler also creates a proxy you can use, logging all traffic. Rick Strahl blogged about using this in .NET Apps, I am always misplacing this blog post, so let me link it here: http://weblog.west-wind.com/posts/2008/Mar/14/Debugging-Http-or-Web-Services-Calls-from-ASPNET-with-Fiddler.

To be brief, the app.config change is:

<system.net>
  <defaultProxy>
    <proxy  proxyaddress="http://127.0.0.1:8888" />      
  </defaultProxy>
</system.net>

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

How do you read CSS rule values with JavaScript?

Some browser differences to be aware of:

Given the CSS:

div#a { ... }
div#b, div#c { ... }

and given InsDel's example, classes will have 2 classes in FF and 3 classes in IE7.

My example illustrates this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style>
    div#a { }
    div#b, div#c { }
    </style>
    <script>
    function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<rules.length;x++) {
            document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
        }
    }
    </script>
</head>
<body>
    <input onclick="PrintRules()" type="button" value="Print Rules" /><br />
    RULES:
    <div id="rules"></div>
</body>
</html>

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:

collect($items)->sum('amount');

This will give you the sum total of all the items.

How to create and download a csv file from php script?

That is the function that I used for my project, and it works as expected.

function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '";' );

    // clean output buffer
    ob_end_clean();

    $handle = fopen( 'php://output', 'w' );

    // use keys as column titles
    fputcsv( $handle, array_keys( $array['0'] ) );

    foreach ( $array as $value ) {
        fputcsv( $handle, $value , $delimiter );
    }

    fclose( $handle );

    // flush buffer
    ob_flush();

    // use exit to get rid of unexpected output afterward
    exit();
}

How to sort an array of ints using a custom comparator?

I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.

public class ArrSortComptr {
    public static void main(String[] args) {

         int[] array = { 3, 2, 1, 5, 8, 6 };
         int[] sortedArr=SortPrimitiveInt(new intComp(),array);
         System.out.println("InPut "+ Arrays.toString(array));
         System.out.println("OutPut "+ Arrays.toString(sortedArr));

    }
 static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
 {
    Integer[] objInt=intToObject(arr);
    Arrays.sort(objInt,com);
    return intObjToPrimitive(objInt);

 }
 static Integer[] intToObject(int ... arr)
 {
    Integer[] a=new Integer[arr.length];
    int cnt=0;
    for(int val:arr)
      a[cnt++]=new Integer(val);
    return a;
 }
 static int[] intObjToPrimitive(Integer ... arr)
 {
     int[] a=new int[arr.length];
     int cnt=0;
     for(Integer val:arr)
         if(val!=null)
             a[cnt++]=val.intValue();
     return a;

 }

}
class intComp implements Comparator<Integer>
{

    @Override //your comparator implementation.
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        return o1.compareTo(o2);
    }

}

@Roman: I can't say that this is a good example but since you asked this is what came to my mind. Suppose in an array you want to sort number's just based on their absolute value.

Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);

Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

What is the difference between dynamic and static polymorphism in Java?

Binding refers to the link between method call and method definition.

This picture clearly shows what is binding.

binding

In this picture, “a1.methodOne()” call is binding to corresponding methodOne() definition and “a1.methodTwo()” call is binding to corresponding methodTwo() definition.

For every method call there should be proper method definition. This is a rule in java. If compiler does not see the proper method definition for every method call, it throws error.

Now, come to static binding and dynamic binding in java.

Static Binding In Java :

Static binding is a binding which happens during compilation. It is also called early binding because binding happens before a program actually runs

.

Static binding can be demonstrated like in the below picture.

enter image description here

In this picture, ‘a1’ is a reference variable of type Class A pointing to object of class A. ‘a2’ is also reference variable of type class A but pointing to object of Class B.

During compilation, while binding, compiler does not check the type of object to which a particular reference variable is pointing. It just checks the type of reference variable through which a method is called and checks whether there exist a method definition for it in that type.

For example, for “a1.method()” method call in the above picture, compiler checks whether there exist method definition for method() in Class A. Because ‘a1' is Class A type. Similarly, for “a2.method()” method call, it checks whether there exist method definition for method() in Class A. Because ‘a2' is also Class A type. It does not check to which object, ‘a1’ and ‘a2’ are pointing. This type of binding is called static binding.

Dynamic Binding In Java :

Dynamic binding is a binding which happens during run time. It is also called late binding because binding happens when program actually is running.

During run time actual objects are used for binding. For example, for “a1.method()” call in the above picture, method() of actual object to which ‘a1’ is pointing will be called. For “a2.method()” call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is called dynamic binding.

The dynamic binding of above example can be demonstrated like below.

enter image description here

Reference static-binding-and-dynamic-binding-in-java

How to count the number of lines of a string in javascript

I made a performance test comparing split with regex, with a string and doing it with a for loop.

It seems that the for loop is the fastest.

NOTE: this code 'as is' is not useful for windows nor macos endline, but should be ok to compare performance.

Split with string:

split('\n').length;

Split with regex:

split(/\n/).length;

Split using for:

var length = 0;
for(var i = 0; i < sixteen.length; ++i)
  if(sixteen[i] == s)
    length++;

http://jsperf.com/counting-newlines/2

How to loop through an associative array and get the key?

You can do:

foreach ($arr as $key => $value) {
 echo $key;
}

As described in PHP docs.

ASP.NET Identity DbContext confusion

There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
" Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"

To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:

/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
    where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
    where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
    where TKey : IEquatable<TKey>
    where TUserClaim : IdentityUserClaim<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserLogin : IdentityUserLogin<TKey>
    where TRoleClaim : IdentityRoleClaim<TKey>
    where TUserToken : IdentityUserToken<TKey>
{
    /// <summary>
    /// Initializes a new instance of <see cref="IdentityDbContext"/>.
    /// </summary>
    /// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
    public IdentityDbContext(DbContextOptions options) : base(options)
    { }

    /// <summary>
    /// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
    /// </summary>
    protected IdentityDbContext()
    { }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
    /// </summary>
    public DbSet<TUser> Users { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
    /// </summary>
    public DbSet<TUserClaim> UserClaims { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
    /// </summary>
    public DbSet<TUserLogin> UserLogins { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
    /// </summary>
    public DbSet<TUserRole> UserRoles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
    /// </summary>
    public DbSet<TUserToken> UserTokens { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
    /// </summary>
    public DbSet<TRole> Roles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
    /// </summary>
    public DbSet<TRoleClaim> RoleClaims { get; set; }

    /// <summary>
    /// Configures the schema needed for the identity framework.
    /// </summary>
    /// <param name="builder">
    /// The builder being used to construct the model for this context.
    /// </param>
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<TUser>(b =>
        {
            b.HasKey(u => u.Id);
            b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
            b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
            b.ToTable("AspNetUsers");
            b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.UserName).HasMaxLength(256);
            b.Property(u => u.NormalizedUserName).HasMaxLength(256);
            b.Property(u => u.Email).HasMaxLength(256);
            b.Property(u => u.NormalizedEmail).HasMaxLength(256);
            b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
            b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
            b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
        });

        builder.Entity<TRole>(b =>
        {
            b.HasKey(r => r.Id);
            b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
            b.ToTable("AspNetRoles");
            b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.Name).HasMaxLength(256);
            b.Property(u => u.NormalizedName).HasMaxLength(256);

            b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
            b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
        });

        builder.Entity<TUserClaim>(b => 
        {
            b.HasKey(uc => uc.Id);
            b.ToTable("AspNetUserClaims");
        });

        builder.Entity<TRoleClaim>(b => 
        {
            b.HasKey(rc => rc.Id);
            b.ToTable("AspNetRoleClaims");
        });

        builder.Entity<TUserRole>(b => 
        {
            b.HasKey(r => new { r.UserId, r.RoleId });
            b.ToTable("AspNetUserRoles");
        });

        builder.Entity<TUserLogin>(b =>
        {
            b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
            b.ToTable("AspNetUserLogins");
        });

        builder.Entity<TUserToken>(b => 
        {
            b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
            b.ToTable("AspNetUserTokens");
        });
    }
}


Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:

First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.

   public class ApplicationDbContext 
    : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}


Extra Notes:

1) We can also change asp.net Identity default table names with the following solution:

    public class ApplicationDbContext : IdentityDbContext
    {    
        public ApplicationDbContext(): base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUser>().ToTable("user");
            modelBuilder.Entity<ApplicationUser>().ToTable("user");

            modelBuilder.Entity<IdentityRole>().ToTable("role");
            modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
        }
    }

2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...

    public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() 
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public ApplicationRole(string name)
        : this()
    {
        this.Name = name;
    }

    // Add any custom Role properties/code here
}


// Must be expressed in terms of our custom types:
public class ApplicationDbContext 
    : IdentityDbContext<ApplicationUser, ApplicationRole, 
    string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}

To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.

Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code

Regex for string contains?

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
      <h5>
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
      </div>
    </div>
  </div>
  ... (more cards/collapsibles inside #accordion parent)
</div>

Bootstrap 3

See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

http://bootply.com/88288

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">
           ...
        </div>
    </div>
</div>

Edit

As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (http://www.bootply.com/AbiRW7BdD6#)

How to convert a String into an array of Strings containing one character each

You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?

Fastest way to check if string contains only digits

The char already has an IsDigit(char c) which does this:

 public static bool IsDigit(char c)
    {
      if (!char.IsLatin1(c))
        return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
      if ((int) c >= 48)
        return (int) c <= 57;
      else
        return false;
    }

You can simply do this:

var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);

How can two strings be concatenated?

Another non-paste answer:

x <- capture.output(cat(data, sep = ","))
x
[1] "GAD,AB"

Where

 data <- c("GAD", "AB")

Programmatically go back to previous ViewController in Swift

I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:

  1. The origin controller can go back to any other destination controller (not just the previous one) without knowing anything about the destination.
  2. Push and pop segues are defined in storyboard, so no navigation code in your view controllers.

You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.

1) Go to the destination (not the origin) view controller and add an unwind segue:

    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }

2) CTRL drag from the view controller itself to the exit icon in the origin view controller:

Unwind from view controller

3) Select the unwind function you just created a few moments ago:

Select unwind function

4) Select the unwind segue and give it a name:

Naming unwind segue

5) Go to any place of the origin view controller and call the unwind segue:

performSegue(withIdentifier: "unwindToContact", sender: self)

I have found this approach payoffs a lot when your navigation starts to get complicated.

I hope this helps someone.

CSS way to horizontally align table

Basically, it works like,

<table align="center">
...

But, you can do it in better way using CSS, and this will be a better approach to use CSS as it provides dynamic behavior to a web page and is responsive.

  <table style="text-align:center;">

Also, if you need to display only table on a page then you can go with body tag alignment only as shown below,

 <body style="text-align:center;">
<table>
  ...
</table>

If you want any other suggestions please let me know. Will surely help you on this. Also using bootstrap features this would be more easy and interactive.

How to parse XML using vba

Add reference Project->References Microsoft XML, 6.0 and you can use example code:

    Dim xml As String

    xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
    Dim oXml As MSXML2.DOMDocument60
    Set oXml = New MSXML2.DOMDocument60
    oXml.loadXML xml
    Dim oSeqNodes, oSeqNode As IXMLDOMNode

    Set oSeqNodes = oXml.selectNodes("//root/person")
    If oSeqNodes.length = 0 Then
       'show some message
    Else
        For Each oSeqNode In oSeqNodes
             Debug.Print oSeqNode.selectSingleNode("name").Text
        Next
    End If 

be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text

Correct way to import lodash

If you are using babel, you should check out babel-plugin-lodash, it will cherry-pick the parts of lodash you are using for you, less hassle and a smaller bundle.

It has a few limitations:

  • You must use ES2015 imports to load Lodash
  • Babel < 6 & Node.js < 4 aren’t supported
  • Chain sequences aren’t supported. See this blog post for alternatives.
  • Modularized method packages aren’t supported

JavaScript and getElementById for multiple elements with the same ID

I know this is an old question and that an HTML page with multiple IDs is invalid. However, I ran into this issues while needing to scrape and reformat someone else's API's HTML documentation that contained duplicate IDs (invalid HTML).

So for anyone else, here is the code I used to work around the issue using querySelectorAll:

var elms = document.querySelectorAll("[id='duplicateID']");

for(var i = 0; i < elms.length; i++) 
  elms[i].style.display='none'; // <-- whatever you need to do here.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Allow Apache Through the Firewall

Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp

And reload the firewall:

sudo firewall-cmd --reload

How to do a non-greedy match in grep?

The short answer is using the next regular expression:

(?s)<car .*? model=BMW .*?>.*?</car>
  • (?s) - this makes a match across multiline
  • .*? - matches any character, a number of times in a lazy way (minimal match)

A (little) more complicated answer is:

(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>

This will makes possible to match car1 and car2 in the following text

<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
  • (..) represents a capturing group
  • \1 in this context matches the sametext as most recently matched by capturing group number 1

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Bundling data files with PyInstaller (--onefile)

Instead for rewriting all my path code as suggested, I changed the working directory:

if getattr(sys, 'frozen', False):
    os.chdir(sys._MEIPASS)

Just add those two lines at the beginning of your code, you can leave the rest as is.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In line 2, there's a std::string involved (name). There are operations defined for char[] + std::string, std::string + char[], etc. "Hello " + name gives a std::string, which is added to " you are ", giving another string, etc.

In line 3, you're saying

char[] + char[] + char[]

and you can't just add arrays to each other.

How to refresh app upon shaking the device?

You should subscribe as a SensorEventListener, and get the accelerometer data. Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake' movement of device.

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How to check for file lock?

You can see if the file is locked by trying to read or lock it yourself first.

Please see my answer here for more information.

How do I check for a network connection?

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Force Internet Explorer to use a specific Java Runtime Environment install?

For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,

<OBJECT 
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid attribute identifies which version of Java Plug-in to use.

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.

For example, to use Java Plug-in version 1.5.0, you specify:

classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

Can't install laravel installer via composer

If you're facing this issue with macOS Catalina, I recommend these steps:

  1. Install Homebrew (if you haven't already done so): head over to brew.sh or simply run this command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  2. Run brew install [email protected]

  3. Update your $PATH variable to include the newly installed version of php:

echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.zshrc

echo 'export PATH="/usr/local/opt/[email protected]/sbin:$PATH"' >> ~/.zshrc

  1. Reload your shell preferences script $ source ~/.zshrc or source ~/.bashrc

  2. Finally, install laravel: composer global require laravel/installer

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

Hide the browse button on a input type=file

You may just without making the element hidden, simply make it transparent by making its opacity to 0.

Making the input file hidden will make it STOP working. So DON'T DO THAT..

Here you can find an example for a transparent Browse operation;

What is the best open source help ticket system?

It absolutely depens on what your goals are. The Bugzilla and Trac systems mentioned are nice but geared towards bug tracking, which is just very different from a tool you'd want to use in a helpdesk-type setup where end users would raise incidents.

If the latter is what you are looking for I'd suggest you take a look at OTRS which is a very capable trouble ticketing system. It also has ITSM extensions, which makes it able to support ITIL processes if you need to.

Assign an initial value to radio button as checked

You can use the checked attribute for this:

<input type="radio" checked="checked">

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

How can I switch views programmatically in a view controller? (Xcode, iPhone)

#import "YourViewController.h"

To push a view including the navigation bar and/or tab bar:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self.navigationController pushViewController:viewController animated:YES];

To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

Convert LocalDateTime to LocalDateTime in UTC

Question?

Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:

Convert LocalDateTime to LocalDateTime in UTC.

Timezone?

LocalDateTime does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime? It might as well be UTC already, therefore no conversion has to be made.

System Default Timezone

Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime object is created by using LocalDateTime.now() which returns the current time in the system-default timezone. In this case, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time) {
    return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information

Explicit Timezone

In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
    return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information

The atZone() Method

The result of the atZone() method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).

If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:

2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information

The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.

Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:

2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]

Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30 for the timezone Europe/Tallinn can mean two different UTC times, and two different offsets.

Summary

As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime object, you have to know yourself which timezone it is coming from in order to convert it to UTC.

Generating a unique machine id

For one of my applications, I either use the computer name if it is non-domain computer, or the domain machine account SID for domain computers. Mark Russinovich talks about it in this blog post, Machine SID:

The final case where SID duplication would be an issue is if a distributed application used machine SIDs to uniquely identify computers. No Microsoft software does so and using the machine SID in that way doesn’t work just for the fact that all DC’s have the same machine SID. Software that relies on unique computer identities either uses computer names or computer Domain SIDs (the SID of the computer accounts in the Domain).

You can access the domain machine account SID via LDAP or System.DirectoryServices.

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

Get host domain from URL?

You should construct your string as URI object and Authority property returns what you need.

How to change the height of a <br>?

So, peeps above have got basically a similar answer, but here it is very succinctly. Works in Opera, Chrome, Safari & Firefox, most likely IE too?

br {
            display: block; /* makes it have a width */
            content: ""; /* clears default height */
            margin-top: 0; /* change this to whatever height you want it */
}

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

Storing data into list with class

You need to new up an instance of EmailData and then add that:

var data = new EmailData { FirstName = "John", LastName = "Smith", Location = "LA" };

List<EmailData> listemail = new List<EmailData>();
listemail.Add(data);

If you want to able to do:

listemail.Add("JOhn","Smith","Los Angeles");

you can create your own custom list, by specializing System.Collections.Generic.List and implementing your own Add method, more or less like this:

public class EmailList : List<EmailData>
{
    public void Add(string firstName, string lastName, string location)
    {
        var data = new EmailData 
                   { 
                       FirstName = firstName, 
                       LastName = lastName,
                       Location = location
                   };
        this.Add(data);
    }
}

Foreach loop in C++ equivalent of C#

Just for fun (new lambda functions):

      static std::list<string> some_list;

      vector<string> s; 
      s.push_back("a");
      s.push_back("b");
      s.push_back("c");

      for_each( s.begin(), s.end(), [=](string str) 
        {
          some_list.push_back(str);
        }

  );

  for_each( some_list.begin(), some_list.end(), [](string ss) { cout << ss; } );

Although doing a simple loop is recommended :-)

IndentationError expected an indented block

This error also occurs if you have a block with no statements in it

For example:

def my_function():
    for i in range(1,10):


def say_hello():
    return "hello"

Notice that the for block is empty. You can use the pass statement if you want to test the remaining code in the module.

What is the difference between `let` and `var` in swift?

Even though you have already got many difference between let and var but one main difference is:

let is compiled fast in comparison to var.

How do I change selected value of select2 dropdown with JqGrid?

My Expected code :

$('#my-select').val('').change();

working perfectly thank to @PanPipes for the usefull one.

What is the simplest way to convert array to vector?

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

or

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.

Why do table names in SQL Server start with "dbo"?

dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

How to put multiple statements in one line?

if you want it without try and except then there is the solution

what you are trying to do is print 'hello' if 'harry' in a list then the solution is

'hello' if 'harry' in sam else ''

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

Is it possible to find out the users who have checked out my project on GitHub?

I believe this is an old question, and the Traffic was introduced by Github in 2014. Here is the link to the description of Traffic, that tells you the views on your repositories.

HTML Form: Select-Option vs Datalist-Option

Datalist includes autocomplete and suggestions natively, it can also allow a user to enter a value that is not defined in the suggestions.

Select only gives you pre-defined options the user has to select from

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

(grep) Regex to match non-ASCII characters?

This turned out to be very flexible and extensible. $field =~ s/[^\x00-\x7F]//g ; # thus all non ASCII or specific items in question could be cleaned. Very nice either in selection or pre-processing of items that will eventually become hash keys.

undefined reference to WinMain@16 (codeblocks)

  1. You need to open the project file of your program and it should appear on Management panel.

  2. Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)

  3. Compile and enjoy. Hope, I could help you.

Laravel: Using try...catch with DB::transaction()

I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.

Instead of using try-catch, you can just use the DB::transaction(){...} wrapper like this:

// MyController.php
public function store(Request $request) {
    return DB::transaction(function() use ($request) {
        $user = User::create([
            'username' => $request->post('username')
        ]);

        // Add some sort of "log" record for the sake of transaction:
        $log = Log::create([
            'message' => 'User Foobar created'
        ]);

        // Lets add some custom validation that will prohibit the transaction:
        if($user->id > 1) {
            throw AnyException('Please rollback this transaction');
        }

        return response()->json(['message' => 'User saved!']);
    });
};

You should then see that the User and the Log record cannot exist without eachother.

Some notes on the implementation above:

  • Make sure to return the transaction, so that you can use the response() you return within its callback.
  • Make sure to throw an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).
  • The id, updated_at, created_at and any other fields are AVAILABLE AFTER CREATION for the $user object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException is thrown. This means that for instance an auto-increment column for id does get incremented on failed transactions.

Tested on Laravel 5.8

are there dictionaries in javascript like python?

Firefox 13+ provides an experimental implementation of the map object similar to the dict object in python. Specifications here.

It's only avaible in firefox, but it looks better than using attributes of a new Object(). Citation from the documentation :

  • An Object has a prototype, so there are default keys in the map. However, this can be bypassed using map = Object.create(null).
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

How do I make Visual Studio pause after executing a console application in debug mode?

Just use a logging library, like log4net, and have it log to a file appender.

Logging best practices


Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)


Frameworks

Q: What frameworks do you use?

A: System.Diagnostics.TraceSource, built in to .NET 2.0.

It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.

There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).

Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.

It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.

Features you may not have known:

  • Using the TraceEvent overloads that take a format string and args can help performance as parameters are kept as separate references until after Filter.ShouldTrace() has succeeded. This means no expensive calls to ToString() on parameter values until after the system has confirmed message will actually be logged.
  • The Trace.CorrelationManager allows you to correlate log statements about the same logical operation (see below).
  • VisualBasic.Logging.FileLogTraceListener is good for writing to log files and supports file rotation. Although in the VisualBasic namespace, it can be just as easily used in a C# (or other language) project simply by including the DLL.
  • When using EventLogTraceListener if you call TraceEvent with multiple arguments and with empty or null format string, then the args are passed directly to the EventLog.WriteEntry() if you are using localized message resources.
  • The Service Trace Viewer tool (from WCF) is useful for viewing graphs of activity correlated log files (even if you aren't using WCF). This can really help debug complex issues where multiple threads/activites are involved.
  • Avoid overhead by clearing all listeners (or removing Default); otherwise Default will pass everything to the trace system (and incur all those ToString() overheads).

Areas you might want to look at extending (if needed):

  • Database trace listener
  • Colored console trace listener
  • MSMQ / Email / WMI trace listeners (if needed)
  • Implement a FileSystemWatcher to call Trace.Refresh for dynamic configuration changes

Other Recommendations:

Use structed event id's, and keep a reference list (e.g. document them in an enum).

Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.

Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.

e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.

The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.

Assigned, structured event id's also allow you use them in filters.

Q: If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?

A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).

You need at least to set the ActivityId once for each logical operation in order to correlate.

Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.

The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).

Q: Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?

A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.

This allows you to write code such as the following to automatically wrap operations:

  using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
  {
    // .. do work here
  }

On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.

Q: Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels.

A: Yes, multiple Trace Sources are useful / important as systems get larger.

Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.

Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.

This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.

The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.

If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).

You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.

Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.


Listeners

Q: What log outputs do you use?

This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).

I generally classify outputs into three groups:

(1) Events - Windows Event Log (and trace files)

e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).

In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.

In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).

In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).

Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.

i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).

(2) Activities - Application Log files or database table (and trace files)

This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.

Activity Tracing (start, stop, etc) is useful here (at the right granuality).

Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).

Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.

A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.

As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.

In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).

(3) Debug Trace - Text file, or maybe XML or database.

This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.

This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.

A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".

One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.

If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.

Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?

A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).

Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).

If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].

One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.

If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.

Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).


Viewing

Q: What tools to you use for viewing the logs?

A: If you have multiple logs for different reasons then you will use multiple viewers.

Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.

If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).

As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).

Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.

Others --

If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)

MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.

When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.

Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).

It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.

Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?

These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.

Q: What about custom performance counters?

For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.

You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).

This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.

Detect when input has a 'readonly' attribute

Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

if($('input').prop('readonly')){ }

.prop() can also be used to set the property

$('input').prop('readonly',true);

$('input').prop('readonly',false);

How to increase the gap between text and underlining in CSS

Getting into the details of the visual style of text-decoration:underline is pretty much futile, so you're going to have to go with some kind of hack the removes text-decoration:underline and replaces it with something else until a magical far-distant future version of CSS gives us more control.

This worked for me:

_x000D_
_x000D_
   a {_x000D_
    background-image: linear-gradient(_x000D_
        180deg, rgba(0,0,0,0),_x000D_
        rgba(0,0,0,0) 81%, _x000D_
        #222222 81.1%,_x000D_
        #222222 85%,_x000D_
        rgba(0,0,0,0) 85.1%,_x000D_
        rgba(0,0,0,0)_x000D_
    );_x000D_
    text-decoration: none;_x000D_
}
_x000D_
<a href="#">Lorem ipsum</a> dolor sit amet, <a href="#">consetetur sadipscing</a> elitr, sed diam nonumy eirmod tempor <a href="#">invidunt ut labore.</a>
_x000D_
_x000D_
_x000D_

  • Adjust the % values (81% and 85%) to change how far the line is from the text
  • Adjust the difference between the two % values to change the line thickness
  • adjust the color values (#222222) to change the underline color
  • works with multiple line inline elements
  • works with any background

Here's a version with all the proprietary properties for some backwards compatibility:

a {     
    /* This code generated from: http://colorzilla.com/gradient-editor/ */
    background: -moz-linear-gradient(top,  rgba(0,0,0,0) 0%, rgba(0,0,0,0) 81%, rgba(0,0,0,1) 81.1%, rgba(0,0,0,1) 85%, rgba(0,0,0,0) 85.1%, rgba(0,0,0,0) 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0)), color-stop(81%,rgba(0,0,0,0)), color-stop(81.1%,rgba(0,0,0,1)), color-stop(85%,rgba(0,0,0,1)), color-stop(85.1%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* IE10+ */
    background: linear-gradient(to bottom,  rgba(0,0,0,0) 0%,rgba(0,0,0,0) 81%,rgba(0,0,0,1) 81.1%,rgba(0,0,0,1) 85%,rgba(0,0,0,0) 85.1%,rgba(0,0,0,0) 100%); /* W3C */

    text-decoration: none;
}

Update: SASSY version

I made a scss mixin for this. If you don't use SASS, the regular version above still works great...

@mixin fake-underline($color: #666, $top: 84%, $bottom: 90%) {
    background-image: linear-gradient(
        180deg, rgba(0,0,0,0),
        rgba(0,0,0,0) $top,
        $color $top + 0.1%,
        $color $bottom,
        rgba(0,0,0,0) $bottom + 0.1%,
        rgba(0,0,0,0)
    );
    text-decoration: none;
}

then use it like so:

$blue = #0054a6;
a {
    color: $blue;
    @include fake-underline(lighten($blue,20%));
}
a.thick {
    color: $blue;
    @include fake-underline(lighten($blue,40%), 86%, 99%);
}

Update 2: Descenders Tip

If you have a solid background color, try adding a thin text-stroke or text-shadow in the same color as your background to make the descenders look nice.

Credit

This is simplified version of the technique I originally found at https://eager.io/app/smartunderline, but the article has since been taken down.

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

How do I upload a file with the JS fetch API?

The accepted answer here is a bit dated. As of April 2020, a recommended approach seen on the MDN website suggests using FormData and also does not ask to set the content type. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

I'm quoting the code snippet for convenience:

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then((response) => response.json())
.then((result) => {
  console.log('Success:', result);
})
.catch((error) => {
  console.error('Error:', error);
});

How to read values from the querystring with ASP.NET Core?

I have a better solution for this problem,

  • request is a member of abstract class ControllerBase
  • GetSearchParams() is an extension method created in bellow helper class.

var searchparams = await Request.GetSearchParams();

I have created a static class with few extension methods

public static class HttpRequestExtension
{
  public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
        {
            var parameters = await request.TupledParameters();

            try
            {
                for (var i = 0; i < parameters.Count; i++)
                {
                    if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
                    {
                        parameters[i] = new Tuple<string, string>("_summary", "count");
                    }
                }
                var searchCommand = SearchParams.FromUriParamList(parameters);
                return searchCommand;
            }
            catch (FormatException formatException)
            {
                throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
            }
        }



public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
        var list = new List<Tuple<string, string>>();


        var query = request.Query;
        foreach (var pair in query)
        {
            list.Add(new Tuple<string, string>(pair.Key, pair.Value));
        }

        if (!request.HasFormContentType)
        {
            return list;
        }
        var getContent = await request.ReadFormAsync();

        if (getContent == null)
        {
            return list;
        }
        foreach (var key in getContent.Keys)
        {
            if (!getContent.TryGetValue(key, out StringValues values))
            {
                continue;
            }
            foreach (var value in values)
            {
                list.Add(new Tuple<string, string>(key, value));
            }
        }
        return list;
    }
}

in this way you can easily access all your search parameters. I hope this will help many developers :)

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

Android Studio - local path doesn't exist

Please check the build.gradle file. if there is some operation about "applicationVariants.all" or the assignment to output.outputFile, means trying to change to name or location of the output file.

You can try to comment them out first then try again.

Way to go from recursion to iteration

Thinking of things that actually need a stack:

If we consider the pattern of recursion as:

if(task can be done directly) {
    return result of doing task directly
} else {
    split task into two or more parts
    solve for each part (possibly by recursing)
    return result constructed by combining these solutions
}

For example, the classic Tower of Hanoi

if(the number of discs to move is 1) {
    just move it
} else {
    move n-1 discs to the spare peg
    move the remaining disc to the target peg
    move n-1 discs from the spare peg to the target peg, using the current peg as a spare
}

This can be translated into a loop working on an explicit stack, by restating it as:

place seed task on stack
while stack is not empty 
   take a task off the stack
   if(task can be done directly) {
      Do it
   } else {
      Split task into two or more parts
      Place task to consolidate results on stack
      Place each task on stack
   }
}

For Tower of Hanoi this becomes:

stack.push(new Task(size, from, to, spare));
while(! stack.isEmpty()) {
    task = stack.pop();
    if(task.size() = 1) {
        just move it
    } else {
        stack.push(new Task(task.size() -1, task.spare(), task,to(), task,from()));
        stack.push(new Task(1, task.from(), task.to(), task.spare()));
        stack.push(new Task(task.size() -1, task.from(), task.spare(), task.to()));
    }
}

There is considerable flexibility here as to how you define your stack. You can make your stack a list of Command objects that do sophisticated things. Or you can go the opposite direction and make it a list of simpler types (e.g. a "task" might be 4 elements on a stack of int, rather than one element on a stack of Task).

All this means is that the memory for the stack is in the heap rather than in the Java execution stack, but this can be useful in that you have more control over it.

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

Opposite of append in jquery

What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:

   var newUL = $('<ul><li>test</li></ul>');
   $(this).append(newUL);

   // Later ...

   newUL.remove();

In Django, how do I check if a user is in a certain group?

If a user belongs to a certain group or not, can be checked in django templates using:

{% if group in request.user.groups.all %} "some action" {% endif %}

int to string in MySQL

Try it using CONCAT

CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Deleting multiple columns based on column names in Pandas

You can do this in one line and one go:

df.drop([col for col in df.columns if "Unnamed" in col], axis=1, inplace=True)

This involves less moving around/copying of the object than the solutions above.

An invalid XML character (Unicode: 0xc) was found

The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.

In PHP, how do you change the key of an array element?

You could use a second associative array that maps human readable names to the id's. That would also provide a Many to 1 relationship. Then do something like this:

echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

CodeIgniter - File upload required validation

you can use call back function, like this

  $this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');

    if ($this->form_validation->run() == FALSE) {
         //error
     }
    else{
           // success       
      }

function file_selected_test(){

    $this->form_validation->set_message('file_selected_test', 'Please select file.');
    if (empty($_FILES['userfile']['name'])) {
            return false;
        }else{
            return true;
        }
}

jQuery AJAX cross domain

it works, all you need:

PHP:

header('Access-Control-Allow-Origin: http://www.example.com');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

JS (jQuery ajax):

var getWBody = $.ajax({ cache: false,
        url: URL,
        dataType : 'json',
        type: 'GET',
        xhrFields: { withCredentials: true }
});

What does an exclamation mark mean in the Swift language?

The entire story begins with a feature of swift called optional vars. These are the vars which may have a value or may not have a value. In general swift doesn't allow us to use a variable which isn't initialised, as this may lead to crashes or unexpected reasons and also server a placeholder for backdoors. Thus in order to declare a variable whose value isn't initially determined we use a '?'. When such a variable is declared, to use it as a part of some expression one has to unwrap them before use, unwrapping is an operation through which value of a variable is discovered this applies to objects. Without unwrapping if you try to use them you will have compile time error. To unwrap a variable which is an optional var, exclamation mark "!" is used.

Now there are times when you know that such optional variables will be assigned values by system for example or your own program but sometime later , for example UI outlets, in such situation instead of declaring an optional variable using a question mark "?" we use "!".

Thus system knows that this variable which is declared with "!" is optional right now and has no value but will receive a value in later in its lifetime.

Thus exclamation mark holds two different usages, 1. To declare a variable which will be optional and will receive value definitely later 2. To unwrap an optional variable before using it in an expression.

Above descriptions avoids too much of technical stuff, i hope.

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

Determine Whether Integer Is Between Two Other Integers?

The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=

#                             v---------- should be <
if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

Python lets you just write what you mean in words

if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)

In Python3, you need to use range instead of xrange.

edit: People seem to be more concerned with microbench marks and how cool chaining operations. My answer is about defensive (less attack surface for bugs) programming.

As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2

$ python3.5 -m timeit "5 in range(10000, 30000)"
1000000 loops, best of 3: 0.266 usec per loop
$ python3.5 -m timeit "10000 <= 5 < 30000"
10000000 loops, best of 3: 0.0327 usec per loop

If you are worried about performance, you could compute the range once

$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop

How to drop a database with Mongoose?

beforeEach((done) => {
      mongoose.connection.dropCollection('products',(error ,result) => {
      if (error) {
        console.log('Products Collection is not dropped')
      } else {
        console.log(result)
      }
    done()
    })
  })

Where to find htdocs in XAMPP Mac

In the "volumes" tab, you have to mount it first. Then it appears on the desktop as if it were an external USB. All the data is inside it. :D

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

In CodeIgniter 3.0-dev (get it from github) this is not working because the CI is search as first letter uppercase.

You can find the code on system/core/Loader.php line 282 or bellow:

$model = ucfirst(strtolower($model));

foreach ($this->_ci_model_paths as $mod_path)
{
    if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
    {
        continue;
    }

    require_once($mod_path.'models/'.$path.$model.'.php');

    $CI->$name = new $model();
    $this->_ci_models[] = $name;
    return $this;
}

This mean that we need to create the file with the following name on application/models/Logon_mode.php

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

imagecreatefromjpeg and similar functions are not working in PHP

If you are like me and you are using one of the PHP Docker images as your base, you need to add the gd extension using different instructions then what's discussed above.

For the php:7.4.1-apache image you need to add in your Dockerfile:

RUN apt-get update && \
    apt-get install -y zlib1g-dev libpng-dev libjpeg-dev

RUN docker-php-ext-configure gd --with-jpeg && \
    docker-php-ext-install gd

These dev packages are needed for compilation of the GD php extension. For me this resulted in activation of GD with PNG and JPEG support in PHP.

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

How to add new DataRow into DataTable?

This works for me:

var table = new DataTable();
table.Rows.Add();

getch and arrow codes

I'm Just a starter, but i'v created a char(for example "b"), and I do b = _getch(); (its a conio.h library's command) And check

If (b == -32)
b = _getch();

And do check for the keys (72 up, 80 down, 77 right, 75 left)

Leaflet - How to find existing markers, and delete markers?

Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :

Here is the entire JSFiddle code . Also here is the full page demo.

Adding the marker :

// Script for adding marker on map click
map.on('click', onMapClick);

function onMapClick(e) {

    var geojsonFeature = {

        "type": "Feature",
        "properties": {},
        "geometry": {
                "type": "Point",
                "coordinates": [e.latlng.lat, e.latlng.lng]
        }
    }

    var marker;

    L.geoJson(geojsonFeature, {

        pointToLayer: function(feature, latlng){

            marker = L.marker(e.latlng, {

                title: "Resource Location",
                alt: "Resource Location",
                riseOnHover: true,
                draggable: true,

            }).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");

            marker.on("popupopen", onPopupOpen);

            return marker;
        }
    }).addTo(map);
}

Deleting the Marker :

// Function to handle delete as well as other events on marker popup open

function onPopupOpen() {

    var tempMarker = this;

    // To remove marker on click of delete button in the popup of marker
    $(".marker-delete-button:visible").click(function () {
        map.removeLayer(tempMarker);
    });
}

Getting all the markers in the map :

// getting all the markers at once
function getAllMarkers() {

    var allMarkersObjArray = []; // for marker objects
    var allMarkersGeoJsonArray = []; // for readable geoJson markers

    $.each(map._layers, function (ml) {

        if (map._layers[ml].feature) {

            allMarkersObjArray.push(this)
            allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
        }
    })

    console.log(allMarkersObjArray);
}

// any html element such as button, div to call the function()
$(".get-markers").on("click", getAllMarkers);

Make a DIV fill an entire table cell

a bit late to the party but here's my solution:

<td style="padding: 0; position: relative;">
   <div style="width: 100%; height: 100%; position: absolute; overflow: auto;">
     AaaaaaaaaaaaaaaaaaBBBBBBBbbbbbbbCCCCCCCCCccccc<br>
     DDDDDDDddddEEEEEEEEdddfffffffffgggggggggggggggggggg
   </div>
</td>

Java out.println() how is this possible?

Well, you would typically use

System.out.println("print something");

which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:

import static java.lang.System.*;

class Test {
    public static void main(String[] args) {
        out.println("print something");
    }
}

Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.

Compiling with g++ using multiple cores

make will do this for you. Investigate the -j and -l switches in the man page. I don't think g++ is parallelizable.

Displaying files (e.g. images) stored in Google Drive on a website

Con can disable javascript in your browser open the image file and in the view page source or right click on the image, you will see the image link. ( check share preference before )

Equivalent of LIMIT for DB2

@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:

select * from (
    select * from (
        select * from MYLIB.MYTABLE
        order by MYID asc 
        fetch first {last} rows only 
        ) I 
    order by MYID desc
    fetch first {length} rows only
    ) II
order by MYID asc

where {last} should be replaced with row number of the last record I need and {length} should be replaced with the number of rows I need, calculated as last row - first row + 1.

E.g. if I want rows from 10 to 25 (totally 16 rows), {last} will be 25 and {length} will be 25-10+1=16.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

This was my problem and how I fixed it...

I had done everything everyone had mentioned above etc. but was still getting this error. Turns out I was using the uri's of http://java.sun.com/jsp/jstl/fmt and http://java.sun.com/jsp/jstl/core which were incorrect.

Try switching the uris from above to:

http://java.sun.com/jstl/fmt
http://java.sun.com/jstl/core

Also, make sure you have the correct jars referenced in your class path.

Can't drop table: A foreign key constraint fails

This should do the trick:

SET FOREIGN_KEY_CHECKS=0; DROP TABLE bericht; SET FOREIGN_KEY_CHECKS=1;

As others point out, this is almost never what you want, even though it's whats asked in the question. A more safe solution is to delete the tables depending on bericht before deleting bericht. See CloudyMarble answer on how to do that. I use bash and the method in my post to drop all tables in a database when I don't want to or can't delete and recreate the database itself.

The #1217 error happens when other tables has foreign key constraints to the table you are trying to delete and you are using the InnoDB database engine. This solution temporarily disables checking the restraints and then re-enables them. Read the documentation for more. Be sure to delete foreign key restraints and fields in tables depending on bericht, otherwise you might leave your database in a broken state.

Graph implementation C++

This question is ancient but for some reason I can't seem to get it out of my mind.

While all of the solutions do provide an implementation of graphs, they are also all very verbose. They are simply not elegant.

Instead of inventing your own graph class all you really need is a way to tell that one point is connected to another -- for that, std::map and std::unordered_map work perfectly fine. Simply, define a graph as a map between nodes and lists of edges. If you don't need extra data on the edge, a list of end nodes will do just fine.

Thus a succinct graph in C++, could be implemented like so:

using graph = std::map<int, std::vector<int>>;

Or, if you need additional data,

struct edge {
    int nodes[2];
    float cost; // add more if you need it
};

using graph = std::map<int, std::vector<edge>>;

Now your graph structure will plug nicely into the rest of the language and you don't have to remember any new clunky interface -- the old clunky interface will do just fine.

No benchmarks, but I have a feeling this will also outperform the other suggestions here.

NB: the ints are not indices -- they are identifiers.

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

Sometimes, none of these work. Annoyingly, due to the LF thing I think, what will work is deleting the files, then pulling. Not that I recommend this solution, but if the file doesn't exist, git won't uselessly inform you that your changes (which may not even be changes) will get overridden, and will let you continue.

Use at your own risk.

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

JetBrains / IntelliJ keyboard shortcut to collapse all methods

The above suggestion of Ctrl+Shift+- code folds all code blocks recursively. I only wanted to fold the methods for my classes.

Code > Folding > Expand all to level > 1

I managed to achieve this by using the menu option Code > Folding > Expand all to level > 1.

I re-assigned it to Ctrl+NumPad-1 which gives me a quick way to collapse my classes down to their methods.

This works at the 'block level' of the file and assumes that you have classes defined at the top level of your file, which works for code such as PHP but not for JavaScript (nested closures etc.)

Classpath including JAR within a JAR

Well, there is a very easy way if you're using Eclipse.

Export your project as a "Runnable" Jar file (right-click project folder from within Eclipse, select "Export..."). When you configure the export settings, be sure to select "Extract required libraries into generated Jar." Keep in mind, select "Extract..." and not "Package required libraries...".

Additionally: You must select a run-configuration in your export settings. So, you could always create an empty main( ) in some class and use it for your run configuration.

Anyway, it isn't guaranteed to work 100% of the time - as you will notice a pop-up message telling you to make sure you check the licenses of the Jar files you're including and something about not copying signature files. However, I have been doing this for years and have never encountered a problem.

Pass array to MySQL stored routine

Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.

create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;

delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
  -- use the temporary table `ids` in the SELECT statement or
  -- whatever query you have
  select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;

CALL tsel() ; -- call the procedure

How to pass url arguments (query string) to a HTTP request on Angular?

If you plan on sending more than one parameter.

Component

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

Service

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

And continue with your http request just how @ethemsulan did.

Server side route

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});

Count number of days between two dates

To get the number of days difference by two dates:

(start.to_date...end.to_date).count - 1
or 
(end.to_date - start.to_date).to_i

Normalize columns of pandas data frame

The following function calculates the Z score:

def standardization(dataset):
  """ Standardization of numeric fields, where all values will have mean of zero 
  and standard deviation of one. (z-score)

  Args:
    dataset: A `Pandas.Dataframe` 
  """
  dtypes = list(zip(dataset.dtypes.index, map(str, dataset.dtypes)))
  # Normalize numeric columns.
  for column, dtype in dtypes:
      if dtype == 'float32':
          dataset[column] -= dataset[column].mean()
          dataset[column] /= dataset[column].std()
  return dataset

How do I look inside a Python object?

Many good tipps already, but the shortest and easiest (not necessarily the best) has yet to be mentioned:

object?

How to get a substring of text?

Use String#slice, also aliased as [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[6..]                 #=> "there" (requires Ruby 2.6+)
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

SQL Server IN vs. EXISTS Performance

I'd go with EXISTS over IN, see below link:

SQL Server: JOIN vs IN vs EXISTS - the logical difference

There is a common misconception that IN behaves equally to EXISTS or JOIN in terms of returned results. This is simply not true.

IN: Returns true if a specified value matches any value in a subquery or a list.

Exists: Returns true if a subquery contains any rows.

Join: Joins 2 resultsets on the joining column.

Blog credit: https://stackoverflow.com/users/31345/mladen-prajdic

How do you know a variable type in java?

If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:

boolean b = a instanceof String

Android list view inside a scroll view

Ok, here 's my answer. The method that fixes the ListView height is closed enough, but not perfect. In case that most of the items are the same height, that work well. But in case that's not, then there's a big problem. I've tried many time, and when I put out the value of listItem.getMeasureHeight and listItem.getMeasuerWidth into the log, I saw the width values vary a lot, which is not expected here, since all the item in the same ListView should have the same width. And there go the bug :

Some used measure(0 ,0), which actually made the view unbound, in both direction, and width run wild. Some tried to getWidth of listView, but then it return 0, meaningless.

When I read further into how android render the View, I realize that all of this attempt can't reach the answer that I searched for, unless these function run after the view is render.

This time I use the getViewTreeObserver on the ListView that I want to fix height, then addOnGlobalLayoutListener. Inside this method, I declare a new OnGlobalLayoutListener, in which, this time, getWidth return the actual width of the ListView.

private void getLayoutWidth(final ListView lv, final int pad){
        //final ArrayList<Integer> width = new ArrayList<Integer>();

        ViewTreeObserver vto = lv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                lv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                //width.add(layout.getMeasuredWidth());
                int width = lv.getMeasuredWidth();
                ListUtils.setDynamicHeight(lv, width, pad);
            }
        });
    }

public static class ListUtils {
        //private static final int UNBOUNDED = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        public static void setDynamicHeight(ListView mListView, int width, int pad) {
            ListAdapter mListAdapter = mListView.getAdapter();
            mListView.getParent();
            if (mListAdapter == null) {
                // when adapter is null
                return;
            }
            int height = 0;


            int desiredWidth = View.MeasureSpec.makeMeasureSpec(width - 2*pad, View.MeasureSpec.EXACTLY);
            for (int i = 0; i < mListAdapter.getCount(); i++) {
                View listItem = mListAdapter.getView(i, null, mListView);

                listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                //listItem.measure(UNBOUNDED, UNBOUNDED);
                height += listItem.getMeasuredHeight() + 2*pad;
                Log.v("ViewHeight :", mListAdapter.getClass().toString() + " " + listItem.getMeasuredHeight() + "--" + listItem.getMeasuredWidth());
            }
            ViewGroup.LayoutParams params = mListView.getLayoutParams();
            params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
            mListView.setLayoutParams(params);
            mListView.requestLayout();
        }
    }

The value pad, is the padding that I set in ListView layout.

Querying data by joining two tables in two database on different servers

While I was having trouble join those two tables, I got away with doing exactly what I wanted by opening both remote databases at the same time. MySQL 5.6 (php 7.1) and the other MySQL 5.1 (php 5.6)

//Open a new connection to the MySQL server
$mysqli1 = new mysqli('server1','user1','password1','database1');
$mysqli2 = new mysqli('server2','user2','password2','database2');

//Output any connection error
if ($mysqli1->connect_error) {
    die('Error : ('. $mysqli1->connect_errno .') '. $mysqli1->connect_error);
} else { 
echo "DB1 open OK<br>";
}
if ($mysqli2->connect_error) {
    die('Error : ('. $mysqli2->connect_errno .') '. $mysqli2->connect_error);
} else { 
echo "DB2 open OK<br><br>";
}

If you get those two OKs on screen, then both databases are open and ready. Then you can proceed to do your querys.

$results = $mysqli1->query("SELECT * FROM video where video_id_old is NULL");
    while($row = $results->fetch_array()) {
        $theID = $row[0];
        echo "Original ID : ".$theID." <br>";
        $doInsert = $mysqli2->query("INSERT INTO video (...) VALUES (...)");
        $doGetVideoID = $mysqli2->query("SELECT video_id, time_stamp from video where user_id = '".$row[13]."' and time_stamp = ".$row[28]." ");
            while($row = $doGetVideoID->fetch_assoc()) {
                echo "New video_id : ".$row["video_id"]." user_id : ".$row["user_id"]." time_stamp : ".$row["time_stamp"]."<br>";
                $sql = "UPDATE video SET video_id_old = video_id, video_id = ".$row["video_id"]." where user_id = '".$row["user_id"]."' and video_id = ".$theID.";";
                $sql .= "UPDATE video_audio SET video_id = ".$row["video_id"]." where video_id = ".$theID.";";
                // Execute multi query if you want
                if (mysqli_multi_query($mysqli1, $sql)) {
                    // Query successful do whatever...
                }
            }
    }
// close connection 
$mysqli1->close();
$mysqli2->close();

I was trying to do some joins but since I got those two DBs open, then I can go back and forth doing querys by just changing the connection $mysqli1 or $mysqli2

It worked for me, I hope it helps... Cheers

docker: executable file not found in $PATH

I found the same problem. I did the following:

docker run -ti devops -v /tmp:/tmp /bin/bash

When I change it to

docker run -ti -v /tmp:/tmp devops /bin/bash

it works fine.

How To Include CSS and jQuery in my WordPress plugin?

To include CSS and jQuery in your plugin is easy, try this:

// register jquery and style on initialization
add_action('init', 'register_script');
function register_script() {
    wp_register_script( 'custom_jquery', plugins_url('/js/custom-jquery.js', __FILE__), array('jquery'), '2.5.1' );

    wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
}

// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');

function enqueue_style(){
   wp_enqueue_script('custom_jquery');

   wp_enqueue_style( 'new_style' );
}

I found this great snipped from this site How to include jQuery and CSS in WordPress – The WordPress Way

Hope that helps.

Read input from console in Ruby?

you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number

#!/usr/bin/ruby

first_number = ARGV[0].to_i
second_number = ARGV[1].to_i

puts first_number + second_number

and you call it like this

% ./plus.rb 5 6
==> 11

How to unset (remove) a collection element after fetching it?

Or you can use reject method

$newColection = $collection->reject(function($element) {
    return $item->selected != true;
});

or pull method

$selected = []; 
foreach ($collection as $key => $item) {
      if ($item->selected == true) {
          $selected[] = $collection->pull($key);
      }
}

How to configure a HTTP proxy for svn

There are two common approaches for this:

If you are on Windows, you can also write http-proxy- options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

What is a callback?

Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

React Native fetch() Network Request Failed

The problem may be in server configuration.

Android 7.0 has a bug described here. Workaround proposed by Vicky Chijwani:

Configure your server to use the elliptic curve prime256v1. For example, in Nginx 1.10 you do this by setting ssl_ecdh_curve prime256v1;

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

What is the difference between Bower and npm?

My team moved away from Bower and migrated to npm because:

  • Programmatic usage was painful
  • Bower's interface kept changing
  • Some features, like the url shorthand, are entirely broken
  • Using both Bower and npm in the same project is painful
  • Keeping bower.json version field in sync with git tags is painful
  • Source control != package management
  • CommonJS support is not straightforward

For more details, see "Why my team uses npm instead of bower".

Add a UIView above all, even the navigation bar

You need to add a subview to the first window with the UITextEffectsWindow type. To the first, because custom keyboards add their UITextEffectsWindow, and if you add a subview to it this won't work correctly. Also, you cannot add a subview to the last window because the keyboard, for example, is also a window and you can`t present from the keyboard window. So the best solution I found is to add subview (or even push view controller) to the first window with UITextEffectsWindow type, this window covers accessory view, navbar - everything.

let myView = MyView()
myView.frame = UIScreen.main.bounds

guard let textEffectsWindow = NSClassFromString("UITextEffectsWindow") else { return }
let window = UIApplication.shared.windows.first { window in
    window.isKind(of: textEffectsWindow)
}
window?.rootViewController?.view.addSubview(myView)

Directing print output to a .txt file

Use the logging module

def init_logging():
    rootLogger = logging.getLogger('my_logger')

    LOG_DIR = os.getcwd() + '/' + 'logs'
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
    rootLogger.addHandler(fileHandler)

    rootLogger.setLevel(logging.DEBUG)

    consoleHandler = logging.StreamHandler()
    rootLogger.addHandler(consoleHandler)

    return rootLogger

Get the logger:

logger = init_logging()

And start logging/output(ing):

logger.debug('Hi! :)')

Checking if float is an integer

This deals with computational round-off. You set the epsilon as desired:

bool IsInteger(float value)
{
    return fabs(ceilf(value) - value) < EPSILON;
}

How can I make my custom objects Parcelable?

How? With annotations.

You simply annotate a POJO with a special annotation and library does the rest.

Warning!

I'm not sure that Hrisey, Lombok, and other code generation libraries are compatible with Android's new build system. They may or may not play nicely with hot swapping code (i.e. jRebel, Instant Run).

Pros:

  • Code generation libraries save you from the boilerplate source code.
  • Annotations make your class beautiful.

Cons:

  • It works well for simple classes. Making a complex class parcelable may be tricky.
  • Lombok and AspectJ don't play well together. [details]
  • See my warnings.

Hrisey

Warning!

Hrisey has a known issue with Java 8 and therefore cannot be used for Android development nowadays. See #1 Cannot find symbol errors (JDK 8).

Hrisey is based on Lombok. Parcelable class using Hrisey:

@hrisey.Parcelable
public final class POJOClass implements android.os.Parcelable {
    /* Fields, accessors, default constructor */
}

Now you don't need to implement any methods of Parcelable interface. Hrisey will generate all required code during preprocessing phase.

Hrisey in Gradle dependencies:

provided "pl.mg6.hrisey:hrisey:${hrisey.version}"

See here for supported types. The ArrayList is among them.

Install a plugin - Hrisey xor Lombok* - for your IDE and start using its amazing features!

enter image description here
* Don't enable Hrisey and Lombok plugins together or you'll get an error during IDE launch.


Parceler

Parcelable class using Parceler:

@java.org.parceler.Parcel
public class POJOClass {
    /* Fields, accessors, default constructor */
}

To use the generated code, you may reference the generated class directly, or via the Parcels utility class using

public static <T> Parcelable wrap(T input);

To dereference the @Parcel, just call the following method of Parcels class

public static <T> T unwrap(Parcelable input);

Parceler in Gradle dependencies:

compile "org.parceler:parceler-api:${parceler.version}"
provided "org.parceler:parceler:${parceler.version}"

Look in README for supported attribute types.


AutoParcel

AutoParcel is an AutoValue extension that enables Parcelable values generation.

Just add implements Parcelable to your @AutoValue annotated models:

@AutoValue
abstract class POJOClass implements Parcelable {
    /* Note that the class is abstract */
    /* Abstract fields, abstract accessors */

    static POJOClass create(/*abstract fields*/) {
        return new AutoValue_POJOClass(/*abstract fields*/);
    }
}

AutoParcel in Gradle build file:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

repositories {
    /*...*/
    maven {url "https://clojars.org/repo/"}
}

dependencies {
    apt "frankiesardo:auto-parcel:${autoparcel.version}"
}

PaperParcel

PaperParcel is an annotation processor that automatically generates type-safe Parcelable boilerplate code for Kotlin and Java. PaperParcel supports Kotlin Data Classes, Google's AutoValue via an AutoValue Extension, or just regular Java bean objects.

Usage example from docs.
Annotate your data class with @PaperParcel, implement PaperParcelable, and add a JVM static instance of PaperParcelable.Creator e.g.:

@PaperParcel
public final class Example extends PaperParcelable {
    public static final PaperParcelable.Creator<Example> CREATOR = new PaperParcelable.Creator<>(Example.class);

    private final int test;

    public Example(int test) {
        this.test = test;
    }

    public int getTest() {
        return test;
    }
}

For Kotlin users, see Kotlin Usage; For AutoValue users, see AutoValue Usage.


ParcelableGenerator

ParcelableGenerator (README is written in Chinese and I don't understand it. Contributions to this answer from english-chinese speaking developers are welcome)

Usage example from README.

import com.baoyz.pg.Parcelable;

@Parcelable
public class User {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

The android-apt plugin assists in working with annotation processors in combination with Android Studio.

How to add facebook share button on my website?

You don't need all that code. All you need are the following lines:

<a href="https://www.facebook.com/sharer/sharer.php?u=example.org" target="_blank">
  Share on Facebook
</a>

Documentation can be found at https://developers.facebook.com/docs/reference/plugins/share-links/

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

How to append strings using sprintf?

I write a function support dynamic variable string append, like PHP str append: str . str . ... etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    /*
    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");
    */

    int i;
    for (i = 0; i < 100; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

C# how to use enum with switch

 public enum Operator
    {
        PLUS, MINUS, MULTIPLY, DIVIDE
    }

    public class Calc
    {
        public void Calculate(int left, int right, Operator op)
        {

            switch (op)
            {
                case Operator.DIVIDE:
                    //Divide
                    break;
                case Operator.MINUS:
                    //Minus
                    break;
                case Operator.MULTIPLY:
                    //...
                    break;
                case Operator.PLUS:
                    //;;
                    break;
                default:
                    throw new InvalidOperationException("Couldn't process operation: " + op);
            }
        }
    }

Check if a row exists, otherwise insert

The best approach to this problem is first making the database column UNIQUE

ALTER TABLE table_name ADD UNIQUE KEY

THEN INSERT IGNORE INTO table_name ,the value won't be inserted if it results in a duplicate key/already exists in the table.

DateTime fields from SQL Server display incorrectly in Excel

Here's a hack which might be helpful... it puts an apostrophe in front of the time value, so when you right-click on the output in SSMS and say "Copy with Headers", then paste into Excel, it preserves the milliseconds / nanoseconds for datetime2 values. It's a bit ugly that it puts the apostrophe there, but it's better than the frustration of dealing with Excel doing unwanted rounding on the time value. The date is a UK format but you can look at the CONVERT function page in MSDN.

SELECT CONVERT(VARCHAR(23), sm.MilestoneDate, 103) AS MilestoneDate, '''' + CONVERT(VARCHAR(23), sm.MilestoneDate, 114) AS MilestoneTime FROM SomeTable sm

Importing csv file into R - numeric values read as characters

If you're dealing with large datasets (i.e. datasets with a high number of columns), the solution noted above can be manually cumbersome, and requires you to know which columns are numeric a priori.

Try this instead.

char_data <- read.csv(input_filename, stringsAsFactors = F)
num_data <- data.frame(data.matrix(char_data))
numeric_columns <- sapply(num_data,function(x){mean(as.numeric(is.na(x)))<0.5})
final_data <- data.frame(num_data[,numeric_columns], char_data[,!numeric_columns])

The code does the following:

  1. Imports your data as character columns.
  2. Creates an instance of your data as numeric columns.
  3. Identifies which columns from your data are numeric (assuming columns with less than 50% NAs upon converting your data to numeric are indeed numeric).
  4. Merging the numeric and character columns into a final dataset.

This essentially automates the import of your .csv file by preserving the data types of the original columns (as character and numeric).

Split string with delimiters in C

Method below will do all the job (memory allocation, counting the length) for you. More information and description can be found here - Implementation of Java String.split() method to split C string

int split (const char *str, char c, char ***arr)
{
    int count = 1;
    int token_len = 1;
    int i = 0;
    char *p;
    char *t;

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
            count++;
        p++;
    }

    *arr = (char**) malloc(sizeof(char*) * count);
    if (*arr == NULL)
        exit(1);

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
        {
            (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
            if ((*arr)[i] == NULL)
                exit(1);

            token_len = 0;
            i++;
        }
        p++;
        token_len++;
    }
    (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
    if ((*arr)[i] == NULL)
        exit(1);

    i = 0;
    p = str;
    t = ((*arr)[i]);
    while (*p != '\0')
    {
        if (*p != c && *p != '\0')
        {
            *t = *p;
            t++;
        }
        else
        {
            *t = '\0';
            i++;
            t = ((*arr)[i]);
        }
        p++;
    }

    return count;
}

How to use it:

int main (int argc, char ** argv)
{
    int i;
    char *s = "Hello, this is a test module for the string splitting.";
    int c = 0;
    char **arr = NULL;

    c = split(s, ' ', &arr);

    printf("found %d tokens.\n", c);

    for (i = 0; i < c; i++)
        printf("string #%d: %s\n", i, arr[i]);

    return 0;
}

AttributeError: 'str' object has no attribute 'append'

If you want to append a value to myList, use myList.append(s).

Strings are immutable -- you can't append to them.

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

PHP Adding 15 minutes to Time value

strtotime returns the current timestamp and date is to format timestamp

  $date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
  $date=date("h:i:sa",$date);

This will add 15 mins to the current time

How to initialize an array of objects in Java

thePlayers[i] = new Player(i); I just deleted the i inside Player(i); and it worked.

so the code line should be:

thePlayers[i] = new Player9();

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

Pandas index column title or name

The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:

df.index.names gives the names of a multi-index (as a Frozenlist).

Android Studio - mergeDebugResources exception

In my case I just removed the space from project folder name From: MyApp latest

To: MyApp_latest

and it worked.

Java 8, Streams to find the duplicate elements

the creating of an additional map or stream is time- and space-consuming…

Set<Integer> duplicates = numbers.stream().collect( Collectors.collectingAndThen(
  Collectors.groupingBy( Function.identity(), Collectors.counting() ),
  map -> {
    map.values().removeIf( cnt -> cnt < 2 );
    return( map.keySet() );
  } ) );  // [1, 4]


…and for the question of which is claimed to be a [duplicate]

public static int[] getDuplicatesStreamsToArray( int[] input ) {
  return( IntStream.of( input ).boxed().collect( Collectors.collectingAndThen(
      Collectors.groupingBy( Function.identity(), Collectors.counting() ),
      map -> {
        map.values().removeIf( cnt -> cnt < 2 );
        return( map.keySet() );
      } ) ).stream().mapToInt( i -> i ).toArray() );
}

Apply function to all elements of collection through LINQ

You can try something like

var foo = (from fooItems in context.footable select fooItems.fooID + 1);

Returns a list of id's +1, you can do the same with using a function to whatever you have in the select clause.

Update: As suggested from Jon Skeet this is a better version of the snippet of code I just posted:

var foo = context.footable.Select(foo => foo.fooID + 1);

what is the use of $this->uri->segment(3) in codeigniter pagination

This provides you to retrieve information from your URI strings

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

Consider this example:

http://example.com/index.php/controller/action/1stsegment/2ndsegment

it will return

$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment

Best way to get value from Collection by index

You must either wrap your collection in a list (new ArrayList(c)) or use c.toArray() since Collections have no notion of "index" or "order".