Programs & Examples On #Pyscripter

PyScripter is a free and open-source software Python integrated development environment (IDE) editor for Windows. It is built in Object Pascal and released under the MIT license.

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

center MessageBox in parent form

From a comment on Joel Spolsky's blog:

A Messagebox is always centered on the screen. You can provide an owner, but that is just for Z-order, not centering. The only way is to use Win32 hooks and center it yourself. You can find code doing that online if you search for it.

Much easier is to just write your own message box class and add centering functionality. Then you can also add default captioning, Do not show again-checkbox and making them modeless.

"Win32 hooks" probably refers to using SetWindowsHookEx as shown in this example.

Windows batch command(s) to read first line from text file

for /f "delims=" %a in (downing.txt) do echo %a & pause>nul

Prints 1st line, then waits for user to press a key to print next line. After printing required lines, press Ctrl+C to stop.

@Ross Presser: This method prints lines only, not prepend line numbers.

Could someone explain this for me - for (int i = 0; i < 8; i++)

for(<first part>; <second part>; <third part>)
{
    DoStuff();
}

This code is evaluated like this:

  1. Run <first part>
  2. If <second part> is false, skip to the end
  3. DoStuff();
  4. Run <third part>
  5. Goto 2

So for your example:

for (int i = 0; i < 8; i++)
{
    DoStuff();
}
  1. Set i to 0.
  2. If i is not less than 8, skip to the end.
  3. DoStuff();
  4. i++
  5. Goto 2

So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

In case it helps anyone, the solution mentioned in this other question worked for me when pip stopped working today after upgrading it: Pip broken after upgrading

It seems that it's an issue when a previously cached location changes, so you can refresh the cache with this command:

hash -r

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Spent a lot of time because of the auto-import. Intellij Idea somewhy imported @Service from import org.jvnet.hk2.annotations.Service; instead of import org.springframework.stereotype.Service;!

How to find specific lines in a table using Selenium?

you can try following

int index = 0;
WebElement baseTable = driver.findElement(By.className("table gradient myPage"));
List<WebElement> tableRows = baseTable.findElements(By.tagName("tr"));
tableRows.get(index).getText();

You can also iterate over tablerows to perform any function you want.

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

TypeError: 'float' object not iterable

use

range(count)

int and float are not iterable

IFrame: This content cannot be displayed in a frame

Use target="_top" attribute in anchor tag that will really work.

could not extract ResultSet in hibernate

I faced the same problem after migrating a database from online server to localhost. The schema changed so I had to define the schema manually for each table:

@Entity
@Table(name = "ESBCORE_DOMAIN", schema = "SYS")

python time + timedelta equivalent

This is a bit nasty, but:

from datetime import datetime, timedelta

now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()

error: (-215) !empty() in function detectMultiScale

Probably the face_cascade is empty. You can check if the variable is empty or not by typing following command:

face_cascade.empty()

If it is empty you will get True and this means your file is not available in the path you mentioned. Try to add complete path of xml file as follows:

r'D:\folder Name\haarcascade_frontalface_default.xml'

How to pass optional arguments to a method in C++?

To follow the example given here, but to clarify syntax with the use of header files, the function forward declaration contains the optional parameter default value.

myfile.h

void myfunc(int blah, int mode = 0);

myfile.cpp

void myfunc(int blah, int mode) /* mode = 0 */
{
    if (mode == 0)
        do_something();
     else
        do_something_else();
}

Get the first element of an array

$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key

Mockito, JUnit and Spring

If you would migrate your project to Spring Boot 1.4, you could use new annotation @MockBean for faking MyDependentObject. With that feature you could remove Mockito's @Mock and @InjectMocks annotations from your test.

Nested or Inner Class in PHP

I think I wrote an elegant solution to this problem by using namespaces. In my case, the inner class does not need to know his parent class (like the static inner class in Java). As an example I made a class called 'User' and a subclass called 'Type', used as a reference for the user types (ADMIN, OTHERS) in my example. Regards.

User.php (User class file)

<?php
namespace
{   
    class User
    {
        private $type;

        public function getType(){ return $this->type;}
        public function setType($type){ $this->type = $type;}
    }
}

namespace User
{
    class Type
    {
        const ADMIN = 0;
        const OTHERS = 1;
    }
}
?>

Using.php (An example of how to call the 'subclass')

<?php
    require_once("User.php");

    //calling a subclass reference:
    echo "Value of user type Admin: ".User\Type::ADMIN;
?>

Getting last month's date in php

The best solution I have found is this:

function subtracMonth($currentMonth, $monthsToSubtract){
        $finalMonth = $currentMonth;
        for($i=0;$i<$monthsToSubtract;$i++) {
            $finalMonth--;
            if ($finalMonth=='0'){
                $finalMonth = '12';
            }

        }
        return $finalMonth;

    }

So if we are in 3(March) and we want to subtract 5 months that would be

subtractMonth(3,5);

which would give 10(October). If the year is also desired, one could do this:

function subtracMonth($currentMonth, $monthsToSubtract){
    $finalMonth = $currentMonth;
    $totalYearsToSubtract = 0;
    for($i=0;$i<$monthsToSubtract;$i++) {
        $finalMonth--;
        if ($finalMonth=='0'){
            $finalMonth = '12';
            $totalYearsToSubtract++;
        }

    }
    //Get $currentYear
    //Calculate $finalYear = $currentYear - $totalYearsToSubtract 
    //Put resulting $finalMonth and $finalYear into an object as attributes
    //Return the object

}

Get full path of the files in PowerShell

Really annoying thing in PS 5, where $_ won't be the full path within foreach. These are the string versions of FileInfo and DirectoryInfo objects. For some reason a wildcard in the path fixes it, or use Powershell 6 or 7. You can also pipe to get-item in the middle.

Get-ChildItem -path C:\WINDOWS\System32\*.txt -Recurse | foreach { "$_" }

Get-ChildItem -path C:\WINDOWS\System32 -Recurse | get-item | foreach { "$_" }

This seems to have been an issue with .Net that got resolved in .Net Core (Powershell 7): Stringification behavior of FileInfo / Directory instances has changed since v6.0.2 #7132

How to play YouTube video in my Android application?

Use YouTube Android Player API.

activity_main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.andreaskonstantakos.vfy.MainActivity">

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:layout_centerHorizontal="true"
    android:id="@+id/youtube_player"
    android:layout_alignParentTop="true" />

<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />


</RelativeLayout>

MainActivity.java:

package com.example.andreaskonstantakos.vfy;


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;



public class MainActivity extends YouTubeBaseActivity {

YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;

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

     youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
     button = (Button) findViewById(R.id.button);


     onInitializedListener = new YouTubePlayer.OnInitializedListener(){

         @Override
         public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

            youTubePlayer.loadVideo("Hce74cEAAaE");

             youTubePlayer.play();
     }

         @Override
         public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

         }
     };

    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
        }
    });
}
}

and the PlayerConfig.java class:

    package com.example.andreaskonstantakos.vfy;

/**
 * Created by Andreas Konstantakos on 13/4/2017.
 */

public class PlayerConfig {

PlayerConfig(){}

public static final String API_KEY = 
"xxxxx";
}

Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk

How to iterate for loop in reverse order in swift?

Updated for Swift 3

The answer below is a summary of the available options. Choose the one that best fits your needs.

reversed: numbers in a range

Forward

for index in 0..<5 {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

Backward

for index in (0..<5).reversed() {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

reversed: elements in SequenceType

let animals = ["horse", "cow", "camel", "sheep", "goat"]

Forward

for animal in animals {
    print(animal)
}

// horse
// cow
// camel
// sheep
// goat

Backward

for animal in animals.reversed() {
    print(animal)
}

// goat
// sheep
// camel
// cow
// horse

reversed: elements with an index

Sometimes an index is needed when iterating through a collection. For that you can use enumerate(), which returns a tuple. The first element of the tuple is the index and the second element is the object.

let animals = ["horse", "cow", "camel", "sheep", "goat"]

Forward

for (index, animal) in animals.enumerated() {
    print("\(index), \(animal)")
}

// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat

Backward

for (index, animal) in animals.enumerated().reversed()  {
    print("\(index), \(animal)")
}

// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse

Note that as Ben Lachman noted in his answer, you probably want to do .enumerated().reversed() rather than .reversed().enumerated() (which would make the index numbers increase).

stride: numbers

Stride is way to iterate without using a range. There are two forms. The comments at the end of the code show what the range version would be (assuming the increment size is 1).

startIndex.stride(to: endIndex, by: incrementSize)      // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex

Forward

for index in stride(from: 0, to: 5, by: 1) {
    print(index)
}

// 0
// 1
// 2
// 3
// 4

Backward

Changing the increment size to -1 allows you to go backward.

for index in stride(from: 4, through: 0, by: -1) {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

Note the to and through difference.

stride: elements of SequenceType

Forward by increments of 2

let animals = ["horse", "cow", "camel", "sheep", "goat"]

I'm using 2 in this example just to show another possibility.

for index in stride(from: 0, to: 5, by: 2) {
    print("\(index), \(animals[index])")
}

// 0, horse
// 2, camel
// 4, goat

Backward

for index in stride(from: 4, through: 0, by: -1) {
    print("\(index), \(animals[index])")
}

// 4, goat
// 3, sheep 
// 2, camel
// 1, cow  
// 0, horse 

Notes

How to print a date in a regular format?

Or even

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

Out: '25.12.2013

or

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

Out: 'Today - 25.12.2013'

"{:%A}".format(date.today())

Out: 'Wednesday'

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

Out: '__main____2014.06.09__16-56.log'

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

Rails: How can I rename a database column in a Ruby on Rails migration?

If your code is not shared with other one, then best option is to do just rake db:rollback then edit your column name in migration and rake db:migrate. Thats it

And you can write another migration to rename the column

 def change
    rename_column :table_name, :old_name, :new_name
  end

Thats it.

Can someone explain Microsoft Unity?

Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.

Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.

Without IoC:

public class MyClass
{
   IMyService _myService; 

   public MyClass()
   {
      _myService = new SomeConcreteService();    
   }
}

With IoC container:

public class MyClass
{
   IMyService _myService; 

   public MyClass(IMyService myService)
   {
      _myService = myService;    
   }
}

Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)

With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.

Using StructureMap, configuring the container looks like this:

StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();

So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.

That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).

Final step: when you create your MyClass, you would do this:

var myClass = ObjectFactory.GetInstance<MyClass>();

Hope that helps. Feel free to e-mail me.

Center the content inside a column in Bootstrap 4

Add class text-center to your column:

<div class="col text-center">
I am centered
</div>

"Please provide a valid cache path" error in laravel

So apparently what happened was when I was duplicating my project the framework folder inside my storage folder was not copied to the new directory, this cause my error.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:

now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.

First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.

# Const IsDebug = True

Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc

ExitHere:
    On Error Resume Next
    ' Close objects and stuff here
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
    #If IsDebug Then
        Stop            ' Used for troubleshooting - Then press F8 to step thru code 
        Resume          ' Resume will take you to the line that errored out
    #Else
        Resume ExitHere ' Exit procedure during normal running
    #End If
End Sub

Note: the exception to Resume is if the error occurs in a sub-procedure without an error handling routine, then Resume will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.

There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:

    Resume ExitHere         ' Normally exits during production
    Resume                  ' Never will get here
Exit Sub

It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.

Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.

Cannot find control with name: formControlName in angular reactive form

In your HTML code

<form [formGroup]="userForm">
    <input type="text" class="form-control"  [value]="item.UserFirstName" formControlName="UserFirstName">
    <input type="text" class="form-control"  [value]="item.UserLastName" formControlName="UserLastName">
</form>

In your Typescript code

export class UserprofileComponent implements OnInit {
    userForm: FormGroup;
    constructor(){ 
       this.userForm = new FormGroup({
          UserFirstName: new FormControl(),
          UserLastName: new FormControl()
       });
    }
}

This works perfectly, it does not give any error.

NSUserDefaults - How to tell if a key exists

As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.

NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){

    NSLog(@"mykey found");
}

Test if registry value exists

I would go with the function Get-RegistryValue. In fact it gets requested values (so that it can be used not only for testing). As far as registry values cannot be null, we can use null result as a sign of a missing value. The pure test function Test-RegistryValue is also provided.

# This function just gets $true or $false
function Test-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    $key -and $null -ne $key.GetValue($name, $null)
}

# Gets the specified registry value or $null if it is missing
function Get-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    if ($key) {
        $key.GetValue($name, $null)
    }
}

# Test existing value
Test-RegistryValue HKCU:\Console FontFamily
$val = Get-RegistryValue HKCU:\Console FontFamily
if ($val -eq $null) { 'missing value' } else { $val }

# Test missing value
Test-RegistryValue HKCU:\Console missing
$val = Get-RegistryValue HKCU:\Console missing
if ($val -eq $null) { 'missing value' } else { $val }

OUTPUT:

True
54
False
missing value

Unable to execute dex: method ID not in [0, 0xffff]: 65536

The below code helps, if you use Gradle. Allows you to easily remove unneeded Google services (presuming you're using them) to get back below the 65k threshold. All credit to this post: https://gist.github.com/dmarcato/d7c91b94214acd936e42

Edit 2014-10-22: There's been a lot of interesting discussion on the gist referenced above. TLDR? look at this one: https://gist.github.com/Takhion/10a37046b9e6d259bb31

Paste this code at the bottom of your build.gradle file and adjust the list of google services you do not need:

def toCamelCase(String string) {
    String result = ""
    string.findAll("[^\\W]+") { String word ->
        result += word.capitalize()
    }
    return result
}

afterEvaluate { project ->
    Configuration runtimeConfiguration = project.configurations.getByName('compile')
    ResolutionResult resolution = runtimeConfiguration.incoming.resolutionResult
    // Forces resolve of configuration
    ModuleVersionIdentifier module = resolution.getAllComponents().find { it.moduleVersion.name.equals("play-services") }.moduleVersion

    String prepareTaskName = "prepare${toCamelCase("${module.group} ${module.name} ${module.version}")}Library"
    File playServiceRootFolder = project.tasks.find { it.name.equals(prepareTaskName) }.explodedDir

    Task stripPlayServices = project.tasks.create(name: 'stripPlayServices', group: "Strip") {
        inputs.files new File(playServiceRootFolder, "classes.jar")
        outputs.dir playServiceRootFolder
        description 'Strip useless packages from Google Play Services library to avoid reaching dex limit'

        doLast {
            copy {
                from(file(new File(playServiceRootFolder, "classes.jar")))
                into(file(playServiceRootFolder))
                rename { fileName ->
                    fileName = "classes_orig.jar"
                }
            }
            tasks.create(name: "stripPlayServices" + module.version, type: Jar) {
                destinationDir = playServiceRootFolder
                archiveName = "classes.jar"
                from(zipTree(new File(playServiceRootFolder, "classes_orig.jar"))) {
                    exclude "com/google/ads/**"
                    exclude "com/google/android/gms/analytics/**"
                    exclude "com/google/android/gms/games/**"
                    exclude "com/google/android/gms/plus/**"
                    exclude "com/google/android/gms/drive/**"
                    exclude "com/google/android/gms/ads/**"
                }
            }.execute()
            delete file(new File(playServiceRootFolder, "classes_orig.jar"))
        }
    }

    project.tasks.findAll { it.name.startsWith('prepare') && it.name.endsWith('Dependencies') }.each { Task task ->
        task.dependsOn stripPlayServices
    }
}

How to validate an e-mail address in swift?

Updated answer @Arsonik answer to Swift 2.2, using less verbose code than other offered solutions:

extension String {
    func isValidEmail() -> Bool {
        let regex = try? NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
        return regex?.firstMatchInString(self, options: [], range: NSMakeRange(0, self.characters.count)) != nil
    }
}

How to convert list of key-value tuples into dictionary?

l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)

Disable automatic sorting on the first column when using jQuery DataTables

Set the aaSorting option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.

"aaSorting": []

The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').

How to implement the Softmax function in Python

Everybody seems to post their solution so I'll post mine:

def softmax(x):
    e_x = np.exp(x.T - np.max(x, axis = -1))
    return (e_x / e_x.sum(axis=0)).T

I get the exact same results as the imported from sklearn:

from sklearn.utils.extmath import softmax

Request Permission for Camera and Library in iOS 10 - Info.plist

Great way of implementing Camera session in Swift 5, iOS 13

https://github.com/egzonpllana/CameraSession

Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.

Through the app you can find these camera session implemented:

  • Native camera to take a picture or record a video.
  • Native way of importing photos and videos.
  • The custom way to select assets like photos and videos, with an option to select one or more assets from the Library.
  • Custom camera to take a photo(s) or video(s), with options to hold down the button and record.
  • Separated camera permission requests.

The custom camera features like torch and rotate camera options.

Save results to csv file with Python

You can close files not csv.writer object, it should be:

f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()

How to parseInt in Angular.js

var app = angular.module('myApp', [])

app.controller('MainCtrl', ['$scope', function($scope){
   $scope.num1 = 1;
   $scope.num2 = 1;
   $scope.total = parseInt($scope.num1 + $scope.num2);

}]);

Demo: parseInt with AngularJS

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

Checking if a SQL Server login already exists

As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

How to play an android notification sound

You can now do this by including the sound when building a notification rather than calling the sound separately.

//Define Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
        .setSmallIcon(icon)
        .setContentTitle(title)
        .setContentText(message)
        .setSound(soundUri); //This sets the sound to play

//Display notification
notificationManager.notify(0, mBuilder.build());

link_to image tag. how to add class to a tag

Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)

<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>

Hope this helps!

Getting value of select (dropdown) before change

(function() {

    var value = $('[name=request_status]').change(function() {
        if (confirm('You are about to update the status of this request, please confirm')) {
            $(this).closest('form').submit(); // submit the form
        }else {
            $(this).val(value); // set the value back
        }
    }).val();
})();

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

Drawing a line/path on Google Maps

public class MainActivity extends FragmentActivity  {


  List<Overlay> mapOverlays;
  GeoPoint point1, point2;
  LocationManager locManager;
  Drawable drawable;
  Document document;
  GMapV2GetRouteDirection v2GetRouteDirection;
  LatLng fromPosition;
  LatLng toPosition;
  GoogleMap mGoogleMap;
  MarkerOptions markerOptions;
  Location location ;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        v2GetRouteDirection = new GMapV2GetRouteDirection();
      SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
        mGoogleMap = supportMapFragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.getUiSettings().setCompassEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
        mGoogleMap.setTrafficEnabled(true);
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        markerOptions = new MarkerOptions();
        fromPosition = new LatLng(11.663837, 78.147297);
        toPosition = new LatLng(11.723512, 78.466287);
        GetRouteTask getRoute = new GetRouteTask();
        getRoute.execute();
  }
  /**
   *
   * @author VIJAYAKUMAR M
   * This class Get Route on the map
   *
   */
  private class GetRouteTask extends AsyncTask<String, Void, String> {

        private ProgressDialog Dialog;
        String response = "";
        @Override
        protected void onPreExecute() {
              Dialog = new ProgressDialog(MainActivity.this);
              Dialog.setMessage("Loading route...");
              Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
              //Get All Route values
                         document = v2GetRouteDirection.getDocument(fromPosition, toPosition,          GMapV2GetRouteDirection.MODE_DRIVING);
                    response = "Success";
              return response;

        }

        @Override
        protected void onPostExecute(String result) {
              mGoogleMap.clear();
              if(response.equalsIgnoreCase("Success")){
              ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
              PolylineOptions rectLine = new PolylineOptions().width(10).color(
                          Color.RED);

              for (int i = 0; i < directionPoint.size(); i++) {
                    rectLine.add(directionPoint.get(i));
              }
              // Adding route on the map
              mGoogleMap.addPolyline(rectLine);
              markerOptions.position(toPosition);
              markerOptions.draggable(true);
              mGoogleMap.addMarker(markerOptions);

              }

              Dialog.dismiss();
        }
  }
  @Override
  protected void onStop() {
        super.onStop();
        finish();
    }
 }

Route Helper class

 public class GMapV2GetRouteDirection {
  public final static String MODE_DRIVING = "driving";
  public final static String MODE_WALKING = "walking";

  public GMapV2GetRouteDirection() { }

  public Document getDocument(LatLng start, LatLng end, String mode) {
    String url = "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin=" + start.latitude + "," + start.longitude 
            + "&destination=" + end.latitude + "," + end.longitude
            + "&sensor=false&units=metric&mode=driving";

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }

  public String getDurationText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DurationText", node2.getTextContent());
    return node2.getTextContent();
 }

 public int getDurationValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("duration");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getDistanceText (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DistanceText", node2.getTextContent());
    return node2.getTextContent();
  }

  public int getDistanceValue (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("distance");
    Node node1 = nl1.item(0);
    NodeList nl2 = node1.getChildNodes();
    Node node2 = nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DistanceValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
  }

  public String getStartAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("start_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getEndAddress (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("end_address");
    Node node1 = nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
  }

  public String getCopyRights (Document doc) {
    NodeList nl1 = doc.getElementsByTagName("copyrights");
    Node node1 = nl1.item(0);
    Log.i("CopyRights", node1.getTextContent());
    return node1.getTextContent();
  }

   public ArrayList<LatLng> getDirection (Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for(int j = 0 ; j < arr.size() ; j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
 }

 private int getNodeIndex(NodeList nl, String nodename) {
    for(int i = 0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
 }

 private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
  }
 }

Display loading image while post with ajax

_x000D_
_x000D_
//$(document).ready(function(){_x000D_
//  $("a").click(function(event){_x000D_
//  event.preventDefault();_x000D_
//  $("div").html("This is prevent link...");_x000D_
// });_x000D_
//});   _x000D_
_x000D_
$(document).ready(function(){_x000D_
 $("a").click(function(event){_x000D_
  event.preventDefault();_x000D_
  $.ajax({_x000D_
   beforeSend: function(){_x000D_
    $('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
   },_x000D_
   success : function(){_x000D_
    setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
   }_x000D_
  });_x000D_
 });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  _x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_

How to convert Base64 String to javascript file object like as from file input form?

This is the latest async/await pattern solution.

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

ASP.Net MVC: Calling a method from a view

This is how you call an instance method on the Controller:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

This is how you call a static method in any class

@{
    SomeClass.Method();
}

This will work assuming the method is public and visible to the view.

GoogleMaps API KEY for testing

Updated Answer

As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

This answer is no longer valid

As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I have made a simulation of the problem. looks like the issue is how we should Access Object Properties Dynamically Using Bracket Notation in Typescript

interface IUserProps {
  name: string;
  age: number;
}

export default class User {
  constructor(private data: IUserProps) {}

  get(propName: string): string | number {
    return this.data[propName as keyof IUserProps];
  }
}

I found a blog that might be helpful to understand this better.

here is a link https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/

Cannot open backup device. Operating System error 5

Share this folder and use UNC path, by example: \pc\backups\mydb.bak

Then You can stop share.

Not very elegant, but it resolves all permissions problems (You need to give permissions to share as well, as mentioned above)

Uncaught TypeError: Cannot read property 'length' of undefined

You are not passing the variable correctly. One fast solution is to make a global variable like this:

var global_json_data;
$(document).ready(function() {
    var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
    var string_data ="";
    var json_data = $.ajax({
        dataType: 'json', // Return JSON
        url: json_source,
        success: function(data){
            var data_obj = [];
            for (i=0; i<data.feed.entry.length; i++){
                var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
                data_obj.push(el)};

            console.log("data grabbed");  
            global_json_data =   data_obj;

            return data_obj;


        },      

        error: function(jqXHR, textStatus, errorThrown){ 
                        $('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    }); 

    $(':submit').click(function(event){
        var json_data = global_json_data;
        event.preventDefault();
        console.log(json_data.length);

        //function
        if ($('#place').val() !=''){
            var copy_string = $('#place').val();
            var converted_string = copy_string;
            for (i=0; i<json_data.length; i++){
                //console_log(data.feed.entry[i].title['$t']);
                converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'], 
                    '<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
            }  
            $('#results_box').text(converted_string).html();
        }
    });

});//document ready end 

How do I read all classes from a Java package in the classpath?

Back when applets were common place, one might have a URL on the classpath. When the classloader required a class, it would search all the locations on the classpath, including http resources. Because you can have things like URLs and directories on the classpath, there is no easy way to get a definitive list of the classes.

However, you can get pretty close. Some of the Spring libraries are doing this now. You can get all the jar's on the classpath, and open them up like files. You can then take this list of files, and create a data structure containing your classes.

Windows batch: echo without new line

Using: echo | set /p= or <NUL set /p= will both work to suppress the newline.

However, this can be very dangerous when writing more advanced scripts when checking the ERRORLEVEL becomes important as setting set /p= without specifying a variable name will set the ERRORLEVEL to 1.

A better approach would be to just use a dummy variable name like so:
echo | set /p dummyName=Hello World

This will produce exactly what you want without any sneaky stuff going on in the background as I had to find out the hard way, but this only works with the piped version; <NUL set /p dummyName=Hello will still raise the ERRORLEVEL to 1.

Maximum on http header values?

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5. Various ad hoc limitations on individual header field length are found in practice, often depending on the specific field semantics.

HTTP Header values are restricted by server implementations. Http specification doesn't restrict header size.

A server that receives a request header field, or set of fields, larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code. Ignoring such header fields would increase the server's vulnerability to request smuggling attacks (Section 9.5).

Most servers will return 413 Entity Too Large or appropriate 4xx error when this happens.

A client MAY discard or truncate received header fields that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics.

Uncapped HTTP header size keeps the server exposed to attacks and can bring down its capacity to serve organic traffic.

Source

How can I pad an int with leading zeros when using cout << operator?

Another way to achieve this is using old printf() function of C language

You can use this like

int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);

This will print 09 - 01 - 0001 on the console.

You can also use another function sprintf() to write formatted output to a string like below:

int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;

Don't forget to include stdio.h header file in your program for both of these functions

Thing to be noted:

You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d format specifier than this will not fill 2 in blank spaces. This will set pad to 24 and will fill blank spaces.

getaddrinfo: nodename nor servname provided, or not known

For me, I had to change a line of code in my local_env.yml to get the rspec tests to run.

I had originally had:

REDIS_HOST: 'redis'

and changed it to:

REDIS_HOST: 'localhost'

and the test ran fine.

Check if value exists in enum in TypeScript

TypeScript v3.7.3

export enum YourEnum {
   enum1 = 'enum1',
   enum2 = 'enum2',
   enum3 = 'enum3',
}

const status = 'enumnumnum';

if (!(status in YourEnum)) {
     throw new UnprocessableEntityResponse('Invalid enum val');
}

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

Object of class stdClass could not be converted to string - laravel

This is easy all you need to do is something like this Grab your contents like this

  $result->get(filed1) = 'some modification';
  $result->get(filed2) = 'some modification2';

Redirect after Login on WordPress

This may help. Peter's Login Redirect

Redirect users to different locations after logging in and logging out.

Define a set of redirect rules for specific users, users with specific roles, users with specific capabilities, and a blanket rule for all other users. Also, set a redirect URL for post-registration. This is all managed in Settings > Login/logout redirects.

You can use the syntax [variable]username[/variable] in your URLs so that the system will build a dynamic URL upon each login, replacing that text with the user's username. In addition to username, there is "userslug", "homeurl", "siteurl", "postid-23", "http_referer" and you can also add your own custom URL "variables"...

LAST_INSERT_ID() MySQL

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

How do I close an Android alertdialog

AlertDialog.Builder ad = new AlertDialog.Builder(this);  
ad.setTitle("Unanswered Questions");  
ad.setMessage("You have not answered all the questions.");   
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int id) {  
     dialog.dismiss(); 
}  
});  
ad.show(); 

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Android Studio: Where is the Compiler Error Output Window?

Run

gradlew --stacktrace 

in a terminal to see the full report

for me it was

Task :app:compileDebugJavaWithJavac FAILED javacTask: source release 1.8 requires target release 1.8

so i added

 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

in app.gradle file / android and the build completed successfully

How to get htaccess to work on MAMP

The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with

RewriteBase /

Which doesn't seem to work in MAMP...at least for me.

Random strings in Python

You haven't really said much about what sort of random string you need. But in any case, you should look into the random module.

A very simple solution is pasted below.

import random

def randstring(length=10):
    valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return ''.join((random.choice(valid_letters) for i in xrange(length)))

print randstring()
print randstring(20)

Updating state on props change in React Form

componentWillReceiveProps is being deprecated because using it "often leads to bugs and inconsistencies".

If something changes from the outside, consider resetting the child component entirely with key.

Providing a key prop to the child component makes sure that whenever the value of key changes from the outside, this component is re-rendered. E.g.,

<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

On its performance:

While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.

How to copy static files to build directory with Webpack?

I was stuck here too. copy-webpack-plugin worked for me.

However, 'copy-webpack-plugin' was not necessary in my case (i learned later).

webpack ignores root paths
example

<img src="/images/logo.png'>

Hence, to make this work without using 'copy-webpack-plugin' use '~' in paths

<img src="~images/logo.png'>

'~' tells webpack to consider 'images' as a module

note: you might have to add the parent directory of images directory in

resolve: {
    modules: [
        'parent-directory of images',
        'node_modules'
    ]
}

Visit https://vuejs-templates.github.io/webpack/static.html

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

Pandas Replace NaN with blank/empty string

Try this,

add inplace=True

import numpy as np
df.replace(np.NaN, ' ', inplace=True)

Missing visible-** and hidden-** in Bootstrap v4

i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs                { display:table !important; }
tr.visible-xs                   { display:table-row !important; }
th.visible-xs, td.visible-xs    { display:table-cell !important; }

.visible-xs                 { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}

@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }

.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}

@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }

.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}

@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }

.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}

@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }

.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}

@media (max-width:575px)                        { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px)  { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px)  { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px)                       { .hidden-xl{display:none !important;} }
</pre>

How to make a new List in Java

As an option you can use double brace initialization here:

List<String> list = new ArrayList<String>(){
  {
   add("a");
   add("b");
  }
};

How to add data to DataGridView

LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

Listing only directories using ls in Bash?

Here is what I am using

ls -d1 /Directory/Path/*;

How to perform case-insensitive sorting in JavaScript?

This may help if you have struggled to understand:

var array = ["sort", "Me", "alphabetically", "But", "Ignore", "case"];
console.log('Unordered array ---', array, '------------');

array.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    console.log("Compare '" + a + "' and '" + b + "'");

    if( a == b) {
        console.log('Comparison result, 0 --- leave as is ');
        return 0;
    }
    if( a > b) {
        console.log('Comparison result, 1 --- move '+b+' to before '+a+' ');
        return 1;
    }
    console.log('Comparison result, -1 --- move '+a+' to before '+b+' ');
    return -1;


});

console.log('Ordered array ---', array, '------------');


// return logic

/***
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
***/

http://jsfiddle.net/ianjamieson/wmxn2ram/1/

How to change sender name (not email address) when using the linux mail command for autosending mail?

You can use the "-r" option to set the sender address:

mail -r [email protected] -s ...

In case you also want to include your real name in the from-field, you can use the following format

mail -r "[email protected] (My Name)" -s "My Subject" ...

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Array oList = ((from m in dc.Reviews
                           join n in dc.Users on m.authorID equals n.userID
                           orderby m.createdDate descending
                           where m.foodID == _id                      
                           select new
                           {
                               authorID = m.authorID,
                               createdDate = m.createdDate,
                               review = m.review1,
                               author = n.username,
                               profileImgUrl = n.profileImgUrl
                           }).Take(2)).ToArray();

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me, it was due to the "return type" of the test method. It should be "void"

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

What is recursion and when should I use it?

Recursion is solving a problem with a function that calls itself. A good example of this is a factorial function. Factorial is a math problem where factorial of 5, for example, is 5 * 4 * 3 * 2 * 1. This function solves this in C# for positive integers (not tested - there may be a bug).

public int Factorial(int n)
{
    if (n <= 1)
        return 1;

    return n * Factorial(n - 1);
}

Lumen: get URL parameter in a Blade view

Laravel 5.6:

{{ Request::query('parameter') }}

jquery: get id from class selector

Nothing from this examples , works for me

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });

How to automatically add user account AND password with a Bash script?

I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin though it didn't quite work for me as written. This however worked for me.

echo -e "$password\n$password\n" | sudo passwd $user

-e is to recognize \n as new line.

sudo is root access for Ubuntu.

The double quotes are to recognize $ and expand the variables.

The above command passes the password and a new line, two times, to passwd, which is what passwd requires.

If not using variables, I think this probably works.

echo -e 'password\npassword\n' | sudo passwd username

Single quotes should suffice here.

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

How to pull specific directory with git

Tried and tested this works !

mkdir <directory name> ;  //Same directory name as the one you want to pull
cd <directory name>;
git remote add origin <GIT_URL>;
git checkout -b '<branch name>';
git config core.sparsecheckout true;
echo <directory name>/ >> .git/info/sparse-checkout;
git pull origin <pull branch name>

Hope this was helpful!

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How often should you use git-gc?

You don't have to use git gc very often, because git gc (Garbage collection) is run automatically on several frequently used commands:

git pull
git merge
git rebase
git commit

Source: git gc best practices and FAQS

How can I display a pdf document into a Webview?

This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

Javascript/DOM: How to remove all events of a DOM object?

I am not sure what you mean with remove all events. Remove all handlers for a specific type of event or all event handlers for one type?

Remove all event handlers

If you want to remove all event handlers (of any type), you could clone the element and replace it with its clone:

var clone = element.cloneNode(true);

Note: This will preserve attributes and children, but it will not preserve any changes to DOM properties.


Remove "anonymous" event handlers of specific type

The other way is to use removeEventListener() but I guess you already tried this and it didn't work. Here is the catch:

Calling addEventListener to an anonymous function creates a new listener each time. Calling removeEventListener to an anonymous function has no effect. An anonymous function creates a unique object each time it is called, it is not a reference to an existing object though it may call one. When adding an event listener in this manner be sure it is added only once, it is permanent (cannot be removed) until the object it was added to, is destroyed.

You are essentially passing an anonymous function to addEventListener as eventReturner returns a function.

You have two possibilities to solve this:

  1. Don't use a function that returns a function. Use the function directly:

     function handler() {
         dosomething();
     }
    
     div.addEventListener('click',handler,false);
    
  2. Create a wrapper for addEventListener that stores a reference to the returned function and create some weird removeAllEvents function:

     var _eventHandlers = {}; // somewhere global
    
     const addListener = (node, event, handler, capture = false) => {
       if (!(event in _eventHandlers)) {
         _eventHandlers[event] = []
       }
       // here we track the events and their nodes (note that we cannot
       // use node as Object keys, as they'd get coerced into a string
       _eventHandlers[event].push({ node: node, handler: handler, capture: capture })
       node.addEventListener(event, handler, capture)
     }
    
     const removeAllListeners = (targetNode, event) => {
       // remove listeners from the matching nodes
       _eventHandlers[event]
         .filter(({ node }) => node === targetNode)
         .forEach(({ node, handler, capture }) => node.removeEventListener(event, handler, capture))
    
       // update _eventHandlers global
       _eventHandlers[event] = _eventHandlers[event].filter(
         ({ node }) => node !== targetNode,
       )
     }
    

And then you could use it with:

    addListener(div, 'click', eventReturner(), false)
    // and later
    removeAllListeners(div, 'click')

DEMO

Note: If your code runs for a long time and you are creating and removing a lot of elements, you would have to make sure to remove the elements contained in _eventHandlers when you destroy them.

SQL Server IN vs. EXISTS Performance

So, IN is not the same as EXISTS nor it will produce the same execution plan.

Usually EXISTS is used in a correlated subquery, that means you will JOIN the EXISTS inner query with your outer query. That will add more steps to produce a result as you need to solve the outer query joins and the inner query joins then match their where clauses to join both.

Usually IN is used without correlating the inner query with the outer query, and that can be solved in only one step (in the best case scenario).

Consider this:

  1. If you use IN and the inner query result is millions of rows of distinct values, it will probably perform SLOWER than EXISTS given that the EXISTS query is performant (has the right indexes to join with the outer query).

  2. If you use EXISTS and the join with your outer query is complex (takes more time to perform, no suitable indexes) it will slow the query by the number of rows in the outer table, sometimes the estimated time to complete can be in days. If the number of rows is acceptable for your given hardware, or the cardinality of data is correct (for example fewer DISTINCT values in a large data set) IN can perform faster than EXISTS.

  3. All of the above will be noted when you have a fair amount of rows on each table (by fair I mean something that exceeds your CPU processing and/or ram thresholds for caching).

So the ANSWER is it DEPENDS. You can write a complex query inside IN or EXISTS, but as a rule of thumb, you should try to use IN with a limited set of distinct values and EXISTS when you have a lot of rows with a lot of distinct values.

The trick is to limit the number of rows to be scanned.

Regards,

MarianoC

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

PHP - Debugging Curl

If you just want a very quick way to debug the result:

$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"

Check if XML Element exists

//I am finding childnode ERNO at 2nd but last place

If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), "ERNO", CompareMethod.Text) = 0 Then
                xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c
            Else
                elem = xmldoc.CreateElement("ERNo")
                elem.InnerText = c.ToString
                root.ChildNodes(i).AppendChild(elem)
            End If

How to find encoding of a file via script on Linux?

If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.

Copying a HashMap in Java

There is a small (HUGE) understatement here. If you want to copy a HashMap with nested structures, HashMap.putAll() will copy by reference, because it doesn't know how to exactly copy your object. For example:

import java.util.*;
class Playground {
    public static void main(String[ ] args) {
        Map<Integer, Map<Integer,List<Float>>> dataA = new HashMap<>();
        Map<Integer, Map<Integer,List<Float>>> dataB = new HashMap<>();

        dataA.put(1, new HashMap<>());
        dataB.putAll(dataA);

        assert(dataB.get(1).size() == 0);

        dataA.get(1).put(2, new ArrayList<>());

        if (dataB.get(1).size() == 1) { // true
            System.out.println(
                "Sorry object reference was copied - not the values");
        }
    }
}

So basically you will need to copy the fields yourself like here

List <Float> aX = new ArrayList<>(accelerometerReadingsX);
List <Float> aY = new ArrayList<>(accelerometerReadingsY);

List <Float> gX = new ArrayList<>(gyroscopeReadingsX);
List <Float> gY = new ArrayList<>(gyroscopeReadingsY);

Map<Integer, Map<Integer, Float>> readings = new HashMap<>();

Map<Integer,List<Float>> accelerometerReadings = new HashMap<>();
accelerometerReadings.put(X_axis, aX);
accelerometerReadings.put(Y_axis, aY);
readings.put(Sensor.TYPE_ACCELEROMETER, accelerometerReadings);

Map<Integer,List<Float>> gyroscopeReadings = new HashMap<>();
gyroscopeReadings.put(X_axis, gX);
gyroscopeReadings.put(Y_axis, gY);
readings.put(Sensor.TYPE_GYROSCOPE, gyroscopeReadings);

How do I link a JavaScript file to a HTML file?

This is how you link a JS file in HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script> - tag is used to define a client-side script, such as a JavaScript.

type - specify the type of the script

src - script file name and path

How to select option in drop down protractorjs e2e tests

Here is how to do it by either option value or index. This example is a bit crude, but it shows how to do what you want:

html:

<mat-form-field id="your-id">
    <mat-select>
        <mat-option [value]="1">1</mat-option>
        <mat-option [value]="2">2</mat-option>
    </mat-select>
</mat-form-field>

ts:

function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');    

        for (let optionId of optionIds) {
          const option = element(by.id(optionId));
          option.getText().then((text) => {
            if (text === valueToFind) {
              option.click();
            }
          });
        }
      });
  });
}

function selectOptionByOptionIndex(selectFormFieldElementId, index) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');

        const optionId = optionIds[index];
        const option = element(by.id(optionId));
        option.click();
      });
  });
}

selectOptionByOptionValue('your-id', '1'); //selects first option
selectOptionByOptionIndex('your-id', 1); //selects second option

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Is there a function to split a string in PL/SQL?

You can use regexp_substr(). Example:

create or replace type splitTable_Type is table of varchar2(100);

declare
    l_split_table splitTable_Type;
begin
  select
      regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
  bulk collect into
      l_split_table
  from dual
  connect by
      regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;
end;

The query iterates through the comma separated string, searches for the comma (,) and then splits the string by treating the comma as delimiter. It returns the string as a row, whenever it hits a delimiter.

level in statement regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) refers to a pseudocolumn in Oracle which is used in a hierarchical query to identify the hierarchy level in numeric format: level in connect by

frequent issues arising in android view, Error parsing XML: unbound prefix

I'll throw in a little more for the newbies and for folks, like myself, that don't understand XML.

The answers above a pretty good, but the general answer is that you need a namespace for any namespace used in the config.xml file.

Translation: Any XML tag name that has is a tag with a namespace where blah is the namespace and fubar is the XML tag. The namespace lets you use many different tools to interpret the XML with their own tag names. For example, Intel XDK uses the namespace intelxdk and android uses android. Thus you need the following namespaces or the build throws up blood (i.e. Error parsing XML: unbound prefix) which is translated to: You used a namespace, but did not define it.

  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:intelxdk="http://xdk.intel.com/ns/v1"

Convert pandas dataframe to NumPy array

df.to_numpy() is better than df.values, here's why.*

It's time to deprecate your usage of values and as_matrix().

pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects:

  1. to_numpy(), which is defined on Index, Series, and DataFrame objects, and
  2. array, which is defined on Index and Series objects only.

If you visit the v0.24 docs for .values, you will see a big red warning that says:

Warning: We recommend using DataFrame.to_numpy() instead.

See this section of the v0.24.0 release notes, and this answer for more information.

* - to_numpy() is my recommended method for any production code that needs to run reliably for many versions into the future. However if you're just making a scratchpad in jupyter or the terminal, using .values to save a few milliseconds of typing is a permissable exception. You can always add the fit n finish later.



Towards Better Consistency: to_numpy()

In the spirit of better consistency throughout the API, a new method to_numpy has been introduced to extract the underlying NumPy array from DataFrames.

# Setup
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, 
                  index=['a', 'b', 'c'])

# Convert the entire DataFrame
df.to_numpy()
# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])

# Convert specific columns
df[['A', 'C']].to_numpy()
# array([[1, 7],
#        [2, 8],
#        [3, 9]])

As mentioned above, this method is also defined on Index and Series objects (see here).

df.index.to_numpy()
# array(['a', 'b', 'c'], dtype=object)

df['A'].to_numpy()
#  array([1, 2, 3])

By default, a view is returned, so any modifications made will affect the original.

v = df.to_numpy()
v[0, 0] = -1
 
df
   A  B  C
a -1  4  7
b  2  5  8
c  3  6  9

If you need a copy instead, use to_numpy(copy=True).


pandas >= 1.0 update for ExtensionTypes

If you're using pandas 1.x, chances are you'll be dealing with extension types a lot more. You'll have to be a little more careful that these extension types are correctly converted.

a = pd.array([1, 2, None], dtype="Int64")                                  
a                                                                          

<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64 

# Wrong
a.to_numpy()                                                               
# array([1, 2, <NA>], dtype=object)  # yuck, objects

# Correct
a.to_numpy(dtype='float', na_value=np.nan)                                 
# array([ 1.,  2., nan])

# Also correct
a.to_numpy(dtype='int', na_value=-1)
# array([ 1,  2, -1])

This is called out in the docs.


If you need the dtypes in the result...

As shown in another answer, DataFrame.to_records is a good way to do this.

df.to_records()
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', 'O'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

This cannot be done with to_numpy, unfortunately. However, as an alternative, you can use np.rec.fromrecords:

v = df.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', '<U1'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

Performance wise, it's nearly the same (actually, using rec.fromrecords is a bit faster).

df2 = pd.concat([df] * 10000)

%timeit df2.to_records()
%%timeit
v = df2.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())

12.9 ms ± 511 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
9.56 ms ± 291 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Rationale for Adding a New Method

to_numpy() (in addition to array) was added as a result of discussions under two GitHub issues GH19954 and GH23623.

Specifically, the docs mention the rationale:

[...] with .values it was unclear whether the returned value would be the actual array, some transformation of it, or one of pandas custom arrays (like Categorical). For example, with PeriodIndex, .values generates a new ndarray of period objects each time. [...]

to_numpy aims to improve the consistency of the API, which is a major step in the right direction. .values will not be deprecated in the current version, but I expect this may happen at some point in the future, so I would urge users to migrate towards the newer API, as soon as you can.



Critique of Other Solutions

DataFrame.values has inconsistent behaviour, as already noted.

DataFrame.get_values() is simply a wrapper around DataFrame.values, so everything said above applies.

DataFrame.as_matrix() is deprecated now, do NOT use!

How to match "any character" in regular expression?

Specific Solution to the example problem:-

Try [A-Z]*123$ will match 123, AAA123, ASDFRRF123. In case you need at least a character before 123 use [A-Z]+123$.

General Solution to the question (How to match "any character" in the regular expression):

  1. If you are looking for anything including whitespace you can try [\w|\W]{min_char_to_match,}.
  2. If you are trying to match anything except whitespace you can try [\S]{min_char_to_match,}.

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

In my case, I had two project in a solution, I added a sub-namespace into the referenced project, but when building, I didn't notice that the referenced project build failed and it used the last successfully built version which didn't have this new namespace, so the error was correct, that it cannot be found, because it didn't exist The solution was obviously to fix errors in referenced project.

Google Maps Android API v2 Authorization failure

I had the exact same issue and i just needed to set the SDK for the library project of the MapsApiV2 to Android 2.3.3 (API lvl 10)

Typescript empty object for a typed variable

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

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

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

Convert String to Uri

Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

assertEquals("http://www.google.com/search?q=cat%7Cdog",
    Urls.createURI("http://www.google.com/search?q=cat|dog").toString());

How to Set Variables in a Laravel Blade Template

As for my elegant way is like the following

{{ ''; $old_section = "whatever"; }}

And just echo your $old_section variable.

{{ $old_section }}

How to calculate md5 hash of a file using javascript

The following snippet shows an example, which can archive a throughput of 400 MB/s while reading and hashing the file.

It is using a library called hash-wasm, which is based on WebAssembly and calculates the hash faster than js-only libraries. As of 2020, all modern browsers support WebAssembly.

_x000D_
_x000D_
const chunkSize = 64 * 1024 * 1024;
const fileReader = new FileReader();
let hasher = null;

function hashChunk(chunk) {
  return new Promise((resolve, reject) => {
    fileReader.onload = async(e) => {
      const view = new Uint8Array(e.target.result);
      hasher.update(view);
      resolve();
    };

    fileReader.readAsArrayBuffer(chunk);
  });
}

const readFile = async(file) => {
  if (hasher) {
    hasher.init();
  } else {
    hasher = await hashwasm.createMD5();
  }

  const chunkNumber = Math.floor(file.size / chunkSize);

  for (let i = 0; i <= chunkNumber; i++) {
    const chunk = file.slice(
      chunkSize * i,
      Math.min(chunkSize * (i + 1), file.size)
    );
    await hashChunk(chunk);
  }

  const hash = hasher.digest();
  return Promise.resolve(hash);
};

const fileSelector = document.getElementById("file-input");
const resultElement = document.getElementById("result");

fileSelector.addEventListener("change", async(event) => {
  const file = event.target.files[0];

  resultElement.innerHTML = "Loading...";
  const start = Date.now();
  const hash = await readFile(file);
  const end = Date.now();
  const duration = end - start;
  const fileSizeMB = file.size / 1024 / 1024;
  const throughput = fileSizeMB / (duration / 1000);
  resultElement.innerHTML = `
    Hash: ${hash}<br>
    Duration: ${duration} ms<br>
    Throughput: ${throughput.toFixed(2)} MB/s
  `;
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/hash-wasm"></script>
<!-- defines the global `hashwasm` variable -->

<input type="file" id="file-input">
<div id="result"></div>
_x000D_
_x000D_
_x000D_

What's the name for hyphen-separated case?

Here is a more recent discombobulation. Documentation everywhere in angular JS and Pluralsight courses and books on angular, all refer to kebab-case as snake-case, not differentiating between the two.

Its too bad caterpillar-case did not stick because snake_case and caterpillar-case are easily remembered and actually look like what they represent (if you have a good imagination).

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

SQL Server 2008 Row Insert and Update timestamps

As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERTs that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP which it includes in the final INSERT to the database. You could do the same for the CREATE. You may also be able to set things up so that users cannot execute INSERT and CREATE statements other than via the stored procedures.

I have to admit that I haven't actually done this myself so I'm not at all sure of the details.

HashMap get/put complexity

It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match.

In the worst case, a HashMap has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use.

In JDK 8, HashMap has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course.

And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

How do I use a pipe to redirect the output of one command to the input of another?

Not sure if you are coding these programs, but this is a simple example of how you'd do it.

program1.c

#include <stdio.h>
int main (int argc, char * argv[] ) {
    printf("%s", argv[1]); 
    return 0;
}

rgx.cpp

#include <cstdio>
#include <regex>
#include <iostream>
using namespace std;
int main (int argc, char * argv[] ) {
    char input[200];
    fgets(input,200,stdin);
    string s(input)
    smatch m;
    string reg_exp(argv[1]);
    regex e(reg_exp);
    while (regex_search (s,m,e)) {
      for (auto x:m) cout << x << " ";
      cout << endl;
      s = m.suffix().str();
    }
    return 0;
}

Compile both then run program1.exe "this subject has a submarine as a subsequence" | rgx.exe "\b(sub)([^ ]*)"

The | operator simply redirects the output of program1's printf operation from the stdout stream to the stdin stream whereby it's sitting there waiting for rgx.exe to pick up.

Setting Environment Variables for Node to retrieve

Just provide the env values on command line

USER_ID='abc' USER_KEY='def' node app.js

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

Creating a chart in Excel that ignores #N/A or blank cells

If you have an x and y column that you want to scatterplot, but not all of the cells in one of the columns is populated with meaningful values (i.e. some of them have #DIV/0!), then insert a new column next to the offending column and type =IFERROR(A2, #N/A), where A2 is the value in the offending column.

This will return #N/A if there is a #DIV/0! and will return the good value otherwise. Now make your plot with your new column and Excel ignores #N/A value and will not plot them as zeroes.

Important: do not output "#N/A" in the formula, just output #N/A.

Creating CSS Global Variables : Stylesheet theme management

You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }

Get last 30 day records from today date in SQL Server

you can use this to get the data of the last 30 days based on a column.

WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

change html input type by JS?

Try:

<input id="hybrid" type="text" name="password" />

<script type="text/javascript">
    document.getElementById('hybrid').type = 'password';
</script>

Type of expression is ambiguous without more context Swift

For me the case was Type inference I have changed the function parameters from int To float but did not update the calling code, and the compiler did not warn me on wrong type passed to the function

Before

func myFunc(param:Int, parma2:Int) {}

After

func myFunc(param:Float, parma2:Float) {}

Calling code with error

var param1:Int16 = 1
var param2:Int16 = 2
myFunc(param:param1, parma2:param2)// error here: Type of expression is ambiguous without more context

To fix:

var param1:Float = 1.0f
var param2:Float = 2.0f
myFunc(param:param1, parma2:param2)// ok!

Get IP address of an interface on Linux

Try this:

#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

int
main()
{
 int fd;
 struct ifreq ifr;

 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* I want to get an IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to "eth0" */
 strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 /* display result */
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

The code sample is taken from here.

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

How to Query an NTP Server using C#?

I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.

 /// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
    private readonly TaskCompletionSource<DateTime> _resultCompletionSource;

    /// <summary>
    /// Creates a new instance of <see cref="NtpClient"/> class.
    /// </summary>
    public NtpClient()
    {
        _resultCompletionSource = new TaskCompletionSource<DateTime>();
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync()
    {
        return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeoutMs">Operation timeout in milliseconds.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
    {
        return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeout">Operation timeout.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
    {
        using (var socket = new DatagramSocket())
        using (var ct = new CancellationTokenSource(timeout))
        {
            ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

            socket.MessageReceived += OnSocketMessageReceived;
            //The UDP port number assigned to NTP is 123
            await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
            using (var writer = new DataWriter(socket.OutputStream))
            {
                // NTP message size is 16 bytes of the digest (RFC 2030)
                var ntpBuffer = new byte[48];

                // Setting the Leap Indicator, 
                // Version Number and Mode values
                // LI = 0 (no warning)
                // VN = 3 (IPv4 only)
                // Mode = 3 (Client Mode)
                ntpBuffer[0] = 0x1B;

                writer.WriteBytes(ntpBuffer);
                await writer.StoreAsync();
                var result = await _resultCompletionSource.Task;
                return result;
            }
        }
    }

    private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (var reader = args.GetDataReader())
            {
                byte[] response = new byte[48];
                reader.ReadBytes(response);
                _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
            }
        }
        catch (Exception ex)
        {
            _resultCompletionSource.TrySetException(ex);
        }
    }

    private static DateTime ParseNetworkTime(byte[] rawData)
    {
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    private static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

Usage:

var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));

Representing EOF in C code?

This is system dependent but often -1. See here

How to get a JavaScript object's class?

I find object.constructor.toString() return [object objectClass] in IE ,rather than function objectClass () {} returned in chome. So,I think the code in http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects may not work well in IE.And I fixed the code as follows:

code:

var getObjectClass = function (obj) {
        if (obj && obj.constructor && obj.constructor.toString()) {
            
                /*
                 *  for browsers which have name property in the constructor
                 *  of the object,such as chrome 
                 */
                if(obj.constructor.name) {
                    return obj.constructor.name;
                }
                var str = obj.constructor.toString();
                /*
                 * executed if the return of object.constructor.toString() is 
                 * "[object objectClass]"
                 */
                 
                if(str.charAt(0) == '[')
                {
                        var arr = str.match(/\[\w+\s*(\w+)\]/);
                } else {
                        /*
                         * executed if the return of object.constructor.toString() is 
                         * "function objectClass () {}"
                         * for IE Firefox
                         */
                        var arr = str.match(/function\s*(\w+)/);
                }
                if (arr && arr.length == 2) {
                            return arr[1];
                        }
          }
          return undefined; 
    };
    

How to cast ArrayList<> from List<>

The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>

How to replace a hash key with another key

you can do

hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}

This should work for your case!

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

I have encountered similar problem. The root cause is that (use your scenario for my case), in the #temp table, there is no record for
a. CLASS=RICE and STATE=TX
b. CLASS=VEGIE and (STATE=AZ or STATE=CA)
So, when MSSQL does pivot for no record, MSSQL always shows NULL for MAX, SUM, ... (aggregate functions)

None of above solutions (IsNull([AZ], 0)) works for me. But I do get ideas from these solutions. Thanks.

Sorry, it really depends on the #TEMP table. I can only provide some suggestions.
1. Make sure #TEMP table have records for below condition, even Data is null.
a. CLASS=RICE and STATE=TX
b. CLASS=VEGIE and (STATE=AZ or STATE=CA) You may need to use cartesian product: select A.*, B.* from A, B 2. In the select query for #temp, if you need to join any table with WHERE, then would better put where inside another sub select query. (Goal is 1.)
3. Use isnull(DATA, 0) in #TEMP table.
4. Before pivot, make sure you have achieved Goal 1.

I can't give an answer to the orginal question, since there is no enough info for #temp table. I have pasted my code as example here, hope this will help others.

_x000D_
_x000D_
SELECT * FROM (_x000D_
   SELECT eeee.id as enterprise_id_x000D_
   , eeee.name AS enterprise_name_x000D_
   , eeee.indicator_name_x000D_
   , CONVERT(varchar(12) , isnull(eid.[date],'2019-12-01') , 23) AS data_date_x000D_
   , isnull(eid.value,0) AS indicator_value_x000D_
   FROM (select ei.id as indicator_id, ei.name as indicator_name, e.* FROM tbl_enterprise_indicator ei, tbl_enterprise e) eeee            _x000D_
   LEFT JOIN  (select * from tbl_enterprise_indicator_data WHERE [date]='2020-01-01') eid_x000D_
     ON  eeee.id = eid.enterprise_id and eeee.indicator_id = enterprise_indicator_id_x000D_
  ) AS P _x000D_
  PIVOT _x000D_
  (_x000D_
   SUM(P.indicator_value) FOR P.indicator_name IN(TX,CA)_x000D_
  ) AS T 
_x000D_
_x000D_
_x000D_

How do you extract IP addresses from files using a regex in a linux shell?

You can use some shell helper I made: https://github.com/philpraxis/ipextract

included them here for convenience:

#!/bin/sh
ipextract () 
{ 
egrep --only-matching -E  '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' 
}

ipextractnet ()
{ 
egrep --only-matching -E  '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/[[:digit:]]+' 
}

ipextracttcp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/tcp' 
}

ipextractudp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/udp' 
}

ipextractsctp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/sctp' 
}

ipextractfqdn ()
{ 
egrep --only-matching -E  '[a-zA-Z0-9]+[a-zA-Z0-9\-\.]*\.[a-zA-Z]{2,}' 
}

Load it / source it (when stored in ipextract file) from shell:

$ . ipextract

Use them:

$ ipextract < /etc/hosts
127.0.0.1
255.255.255.255
$

For some example of real use:

ipextractfqdn < /var/log/snort/alert | sort -u
dmesg | ipextractudp

To switch from vertical split to horizontal split fast in Vim

When you have two or more windows open horizontally or vertically and want to switch them all to the other orientation, you can use the following:

(switch to horizontal)

:windo wincmd K

(switch to vertical)

:windo wincmd H

It's effectively going to each window individually and using ^WK or ^WH.

How to resize array in C++?

You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.

#include<algorithm> // for copy

void resize(int*& a, size_t& n)
{
   size_t new_n = 2 * n;
   int* new_a = new int[new_n];
   copy(a, a + n, new_a);
   delete[] a;
   a = new_a;
   n = new_n;
}

For 2D arrays:

#include<algorithm> // for copy

void resize(int**& a, size_t& n)
{
   size_t new_n = 2 * n, i = 0;
   int** new_a = new int* [new_n];
   for (i = 0; i != new_n; ++i)
       new_a[i] = new int[100];
   for (i = 0; i != n; ++i)
   {
       copy(a[i], a[i] + 100, new_a[i]);
       delete[] a[i];
   }
   delete[] a;
   a = new_a;
   n = new_n;
}

Invoking of 1D array:

void myfn(int*& a, size_t& n)
{
   // do smth
   resize(a, n);
}

Invoking of 2D array:

void myfn(int**& a, size_t& n)
{
   // do smth
   resize(a, n);
}
  


   

I want to get the type of a variable at runtime

If by the type of a variable you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.

val name = "sam";
name: java.lang.String = sam
name.getClass
res0: java.lang.Class[_] = class java.lang.String

If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say

val name: Object = "sam"

then you will still get a String back from the above code.

Why is 2 * (i * i) faster than 2 * i * i in Java?

I got similar results:

2 * (i * i): 0.458765943 s, n=119860736
2 * i * i: 0.580255126 s, n=119860736

I got the SAME results if both loops were in the same program, or each was in a separate .java file/.class, executed on a separate run.

Finally, here is a javap -c -v <.java> decompile of each:

     3: ldc           #3                  // String 2 * (i * i):
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: iload         4
    30: imul
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

vs.

     3: ldc           #3                  // String 2 * i * i:
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: imul
    29: iload         4
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

FYI -

java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Converting unix time into date-time via excel

If you have ########, it can help you:

=((A1/1000+1*3600)/86400+25569)

+1*3600 is GTM+1

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:

$("#elementID").show();

Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:

$("#elem").show();

The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

It seems your MYSQL is stopped. use below command to start MySQL again

sudo service mysql start

'negative' pattern matching in python

You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group.

Let's write python code:

string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.
"""

search_result = re.search(r"^OK.*\n((.|\s)*).", string)

if search_result:
    print(search_result.group(1))

Output is:

1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt

^OK.*\n will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*), so put it inside parentheses. And in the end of regexp we look for a dot ., but we also don't want to capture it.

P.S: I find this answer is super helpful to understand power of groups. https://stackoverflow.com/a/3513858/4333811

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

How do I vertically align text in a paragraph?

If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.

_x000D_
_x000D_
.parent-div{_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.text-div{_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}_x000D_
_x000D_
p.event_desc{_x000D_
  font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="parent-div">_x000D_
  <div class="text-div">_x000D_
   <p class="event_desc">_x000D_
    MY TEXT_x000D_
   </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

select right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ + right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ + right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string:

TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.

Long term, I'd recommend leveraging Let's Encrypt to get a CA signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".

SQL Server: Difference between PARTITION BY and GROUP BY

-- BELOW IS A SAMPLE WHICH OUTLINES THE SIMPLE DIFFERENCES
-- READ IT AND THEN EXECUTE IT
-- THERE ARE THREE ROWS OF EACH COLOR INSERTED INTO THE TABLE
-- CREATE A database called testDB


-- use testDB
USE [TestDB]
GO


-- create Paints table
CREATE TABLE [dbo].[Paints](
    [Color] [varchar](50) NULL,
    [glossLevel] [varchar](50) NULL
) ON [PRIMARY]

GO


-- Populate Table
insert into paints (color, glossLevel)
select 'red', 'eggshell'
union
select 'red', 'glossy'
union
select 'red', 'flat'
union
select 'blue', 'eggshell'
union
select 'blue', 'glossy'
union
select 'blue', 'flat'
union
select 'orange', 'glossy'
union
select 'orange', 'flat'
union
select 'orange', 'eggshell'
union
select 'green', 'eggshell'
union
select 'green', 'glossy'
union
select 'green', 'flat'
union
select 'black', 'eggshell'
union
select 'black', 'glossy'
union
select 'black', 'flat'
union
select 'purple', 'eggshell'
union
select 'purple', 'glossy'
union
select 'purple', 'flat'
union
select 'salmon', 'eggshell'
union
select 'salmon', 'glossy'
union
select 'salmon', 'flat'


/*   COMPARE 'GROUP BY' color to 'OVER (PARTITION BY Color)'  */

-- GROUP BY Color 
-- row quantity defined by group by
-- aggregate (count(*)) defined by group by
select count(*) from paints
group by color

-- OVER (PARTITION BY... Color 
-- row quantity defined by main query
-- aggregate defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color)
from paints

/* COMPARE 'GROUP BY' color, glossLevel to 'OVER (PARTITION BY Color, GlossLevel)'  */

-- GROUP BY Color, GlossLevel
-- row quantity defined by GROUP BY
-- aggregate (count(*)) defined by GROUP BY
select count(*) from paints
group by color, glossLevel



-- Partition by Color, GlossLevel
-- row quantity defined by main query
-- aggregate (count(*)) defined by OVER-PARTITION BY
select color
, glossLevel
, count(*) OVER (Partition by color, glossLevel)
from paints

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

OpenCV & Python - Image too big to display

The other answers perform a fixed (width, height) resize. If you wanted to resize to a specific size while maintaining aspect ratio, use this

def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

Example

image = cv2.imread('img.png')
resize = ResizeWithAspectRatio(image, width=1280) # Resize by width OR
# resize = ResizeWithAspectRatio(image, height=1280) # Resize by height 

cv2.imshow('resize', resize)
cv2.waitKey()

How can I delete using INNER JOIN with SQL Server?

Try this query:

DELETE WorkRecord2, Employee 
FROM WorkRecord2 
INNER JOIN Employee ON (tbl_name.EmployeeRun=tbl_name.EmployeeNo)
WHERE tbl_name.Company = '1' 
AND tbl_name.Date = '2013-05-06';

Java: How can I compile an entire directory structure of code ?

There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:

find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +

Though if you are in Bash and/or don't mind using a pipe, then you can do:

find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

How to delete empty folders using windows command prompt?

You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.

ROBOCOPY folder1 folder1 /S /MOVE

Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.

Vertically aligning CSS :before and :after content

This is what worked for me:

.pdf::before {
    content: url('path/to/image.png');
    display: flex;
    align-items: center;
    justify-content: center;
    height: inherit;
}

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

work fine for me ,change ids according to you requirement.

$("#FormId select#status_id_new").val('');
 $("#FormId select#status_id_new").multiselect("refresh");

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

How to get bitmap from a url in android?

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

"X does not name a type" error in C++

On a related note, if you had:

    class User; // let the compiler know such a class will be defined

    class MyMessageBox
    {
    public:
        User* myUser;
    };

    class User
    {
    public:
        // also ok, since it's now defined
        MyMessageBox dataMsgBox;
    };

Then that would also work, because the User is defined in MyMessageBox as a pointer

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I had a great deal of trouble linking to MySQL from a 64 bit laptop, running Windows 7, using MS Access 2010. I found the previous article very helpful, but still could not connect using odbc 3.5.1. As I had previously linked a 32 bit machine using Connector/ODBC 5.1.13, I downloaded that version and set it up using the instructions above. Success. The answer seems to be to try different versions of Connector.odbc.

Find object by id in an array of JavaScript objects

Shortest,

var theAnswerObj = _.findWhere(array, {id : 42});

How to concat two ArrayLists?

ArrayList<String> resultList = new ArrayList<String>();
resultList.addAll(arrayList1);
resultList.addAll(arrayList2);

What is the purpose of a question mark after a type (for example: int? myVariable)?

To add on to the answers above, here is a code sample

struct Test
{
    int something;
}
struct NullableTest
{
    int something;
}
class Example
{
    public void Demo()
    {
        Test t = new Test();
        t = null;

        NullableTest? t2 = new NullableTest();
        t2 = null;
    }
}

This would give a compilation error:

Error 12 Cannot convert null to 'Test' because it is a non-nullable value type

Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)

git - Server host key not cached

Just ssh'ing to the host is not enough, on Windows at least. That adds the host key to ssh/known_hosts but the error still persists.

You need to close the git bash window and open a new one. Then the registry cache is cleared and the push/pull then works.

DLL load failed error when importing cv2

I took a lot of time to solve this error! Run command

pip install opencv-contrib-python

How to adjust text font size to fit textview

I've written a class that extends TextView and does this. It just uses measureText as you suggest. Basically it has a maximum text size and minimum text size (which can be changed) and it just runs through the sizes between them in decrements of 1 until it finds the biggest one that will fit. Not particularly elegant, but I don't know of any other way.

Here is the code:

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialise();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        testPaint = new Paint();
        testPaint.set(this.getPaint());
        //max size defaults to the intially specified text size unless it is too small
        maxTextSize = this.getTextSize();
        if (maxTextSize < 11) {
            maxTextSize = 20;
        }
        minTextSize = 10;
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth) { 
        if (textWidth > 0) {
            int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
            float trySize = maxTextSize;

            testPaint.setTextSize(trySize);
            while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) {
                trySize -= 1;
                if (trySize <= minTextSize) {
                    trySize = minTextSize;
                    break;
                }
                testPaint.setTextSize(trySize);
            }

            this.setTextSize(trySize);
        }
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
        }
    }

    //Getters and Setters
    public float getMinTextSize() {
        return minTextSize;
    }

    public void setMinTextSize(int minTextSize) {
        this.minTextSize = minTextSize;
    }

    public float getMaxTextSize() {
        return maxTextSize;
    }

    public void setMaxTextSize(int minTextSize) {
        this.maxTextSize = minTextSize;
    }

    //Attributes
    private Paint testPaint;
    private float minTextSize;
    private float maxTextSize;

}

gradle build fails on lint task

You can select proper options from here

android {
    lintOptions {
        // set to true to turn off analysis progress reporting by lint
        quiet true
        // if true, stop the gradle build if errors are found
        abortOnError false
        // if true, only report errors
        ignoreWarnings true
        // if true, emit full/absolute paths to files with errors (true by default)
        //absolutePaths true
        // if true, check all issues, including those that are off by default
        checkAllWarnings true
        // if true, treat all warnings as errors
        warningsAsErrors true
        // turn off checking the given issue id's
        disable 'TypographyFractions','TypographyQuotes'
        // turn on the given issue id's
        enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
        // check *only* the given issue id's
        check 'NewApi', 'InlinedApi'
        // if true, don't include source code lines in the error output
        noLines true
        // if true, show all locations for an error, do not truncate lists, etc.
        showAll true
        // Fallback lint configuration (default severities, etc.)
        lintConfig file("default-lint.xml")
        // if true, generate a text report of issues (false by default)
        textReport true
        // location to write the output; can be a file or 'stdout'
        textOutput 'stdout'
        // if true, generate an XML report for use by for example Jenkins
        xmlReport false
        // file to write report to (if not specified, defaults to lint-results.xml)
        xmlOutput file("lint-report.xml")
        // if true, generate an HTML report (with issue explanations, sourcecode, etc)
        htmlReport true
        // optional path to report (default will be lint-results.html in the builddir)
        htmlOutput file("lint-report.html")

        // set to true to have all release builds run lint on issues with severity=fatal
        // and abort the build (controlled by abortOnError above) if fatal issues are found
        checkReleaseBuilds true
        // Set the severity of the given issues to fatal (which means they will be
        // checked during release builds (even if the lint target is not included)
        fatal 'NewApi', 'InlineApi'
        // Set the severity of the given issues to error
        error 'Wakelock', 'TextViewEdits'
        // Set the severity of the given issues to warning
        warning 'ResourceAsColor'
        // Set the severity of the given issues to ignore (same as disabling the check)
        ignore 'TypographyQuotes'
    }
}

How do I get the Git commit count?

If you're just using one branch, such as master, I think this would work great:

git rev-list --full-history --all | wc -l

This will only output a number. You can alias it to something like

git revno

to make things really convenient. To do so, edit your .git/config file and add this in:

[alias]
    revno = "!git rev-list --full-history --all | wc -l"

This will not work on Windows. I do not know the equivalent of "wc" for that OS, but writing a Python script to do the counting for you would be a multi-platform solution.

EDIT: Get count between two commits:


I was looking for an answer that would show how to get the number of commits between two arbitrary revisions and didn't see any.

git rev-list --count [older-commit]..[newer-commit]

Using String Format to show decimal up to 2 places or simple integer

I am afraid there is no built-in format that will do this. You will have to use a different format depending on whether the value is a whole number or not. Or always format to 2 decimal places, and manipulate the string afterwards to remove any trailing ".00".

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I think it is better to update your "mysql-connector" lib package, so database can be still more safe.

I am using mysql of version 8.0.12. When I updated the mysql-connector-java to version 8.0.11, the problem was gone.

Bi-directional Map in Java?

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

jQuery document.createElement equivalent?

Simply supplying the HTML of elements you want to add to a jQuery constructor $() will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append() method.

For example:

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

You could then populate this table programmatically, if you wished.

This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement and then setting attributes like cellSpacing and className via JS.

How to hide reference counts in VS2013?

The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.

However, if the only way to disable Show References is to disable CodeLens altogether.

Then, I guess I could do just that.

Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'

If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.

In short, uncheck Codelens...

Determine distance from the top of a div to top of window with javascript

You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

The distance variable now holds the distance from the top of the #my-element element and the top-fold.

Here is a demo: http://jsfiddle.net/Rxs2m/

Note that negative values mean that the element is above the top-fold.

How to change the background-color of jumbrotron?

You can use the following to change the background-color of a Jumbotron:

<div class="container">
    <div class="jumbotron text-white" style="background-color: #8c6278;">
        <h1>Coffee lover project !</h1>
    </div>
</div>

How do I convert a C# List<string[]> to a Javascript array?

For those trying to do it without using JSON, the following is how I did it:

<script>
    var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

Java Loop every minute

If you are using a SpringBoot application it's as simple as

ScheduledProcess

@Log
@Component
public class ScheduledProcess {

    @Scheduled(fixedRate = 5000)
    public void run() {
        log.info("this runs every 5 seconds..");
    }

}

Application.class

@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

Is Visual Studio Community a 30 day trial?

Remember, if you are inside of private red with some proxy, you must be logout and relogin with an external WIFI for example.

Java Round up Any Number

Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));

Outputs:

1
1.0
1.42
2.0
2

See http://ideone.com/yhT0l

how to get yesterday's date in C#

You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that

 string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");

OR

 string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

TSQL - Cast string to integer or return default value

If you are on SQL Server 2012 (or newer):

Use the TRY_CONVERT function.

If you are on SQL Server 2005, 2008, or 2008 R2:

Create a user defined function. This will avoid the issues that Fedor Hajdu mentioned with regards to currency, fractional numbers, etc:

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS int
AS
BEGIN
    SET @Value = REPLACE(@Value, ',', '')
    IF ISNUMERIC(@Value + 'e0') = 0 RETURN NULL
    IF ( CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0 ) RETURN NULL
    DECLARE @I bigint =
        CASE
        WHEN CHARINDEX('.', @Value) > 0 THEN CONVERT(bigint, PARSENAME(@Value, 2))
        ELSE CONVERT(bigint, @Value)
        END
    IF ABS(@I) > 2147483647 RETURN NULL
    RETURN @I
END
GO

-- Testing
DECLARE @Test TABLE(Value nvarchar(50))    -- Result
INSERT INTO @Test SELECT '1234'            -- 1234
INSERT INTO @Test SELECT '1,234'           -- 1234
INSERT INTO @Test SELECT '1234.0'          -- 1234
INSERT INTO @Test SELECT '-1234'           -- -1234
INSERT INTO @Test SELECT '$1234'           -- NULL
INSERT INTO @Test SELECT '1234e10'         -- NULL
INSERT INTO @Test SELECT '1234 5678'       -- NULL
INSERT INTO @Test SELECT '123-456'         -- NULL
INSERT INTO @Test SELECT '1234.5'          -- NULL
INSERT INTO @Test SELECT '123456789000000' -- NULL
INSERT INTO @Test SELECT 'N/A'             -- NULL
SELECT Value, dbo.TryConvertInt(Value) FROM @Test

Reference: I used this page extensively when creating my solution.

jQuery location href

You can use just JavaScript:

window.location = 'http://address.com';

C# Lambda expressions: Why should I use them?

Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.

Consider this example:

 List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
 string person = people.Find(person => person.Contains("Joe"));

versus

 public string FindPerson(string nameContains, List<string> persons)
 {
     foreach (string person in persons)
         if (person.Contains(nameContains))
             return person;
     return null;
 }

These are functionally equivalent.

Custom exception type

//create error object
var error = new Object();
error.reason="some reason!";

//business function
function exception(){
    try{
        throw error;
    }catch(err){
        err.reason;
    }
}

Now we set add the reason or whatever properties we want to the error object and retrieve it. By making the error more reasonable.