Programs & Examples On #Hmvc

The HMVC (Hierarchical-Model-View-Controller) pattern decomposes the client tier into a hierarchy of parent-child MVC (Model-View-Controller) layers.

How to load a controller from another controller in codeigniter?

I had a similar problem. I wanted to have two controllers:

homepage.php - public facing homepage

home.php - home screen once a user was logged in

and I wanted them both to read from 'mydomain.com'

I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php

function _remap()
{
  if(user_is_logged_in())
  {
    require_once(APPPATH.'controllers/home.php'); 
    $oHome =  new Home();
    $oHome->index();
  }
  else
  {
    $this->index();
  }
}

Detect and exclude outliers in Pandas data frame

Use boolean indexing as you would do in numpy.array

df = pd.DataFrame({'Data':np.random.normal(size=200)})
# example dataset of normally distributed data. 

df[np.abs(df.Data-df.Data.mean()) <= (3*df.Data.std())]
# keep only the ones that are within +3 to -3 standard deviations in the column 'Data'.

df[~(np.abs(df.Data-df.Data.mean()) > (3*df.Data.std()))]
# or if you prefer the other way around

For a series it is similar:

S = pd.Series(np.random.normal(size=200))
S[~((S-S.mean()).abs() > 3*S.std())]

How to open Android Device Monitor in latest Android Studio 3.1

If you want to push or pull your files from devices monitor now android studio offers something better then android monitor. Just take a look at right side of your studio there is an option device file explorer. Open it and you are good to go. Select your device from top dropdown and rest of everything is pretty much the same as it was in android monitor. Below is the screen Shot attached to give you the exact location and idea.

enter image description here

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

Difference between 'cls' and 'self' in Python classes?

The distinction between "self" and "cls" is defined in PEP 8 . As Adrien said, this is not a mandatory. It's a coding style. PEP 8 says:

Function and method arguments:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Ignore parent padding

The problem could come down to which box model you're using. Are you using IE?

When IE is in quirks mode, width is the outer width of your box, which means the padding will be inside. So the total area left inside the box is 100px - 2 * 10px = 80px in which case your 100px wide <hr> will not look right.

If you're in standards mode, width is the inner width of your box, and padding is added outside. So the total width of the box is 100px + 2 * 10px = 120px leaving exactly 100px inside the box for your <hr>.

To solve it, either adjust your CSS values for IE. (Check in Firefox to see if it looks okay there). Or even better, set a document type to kick the browser into strict mode - where also IE follows the standard box model.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
 ...

http://www.quirksmode.org/css/quirksmode.html

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I was seeing this error reported once in a while from some of my apps, and here's what solved it for me:

if(!((Activity) context).isFinishing())
{
    //show dialog
}

All the other answers out there seem to be doing weird things like iterating through the list of running activities, but this is much simpler and seems to do the trick.

How to make a drop down list in yii2?

There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).

@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.

I went with:

<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?=
$form->field($model, 'parent_id')
     ->dropDownList(
            ArrayHelper::map(Product::find()->asArray()->all(), 'parent_id', 'name')
            )
?>

Again, full credit to: @Sarvar Nishonboyev's and @ippi

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

This is the solution i found.

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

Configure DBContext via AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

Redirect in Spring MVC

i know this is late , but you should try redirecting to a path and not to a file ha ha

How do I POST urlencoded form data with $http without jQuery?

URL-encoding variables using only AngularJS services

With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

  1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)

  2. $httpParamSerializer - a serializer used by Angular itself for GET requests

Example usage

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

See a more verbose Plunker demo


How are $httpParamSerializerJQLike and $httpParamSerializer different

In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.

For example (ignoring percent encoding of brackets):

Encoding an array

{sites:['google', 'Facebook']} // Object with array property

sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike

sites=google&sites=facebook // Result with $httpParamSerializer

Encoding an object

{address: {city: 'LA', country: 'USA'}} // Object with object property

address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike

address={"city": "LA", country: "USA"} // Result with $httpParamSerializer

Nexus 5 USB driver

Is it your first android connected to your computer? Sometimes windows drivers need to be erased. Refer http://forum.xda-developers.com/showthread.php?t=2512549

Facebook user url by id

I've collected info together:

And finaly: it doen't work without additional Facebook permission check:(

Difference between DOM parentNode and parentElement

Use .parentElement and you can't go wrong as long as you aren't using document fragments.

If you use document fragments, then you need .parentNode:

let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment

Also:

_x000D_
_x000D_
let div = document.getElementById('t').content.firstChild_x000D_
div.parentElement // null_x000D_
div.parentNode // document fragment
_x000D_
<template id="t"><div></div></template>
_x000D_
_x000D_
_x000D_


Apparently the <html>'s .parentNode links to the Document. This should be considered a decision phail as documents aren't nodes since nodes are defined to be containable by documents and documents can't be contained by documents.

jQuery get content between <div> tags

Use the below where x is the variable which holds the markup in question.

$(x).find("div").html();

What is the best way to remove a table row with jQuery?

id is not a good selector now. You can define some properties on the rows. And you can use them as selector.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

and you can use a func to select the row like this (ES6):

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.


¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

Join vs. sub-query

I just thinking about the same problem, but I am using subquery in the FROM part. I need connect and query from large tables, the "slave" table have 28 million record but the result is only 128 so small result big data! I am using MAX() function on it.

First I am using LEFT JOIN because I think that is the correct way, the mysql can optimalize etc. Second time just for testing, I rewrite to sub-select against the JOIN.

LEFT JOIN runtime: 1.12s SUB-SELECT runtime: 0.06s

18 times faster the subselect than the join! Just in the chokito adv. The subselect looks terrible but the result ...

String to list in Python

Maybe like this:

list('abcdefgh') # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Nested classes' scope?

class Outer(object):
    outer_var = 1

    class Inner(object):
        @property
        def inner_var(self):
            return Outer.outer_var

This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)

If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:

class Outer(object):
    def __init__(self):
        self.outer_var = 1

    def get_inner(self):
        return self.Inner(self)
        # "self.Inner" is because Inner is a class attribute of this class
        # "Outer.Inner" would also work, or move Inner to global scope
        # and then just use "Inner"

    class Inner(object):
        def __init__(self, outer):
            self.outer = outer

        @property
        def inner_var(self):
            return self.outer.outer_var

Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)

How can I pass some data from one controller to another peer controller

You need to use

 $rootScope.$broadcast()

in the controller that must send datas. And in the one that receive those datas, you use

 $scope.$on

Here is a fiddle that i forked a few time ago (I don't know who did it first anymore

http://jsfiddle.net/patxy/RAVFM/

Angular and debounce

HTML file:

<input [ngModel]="filterValue"
       (ngModelChange)="filterValue = $event ; search($event)"
        placeholder="Search..."/>

TS file:

timer = null;
time = 250;
  search(searchStr : string) : void {
    clearTimeout(this.timer);
    this.timer = setTimeout(()=>{
      console.log(searchStr);
    }, time)
  }

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

Replace all whitespace characters

I've used the "slugify" method from underscore.string and it worked like a charm:

https://github.com/epeli/underscore.string#slugifystring--string

The cool thing is that you can really just import this method, don't need to import the entire library.

Multiple Buttons' OnClickListener() android

You Just Simply have to Follow these steps for making it easy...

You don't have to write new onClickListener for Every Button... Just Implement View.OnClickLister to your Activity/Fragment.. it will implement new Method called onClick() for handling onClick Events for Button,TextView` etc.

  1. Implement OnClickListener() in your Activity/Fragment
public class MainActivity extends Activity implements View.OnClickListener {

}
  1. Implement onClick() method in your Activity/Fragment
public class MainActivity extends Activity implements View.OnClickListener {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public void onClick(View v) {
      // default method for handling onClick Events..
    }
}
  1. Implement OnClickListener() For Buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.your_layout);
    
    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(this); // calling onClick() method
    Button two = (Button) findViewById(R.id.twoButton);
    two.setOnClickListener(this);
    Button three = (Button) findViewById(R.id.threeButton);
    three.setOnClickListener(this);
}
  1. Find Buttons By Id and Implement Your Code..
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.oneButton:
            // do your code
            break;
        case R.id.twoButton:
            // do your code
            break;
        case R.id.threeButton:
            // do your code
            break;
        default:
            break;
    }
}

Please refer to this link for more information :

https://androidacademic.blogspot.com/2016/12/multiple-buttons-onclicklistener-android.html (updated)

This will make easier to handle many buttons click events and makes it looks simple to manage it...

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

ASP.NET Web API session or something?

You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.

Request and response HTTP headers can also be used to pass information between service calls.

How to run a PowerShell script

Pretty easy. Right click the .ps1 file in Windows and in the shell menu click on Run with PowerShell.

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

Java random number with given length

try this:

public int getRandomNumber(int min, int max) {
    return (int) Math.floor(Math.random() * (max - min + 1)) + min;
}

how to insert datetime into the SQL Database table?

You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

INSERT INTO MyTable (MyDate) Values (GetDate())

If it is not today's date then you should be able to use a string and specify the date format:

INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

You do not always need to convert the string either, often you can just do something like:

INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

When is a timestamp (auto) updated?

Add a trigger in database:

DELIMITER //
CREATE TRIGGER update_user_password 
  BEFORE UPDATE ON users
  FOR EACH ROW
    BEGIN
      IF OLD.password <> NEW.password THEN
        SET NEW.password_changed_on = NOW();
      END IF;
    END //
DELIMITER ;

The password changed time will update only when password column is changed.

Force uninstall of Visual Studio

So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).

I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.

To do this

  1. Uninstall any Windows 10 SDKs that me on the system (the naming schem for them looks like Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE) -> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!
  2. All that's left is to download the SDKs you want by Checking out the SDK Archive for all available SDKs and you should be good to go in developing for the UWP!

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

Labels for radio buttons in rails form

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|
  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email

In this case you'd need to specify the value manually to preserve any submissions.

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

How to get the previous URL in JavaScript?

If you want to go to the previous page without knowing the url, you could use the new History api.

history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.

But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API

For more information see the doc

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I see that you've tagged this question with the google-spreadsheet-api tag. So by "drop-down" do you mean Google App Script's ListBox? If so, you may toggle a user's ability to select multiple items from the ListBox with a simple true/false value.
Here's an example:

`var lb = app.createListBox(true).setId('myId').setName('myLbName');` 

Notice that multiselect is enabled because of the word true.

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Swift - Split string over multiple lines

Another way if you want to use a string variable with some predefined text,

var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0

insert data into database with codeigniter

It will be better for you to write your code like this.

In your Controller Write this code.

    function new_blank_order_summary() {
     $query = $this->sales_model->order_summary_insert();
     if($query) {
        $this->load->view('sales/new_blank_order_summary'); 
    } else {
        $this->load->view('sales/data_insertion_failed');
    }
  }

and in your Model

function order_summary_insert() {
    $orderLines = trim(xss_clean($this->input->post('orderlines')));
    $customerName = trim(xss_clean($this->input->post('customer')));
    $data = array(
        'OrderLines'=>$orderLines,
        'CustomerName'=>$customerName
    );

    $this->db->insert('Customer_Orders',$data);
    return ($this->db->affected_rows() != 1) ? false : true;
}

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

Heap vs Binary Search Tree (BST)

Insert all n elements from an array to BST takes O(n logn). n elemnts in an array can be inserted to a heap in O(n) time. Which gives heap a definite advantage

How to change the DataTable Column Name?

Try this:

dataTable.Columns["Marks"].ColumnName = "SubjectMarks";

Generate MD5 hash string with T-SQL

Use HashBytes

SELECT HashBytes('MD5', '[email protected]')

That will give you 0xF53BD08920E5D25809DF2563EF9C52B6

-

SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)

That will give you F53BD08920E5D25809DF2563EF9C52B6

Looping through the content of a file in Bash

@Peter: This could work out for you-

echo "Start!";for p in $(cat ./pep); do
echo $p
done

This would return the output-

Start!
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL

How to add form validation pattern in Angular 2?

My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:

    <form #paymentCardForm="ngForm">         
...
        <md-input-container align="start">
            <input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
            <md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
                <span [hidden]="!cvc2.errors.required && cvc2.dirty">
                    CVC is required.
                </span>
                <span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
                    CVC must be 3 numbers.
                </span>
            </md-hint>
        </md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>

How do I monitor all incoming http requests?

Guys found the perfect way to monitor ALL traffic that is flowing locally between requests from my machine to my machine:

  1. Install Wireshark

  2. When you need to capture traffic that is flowing from a localhost to a localhost then you will struggle to use wireshark as this only monitors incoming traffic on the network card. The way to do this is to add a route to windows that will force all traffic through a gateway and this be captured on the network interface.

    To do this, add a route with <ip address> <gateway>:

     cmd> route add 192.168.20.30 192.168.20.1
    
  3. Then run a capture on wireshark (make sure you select the interface that has bytes flowing through it) Then filter.

The newly added routes will come up in black. (as they are local addresses)

How to resolve symbolic links in a shell script

function realpath {
    local r=$1; local t=$(readlink $r)
    while [ $t ]; do
        r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)
        t=$(readlink $r)
    done
    echo $r
}

#example usage
SCRIPT_PARENT_DIR=$(dirname $(realpath "$0"))/..

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Is it possible to change the package name of an Android app on Google Play?

From Dianne Hackborn:

Things That Cannot Change:

The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.

More on things you cannot change here

Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.

How do I loop through children objects in javascript?

The trick is that the DOM Element.children attribute is not an array but an array-like collection which has length and can be indexed like an array, but it is not an array:

var children = tableFields.children;
for (var i = 0; i < children.length; i++) {
  var tableChild = children[i];
  // Do stuff
}

Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

pgadmin4 : postgresql application server could not be contacted.

I Fixed it in windows 10 just running pgAdmin 4 as Run as Administrator .

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

XAMPP - MySQL shutdown unexpectedly

if you are using MariaDB you can try this:

  1. Go to mysql/data/
  2. Rename aria_log_control to aria_log_control_old
  3. Restart "Mysql"

How do you count the lines of code in a Visual Studio solution?

Visual Studio 2010 Ultimate has this built-in:

Analyze ? Calculate Code Metrics

How to check if string input is a number?

The method isnumeric() will do the job (Documentation for python3.x):

>>>a = '123'
>>>a.isnumeric()
True

But remember:

>>>a = '-1'
>>>a.isnumeric()
False

isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.

So negative numbers are not accepted.

What is the string length of a GUID?

22 bytes, if you do it like this:

System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');

How to fix a header on scroll

Coops answer is a good, simple solution, however, once you apply the fixed class the page becomes that much shorter and content will "jump" up, and if page is of a length where the scroll distance is less than the height of the header element, it will appear to jump and not let you see the bottom of the page.

The answer I found was to add a spacer div above the element that will become fixed (nav element in my case), and set it to the same height as the nav element, and set it to display none.

When adding the .fixed class to the nav, show the .nav-spacer div, and when removing it, hide it. Since the height of the page changes instantly I have set the duration to 0.

HTML

<header>the element above the element that will become fixed</header>
<div class="nav-spacer"></div>
<nav></nav>

CSS

nav {
    position: relative;    
    height: 100px;
}
.nav-spacer{
    position: relative;
    height: 100px;
    display: none;
}
.fixed {
    position: fixed;
    top:0;
    left:0;
    width: 100%;
    /* I like to add a shadow on to the fixed element */
    -webkit-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
    -moz-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
    box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
}

JavaScript

var stickyOffset = $('nav').offset().top;

$(window).scroll(function(){
    if ($(window).scrollTop() >= stickyOffset){
        $('nav').addClass('fixed');
        //this makes the page length equal to what it was before fixing nav
        $('.nav-spacer').show(0); 
    }
    else {
        $('nav').removeClass('fixed');
        $('.nav-spacer').hide(0);
    }
});

Turn on torch/flash on iPhone

This work's very well.. hope it help's someone !

-(IBAction)flashlight:(id)sender {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device hasTorch] && [device hasFlash]){

        if (device.torchMode == AVCaptureTorchModeOff) {

            [sender setTitle:@"Torch Off" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

            AVCaptureSession *cam = [[AVCaptureSession alloc] init];

            [cam beginConfiguration];
            [device lockForConfiguration:nil];

            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];

            [cam addInput:flashInput];
            [cam addOutput:output];

            [device unlockForConfiguration];

            [cam commitConfiguration];
            [cam startRunning];

            [self setTorchSession:cam];
        }
        else {
            [sender setTitle:@"Torch On" forState:UIControlStateNormal];
            [_torchSession stopRunning];
        }
    }
}

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

C++ delete vector, objects, free memory

if I use the clear() member function. Can I be sure that the memory was released?

No, the clear() member function destroys every object contained in the vector, but it leaves the capacity of the vector unchanged. It affects the vector's size, but not the capacity.

If you want to change the capacity of a vector, you can use the clear-and-minimize idiom, i.e., create a (temporary) empty vector and then swap both vectors.


You can easily see how each approach affects capacity. Consider the following function template that calls the clear() member function on the passed vector:

template<typename T>
auto clear(std::vector<T>& vec) {
   vec.clear();
   return vec.capacity();
}

Now, consider the function template empty_swap() that swaps the passed vector with an empty one:

template<typename T>
auto empty_swap(std::vector<T>& vec) {
   std::vector<T>().swap(vec);
   return vec.capacity();
}

Both function templates return the capacity of the vector at the moment of returning, then:

std::vector<double> v(1000), u(1000);
std::cout << clear(v) << '\n';
std::cout << empty_swap(u) << '\n';

outputs:

1000
0

How to annotate MYSQL autoincrement field with JPA annotations

same as pascal answered, just if you need to use .AUTO for some reason you just need to add in your application properties:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto = update

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

How to declare strings in C

This link should satisfy your curiosity.

Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

What is a callback URL in relation to an API?

A callback URL will be invoked by the API method you're calling after it's done. So if you call

POST /api.example.com/foo?callbackURL=http://my.server.com/bar

Then when /foo is finished, it sends a request to http://my.server.com/bar. The contents and method of that request are going to vary - check the documentation for the API you're accessing.

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Joining three tables using MySQL

SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

How do I format a date as ISO 8601 in moment.js?

Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

Passing array in GET for a REST call

As @Ravi_MCA mentioned, /users?ids[]=id1&ids[]=id2 worked for me, too.


When you want to send an array through PATCH or POST method, it's better to use JSON or XML. (I use JSON)
In HTTP Request body you should follow like this:

{"params":["arg1", "arg2", ...]}

You can even use JSON object instead of array.

Detect URLs in text with JavaScript

Generic Object Oriented Solution

For people like me that use frameworks like angular that don't allow manipulating DOM directly, I created a function that takes a string and returns an array of url/plainText objects that can be used to create any UI representation that you want.

URL regex

For URL matching I used (slightly adapted) h0mayun regex: /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g

My function also drops punctuation characters from the end of a URL like . and , that I believe more often will be actual punctuation than a legit URL ending (but it could be! This is not rigorous science as other answers explain well) For that I apply the following regex onto matched URLs /^(.+?)([.,?!'"]*)$/.

Typescript code

    export function urlMatcherInText(inputString: string): UrlMatcherResult[] {
        if (! inputString) return [];

        const results: UrlMatcherResult[] = [];

        function addText(text: string) {
            if (! text) return;

            const result = new UrlMatcherResult();
            result.type = 'text';
            result.value = text;
            results.push(result);
        }

        function addUrl(url: string) {
            if (! url) return;

            const result = new UrlMatcherResult();
            result.type = 'url';
            result.value = url;
            results.push(result);
        }

        const findUrlRegex = /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g;
        const cleanUrlRegex = /^(.+?)([.,?!'"]*)$/;

        let match: RegExpExecArray;
        let indexOfStartOfString = 0;

        do {
            match = findUrlRegex.exec(inputString);

            if (match) {
                const text = inputString.substr(indexOfStartOfString, match.index - indexOfStartOfString);
                addText(text);

                var dirtyUrl = match[0];
                var urlDirtyMatch = cleanUrlRegex.exec(dirtyUrl);
                addUrl(urlDirtyMatch[1]);
                addText(urlDirtyMatch[2]);

                indexOfStartOfString = match.index + dirtyUrl.length;
            }
        }
        while (match);

        const remainingText = inputString.substr(indexOfStartOfString, inputString.length - indexOfStartOfString);
        addText(remainingText);

        return results;
    }

    export class UrlMatcherResult {
        public type: 'url' | 'text'
        public value: string
    }

Can Twitter Bootstrap alerts fade in as well as out?

I got this way to close fading my Alert after 3 seconds. Hope it will be useful.

    setTimeout(function(){
    $('.alert').fadeTo("slow", 0.1, function(){
        $('.alert').alert('close')
    });     
    }, 3000)

How do I exclude all instances of a transitive dependency when using Gradle?

In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:

compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
    exclude group: 'org.apache.httpcomponents', module: ''
    exclude group: 'org.slf4j', module: ''
}

Date Comparison using Java

private boolean checkDateLimit() {

    long CurrentDateInMilisecond = System.currentTimeMillis(); // Date 1
    long Date1InMilisecond = Date1.getTimeInMillis(); //Date2

    if (CurrentDateInMilisecond <= Date1InMilisecond) {
        return true;
    } else {
        return false;
    }

}

// Convert both date into milisecond value .

Open a folder using Process.Start

System.Diagnostics.Process.Start("explorer.exe",@"c:\teste"); 

This code works fine from the VS2010 environment and opens the local folder properly, but if you host the same application in IIS and try to open then it will fail for sure.

Pause in Python

In Windows, you can use the msvcrt module.

msvcrt.kbhit() Return true if a keypress is waiting to be read.

msvcrt.getch() Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

If you want it to also work on Unix-like systems you can try this solution using the termios and fcntl modules.

Create tap-able "links" in the NSAttributedString of a UILabel?

Here’s a Swift implementation that is about as minimal as possible that also includes touch feedback. Caveats:

  1. You must set fonts in your NSAttributedStrings
  2. You can only use NSAttributedStrings!
  3. You must ensure your links cannot wrap (use non breaking spaces: "\u{a0}")
  4. You cannot change the lineBreakMode or numberOfLines after setting the text
  5. You create links by adding attributes with .link keys

.

public class LinkLabel: UILabel {
    private var storage: NSTextStorage?
    private let textContainer = NSTextContainer()
    private let layoutManager = NSLayoutManager()
    private var selectedBackgroundView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        textContainer.lineFragmentPadding = 0
        layoutManager.addTextContainer(textContainer)
        textContainer.layoutManager = layoutManager
        isUserInteractionEnabled = true
        selectedBackgroundView.isHidden = true
        selectedBackgroundView.backgroundColor = UIColor(white: 0, alpha: 0.3333)
        selectedBackgroundView.layer.cornerRadius = 4
        addSubview(selectedBackgroundView)
    }

    public required convenience init(coder: NSCoder) {
        self.init(frame: .zero)
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        textContainer.size = frame.size
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        setLink(for: touches)
    }

    public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        setLink(for: touches)
    }

    private func setLink(for touches: Set<UITouch>) {
        if let pt = touches.first?.location(in: self), let (characterRange, _) = link(at: pt) {
            let glyphRange = layoutManager.glyphRange(forCharacterRange: characterRange, actualCharacterRange: nil)
            selectedBackgroundView.frame = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer).insetBy(dx: -3, dy: -3)
            selectedBackgroundView.isHidden = false
        } else {
            selectedBackgroundView.isHidden = true
        }
    }

    public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        selectedBackgroundView.isHidden = true
    }

    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        selectedBackgroundView.isHidden = true

        if let pt = touches.first?.location(in: self), let (_, url) = link(at: pt) {
            UIApplication.shared.open(url)
        }
    }

    private func link(at point: CGPoint) -> (NSRange, URL)? {
        let touchedGlyph = layoutManager.glyphIndex(for: point, in: textContainer)
        let touchedChar = layoutManager.characterIndexForGlyph(at: touchedGlyph)
        var range = NSRange()
        let attrs = attributedText!.attributes(at: touchedChar, effectiveRange: &range)
        if let urlstr = attrs[.link] as? String {
            return (range, URL(string: urlstr)!)
        } else {
            return nil
        }
    }

    public override var attributedText: NSAttributedString? {
        didSet {
            textContainer.maximumNumberOfLines = numberOfLines
            textContainer.lineBreakMode = lineBreakMode
            if let txt = attributedText {
                storage = NSTextStorage(attributedString: txt)
                storage!.addLayoutManager(layoutManager)
                layoutManager.textStorage = storage
                textContainer.size = frame.size
            }
        }
    }
}

How to programmatically get iOS status bar height

Try this:

CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;

How can I one hot encode in Python?

You can do the following as well. Note for the below you don't have to use pd.concat.

import pandas as pd 
# intialise data of lists. 
data = {'Color':['Red', 'Yellow', 'Red', 'Yellow'], 'Length':[20.1, 21.1, 19.1, 18.1],
       'Group':[1,2,1,2]} 

# Create DataFrame 
df = pd.DataFrame(data) 

for _c in df.select_dtypes(include=['object']).columns:
    print(_c)
    df[_c]  = pd.Categorical(df[_c])
df_transformed = pd.get_dummies(df)
df_transformed

You can also change explicit columns to categorical. For example, here I am changing the Color and Group

import pandas as pd 
# intialise data of lists. 
data = {'Color':['Red', 'Yellow', 'Red', 'Yellow'], 'Length':[20.1, 21.1, 19.1, 18.1],
       'Group':[1,2,1,2]} 

# Create DataFrame 
df = pd.DataFrame(data) 
columns_to_change = list(df.select_dtypes(include=['object']).columns)
columns_to_change.append('Group')
for _c in columns_to_change:
    print(_c)
    df[_c]  = pd.Categorical(df[_c])
df_transformed = pd.get_dummies(df)
df_transformed

Difference between SelectedItem, SelectedValue and SelectedValuePath

To answer a little more conceptually:

SelectedValuePath defines which property (by its name) of the objects bound to the ListBox's ItemsSource will be used as the item's SelectedValue.

For example, if your ListBox is bound to a collection of Person objects, each of which has Name, Age, and Gender properties, SelectedValuePath=Name will cause the value of the selected Person's Name property to be returned in SelectedValue.

Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath cannot be used.

SelectedItem, meanwhile, returns the entire Person object currently selected.

(Here's a further example from MSDN, using TreeView)

Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:

Note that these values are distinct from DisplayMemberPath (which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.

Inline style to act as :hover in CSS

I don't think jQuery supports the pseudo-selectors either, but it does provide a quick way to add events to one, many, or all of your similar controls and tags on a single page.

Best of all, you can chain the event binds and do it all in one line of script if you want. Much easier than manually editing all of the HTML to turn them on or off. Then again, since you can do the same in CSS I don't know that it buys you anything (other than learning jQuery).

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){
    print("success!");
}

Accessing constructor of an anonymous class

Here's another way around the problem:

public class Test{

    public static final void main(String...args){

        new Thread(){

            private String message = null;

            Thread initialise(String message){

                this.message = message;
                return this;
            }

            public void run(){
                System.out.println(message);
            }
        }.initialise(args[0]).start();
    }
}

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If sudo make uninstall is unavailable:

In a Debian based system, instead of (or after*) doing make install you can run sudo checkinstall to make a .deb file that gets automatically installed. You can then remove it using the system package manager (e.g. apt/synaptic/aptitude/dpkg). Checkinstall also supports creating other types of package, e.g. RPM.

See also http://community.linuxmint.com/tutorial/view/162 and some basic checkinstall usage and debian checkinstall package.


*: If you're reading this after having installed with make install you can still follow the above instructions and do a dpkg -r $PACKAGE_NAME_YOU_CHOSEN afterwards.

close vs shutdown socket?

"shutdown() doesn't actually close the file descriptor—it just changes its usability. To free a socket descriptor, you need to use close()."1

Get PHP class property by string

In case anyone else wants to find a deep property of unknown depth, I came up with the below without needing to loop through all known properties of all children.

For example, to find $Foo->Bar->baz, or $Foo->baz, or $Foo->Bar->Baz->dave, where $path is a string like 'foo/bar/baz'.

public function callModule($pathString, $delimiter = '/'){

    //split the string into an array
    $pathArray = explode($delimiter, $pathString);

    //get the first and last of the array
    $module = array_shift($pathArray);
    $property = array_pop($pathArray);

    //if the array is now empty, we can access simply without a loop
    if(count($pathArray) == 0){
        return $this->{$module}->{$property};
    }

    //we need to go deeper
    //$tmp = $this->Foo
    $tmp = $this->{$module};

    foreach($pathArray as $deeper){
        //re-assign $tmp to be the next level of the object
        // $tmp = $Foo->Bar --- then $tmp = $Bar->baz
        $tmp = $tmp->{$deeper};
    }

    //now we are at the level we need to be and can access the property
    return $tmp->{$property};

}

And then call with something like:

$propertyString = getXMLAttribute('string'); // '@Foo/Bar/baz'
$propertyString = substr($propertyString, 1);
$moduleCaller = new ModuleCaller();
echo $moduleCaller->callModule($propertyString);

Page Redirect after X seconds wait using JavaScript

<script type="text/javascript">
      function idleTimer() {
    var t;
    //window.onload = resetTimer;
    window.onmousemove = resetTimer; // catches mouse movements
    window.onmousedown = resetTimer; // catches mouse movements
    window.onclick = resetTimer;     // catches mouse clicks
    window.onscroll = resetTimer;    // catches scrolling
    window.onkeypress = resetTimer;  //catches keyboard actions

    function logout() {
        window.location.href = 'logout.php';  //Adapt to actual logout script
    }

   function reload() {
          window.location = self.location.href;  //Reloads the current page
   }

   function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 1800000);  // time is in milliseconds (1000 is 1 second)
        t= setTimeout(reload, 300000);  // time is in milliseconds (1000 is 1 second)
    }
}
idleTimer();
        </script>

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

when pushing using

git push heroku production:master 

your public key under home directory ~/.ssh/id_rsa is used

To fix this

you should login as a different user may be root

sudo su 

then start fresh by issuing the following commands

heroku keys:clear //removes existing keys
ssh-keygen -t rsa //generates a new key in ~/.ssh folder (set a password)
heroku keys:add   //uploads the new key, ~/.ssh/id_rsa is uploaded                      
git push heroku production:master

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.

First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )

I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.

var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).

So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.

Im guesssing your label should always be there?

So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.

css3 transition animation on load?

Very little Javascript is necessary:

window.onload = function() {
    document.body.className += " loaded";
}

Now the CSS:

.fadein {
    opacity: 0;
    -moz-transition: opacity 1.5s;
    -webkit-transition: opacity 1.5s;
    -o-transition: opacity 1.5s;
    transition: opacity 1.5s;
}

body.loaded .fadein {
    opacity: 1;
}

I know the question said "without Javascript", but I think it's worth pointing out that there is an easy solution involving one line of Javascript.

It could even be inline Javascript, something like that:

<body onload="document.body.className += ' loaded';" class="fadein">

That's all the JavaScript that's needed.

How to deploy a Java Web Application (.war) on tomcat?

Log in :URL = "localhost:8080/" Enter username and pass word Click Manager App Scroll Down and find "WAR file to deploy" Chose file and click deploy

Done

Go to Webapp folder of you Apache tomcat you will see a folder name matching with your war file name.

Type link in your url address bar:: localhost:8080/HelloWorld/HelloWorld.html and press enter

Done

Windows.history.back() + location.reload() jquery

After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2), because the code stops running after the window.history.go(-2). Also the html spec basically views a history.go(-2) to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.

The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true'); Then in the "theme" or the next page that needs to be refreshed do:

if (sessionStorage.getItem("refresh") == "true") { 
    sessionStorage.removeItem("refresh"); window.location.reload()
}

So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.

Hope this helps someone with this bit of frustration.

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Converting any object to a byte array in java

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

How can I make the cursor turn to the wait cursor?

Actually,

Cursor.Current = Cursors.WaitCursor;

temporarily sets the Wait cursor, but doesn’t ensure that the Wait cursor shows until the end of your operation. Other programs or controls within your program can easily reset the cursor back to the default arrow as in fact happens when you move mouse while operation is still running.

A much better way to show the Wait cursor is to set the UseWaitCursor property in a form to true:

form.UseWaitCursor = true;

This will display wait cursor for all controls on the form until you set this property to false. If you want wait cursor to be shown on Application level you should use:

Application.UseWaitCursor = true;

Compare DATETIME and DATE ignoring time portion

You may use DateDiff and compare by day.

DateDiff(dd,@date1,@date2) > 0

It means @date2 > @date1

For example :

select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00') 

has the result : 1

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

As an additional reference for the other responses, instead of using "UTF-8" you can use:

HTTP.UTF_8

which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.

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

import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}

return this._http.get('http://url/login/' + email + '/' + password)
       .map((res: Response) => {
           return res.json();
        }).catch(this._handleError);

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

How can I control the width of a label tag?

Using CSS, of course...

label { display: block; width: 100px; }

The width attribute is deprecated, and CSS should always be used to control these kinds of presentational styles.

How do I find out if the GPS of an Android device is enabled

Here is the snippet worked in my case

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`

Transparent background on winforms?

I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.

How can I run NUnit tests in Visual Studio 2017?

Add the NUnit test adapter NuGet package to your test projects

Or install the Test Adapter Visual Studio extension. There is one for

I prefer the NuGet package, because it will be in sync with the NUnit version used by your project and will thus automatically match the version used in any build server.

get current date with 'yyyy-MM-dd' format in Angular 4

you can try doing this.


component.ts

currentDate = new Date();

component.html

{{currentDate | date:'yyyy-MM-dd'}}

How to open standard Google Map application from my application?

Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.

It happens when you use some emulator like androVM which is not installed google map by default.

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

How to import a csv file using python with headers intact, where first column is a non-numerical

You can use pandas library and reference the rows and columns like this:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X

"SMTP Error: Could not authenticate" in PHPMailer

  1. first go to https://myaccount.google.com
  2. Select Security tab
  3. Scroll down and select 'Less secure app access'
  4. Turn on access

This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.

Making a drop down list using swift?

Unfortunately if you're looking to apply UIPopoverController in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover property to achieve the same result.

Popover

In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.

Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle

Remove all occurrences of a value from a list?

hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
     if hello[item] == ' ': 
#if there is a match, rebuild the list with the list before the item + the list after the item
         hello = hello[:item] + hello [item + 1:]
print hello

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Bootstrap 4 - Inline List?

.list-inline class in bootstrap is a Inline Unordered List.

If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class

<div class="list-inline">
    <a href="#" class="list-inline-item">First item</a>
    <a href="#" class="list-inline-item">Secound item</a>
    <a href="#" class="list-inline-item">Third item</a>
  </div>

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How to list the size of each file and directory and sort by descending size in Bash?

Command

du -h --max-depth=0 * | sort -hr

Output

3,5M    asdf.6000.gz
3,4M    asdf.4000.gz
3,2M    asdf.2000.gz
2,5M    xyz.PT.gz
136K    xyz.6000.gz
116K    xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K    desc.common.tcl
8,0K    wer.2000p.gz
8,0K    wer.2000.gz
4,0K    ttree.3

Explanation

  • du displays "disk usage"
  • h is for "human readable" (both, in sort and in du)
  • max-depth=0 means du will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)
  • r is for "reverse" (biggest file first)

ncdu

When I came to this question, I wanted to clean up my file system. The command line tool ncdu is way better suited to this task.

Installation on Ubuntu:

$ sudo apt-get install ncdu

Usage:

Just type ncdu [path] in the command line. After a few seconds for analyzing the path, you will see something like this:

$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
.  96,1 GiB [##########] /home
.  17,7 GiB [#         ] /usr
.   4,5 GiB [          ] /var
    1,1 GiB [          ] /lib
  732,1 MiB [          ] /opt
. 275,6 MiB [          ] /boot
  198,0 MiB [          ] /storage
. 153,5 MiB [          ] /run
.  16,6 MiB [          ] /etc
   13,5 MiB [          ] /bin
   11,3 MiB [          ] /sbin
.   8,8 MiB [          ] /tmp
.   2,2 MiB [          ] /dev
!  16,0 KiB [          ] /lost+found
    8,0 KiB [          ] /media
    8,0 KiB [          ] /snap
    4,0 KiB [          ] /lib64
e   4,0 KiB [          ] /srv
!   4,0 KiB [          ] /root
e   4,0 KiB [          ] /mnt
e   4,0 KiB [          ] /cdrom
.   0,0   B [          ] /proc
.   0,0   B [          ] /sys
@   0,0   B [          ]  initrd.img.old
@   0,0   B [          ]  initrd.img
@   0,0   B [          ]  vmlinuz.old
@   0,0   B [          ]  vmlinuz

Delete the currently highlighted element with d, exit with CTRL + c

Convert array to JSON

because my array was like below: and I used .push function to create it dynamically

my_array = ["234", "23423"];

The only way I converted my array into json is

json = Object.assign({}, my_array);

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Bold words in a string of strings.xml in Android

You can do it from string

 <resources xmlns:tools="http://schemas.android.com/tools">

 <string name="total_review"><b>Total Review: </b> </string>

 </resources>

and can access it from the java code like

proDuctReviewNumber.setText(getResources().getString(R.string.total_review)+productDetailsSuccess.getProductTotalReview());

Cancel a vanilla ECMAScript 6 Promise chain

simple version:

just give out the reject function.

function Sleep(ms,cancel_holder) {

 return new Promise(function(resolve,reject){
  var done=false; 
  var t=setTimeout(function(){if(done)return;done=true;resolve();}, ms);
  cancel_holder.cancel=function(){if(done)return;done=true;if(t)clearTimeout(t);reject();} 
 })
}

a wraper solution (factory)

the solution I found is to pass a cancel_holder object. it will have a cancel function. if it has a cancel function then it is cancelable.

This cancel function rejects the promise with Error('canceled').

Before resolve, reject, or on_cancel prevent the cancel function to be called without reason.

I have found convenient to pass the cancel action by injection

function cancelablePromise(cancel_holder,promise_fn,optional_external_cancel) {
  if(!cancel_holder)cancel_holder={};
  return new Promise( function(resolve,reject) {
    var canceled=false;
    var resolve2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; resolve.apply(this,arguments);}
    var reject2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; reject.apply(this,arguments);}
    var on_cancel={}
    cancel_holder.cancel=function(){
      if(canceled) return; canceled=true;

      delete cancel_holder.cancel;
      cancel_holder.canceled=true;

      if(on_cancel.cancel)on_cancel.cancel();
      if(optional_external_cancel)optional_external_cancel();

      reject(new Error('canceled'));
    };

    return promise_fn.call(this,resolve2,reject2,on_cancel);        
  });
}

function Sleep(ms,cancel_holder) {

 return cancelablePromise(cancel_holder,function(resolve,reject,oncacnel){

  var t=setTimeout(resolve, ms);
  oncacnel.cancel=function(){if(t)clearTimeout(t);}     

 })
}


let cancel_holder={};

// meanwhile in another place it can be canceled
setTimeout(function(){  if(cancel_holder.cancel)cancel_holder.cancel(); },500) 

Sleep(1000,cancel_holder).then(function() {
 console.log('sleept well');
}, function(e) {
 if(e.message!=='canceled') throw e;
 console.log('sleep interrupted')
})

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

Download file through an ajax call php

A very simple solution using jQuery:

on the client side:

$('.act_download_statement').click(function(e){
    e.preventDefault();
    form = $('#my_form');
    form.submit();
});

and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

What is Func, how and when is it used

I find Func<T> very useful when I create a component that needs to be personalized "on the fly".

Take this very simple example: a PrintListToConsole<T> component.

A very simple object that prints this list of objects to the console. You want to let the developer that uses it personalize the output.

For example, you want to let him define a particular type of number format and so on.

Without Func

First, you have to create an interface for a class that takes the input and produces the string to print to the console.

interface PrintListConsoleRender<T> {
  String Render(T input);
}

Then you have to create the class PrintListToConsole<T> that takes the previously created interface and uses it over each element of the list.

class PrintListToConsole<T> {

    private PrintListConsoleRender<T> _renderer;

    public void SetRenderer(PrintListConsoleRender<T> r) {
        // this is the point where I can personalize the render mechanism
        _renderer = r;
    }

    public void PrintToConsole(List<T> list) {
        foreach (var item in list) {
            Console.Write(_renderer.Render(item));
        }
    }   
}

The developer that needs to use your component has to:

  1. implement the interface

  2. pass the real class to the PrintListToConsole

    class MyRenderer : PrintListConsoleRender<int> {
        public String Render(int input) {
            return "Number: " + input;
        }
    }
    
    class Program {
        static void Main(string[] args) {
            var list = new List<int> { 1, 2, 3 };
            var printer = new PrintListToConsole<int>();
            printer.SetRenderer(new MyRenderer());
            printer.PrintToConsole(list);
            string result = Console.ReadLine();   
        }   
    }
    

Using Func it's much simpler

Inside the component you define a parameter of type Func<T,String> that represents an interface of a function that takes an input parameter of type T and returns a string (the output for the console)

class PrintListToConsole<T> {

    private Func<T, String> _renderFunc;

    public void SetRenderFunc(Func<T, String> r) {
        // this is the point where I can set the render mechanism
        _renderFunc = r;
    }

    public void Print(List<T> list) {
        foreach (var item in list) {
            Console.Write(_renderFunc(item));
        }
    }
}

When the developer uses your component he simply passes to the component the implementation of the Func<T, String> type, that is a function that creates the output for the console.

class Program {
    static void Main(string[] args) {
        var list = new List<int> { 1, 2, 3 }; // should be a list as the method signature expects
        var printer = new PrintListToConsole<int>();
        printer.SetRenderFunc((o) => "Number:" + o);
        printer.Print(list); 
        string result = Console.ReadLine();
    }
}

Func<T> lets you define a generic method interface on the fly. You define what type the input is and what type the output is. Simple and concise.

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

Is there any way to configure multiple registries in a single npmrc file

I encounter the same problem when my company set up its own registry, so I heavily rework on proxy-registry into proxy-multi-registries to solve this problem. Hope it will also helps you.

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Deciding between HttpClient and WebClient

HttpClientFactory

It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...) everywhere.

Receive result from DialogFragment

if you want to send arguments and receive the result from second fragment, you may use Fragment.setArguments to accomplish this task

static class FirstFragment extends Fragment {
    final Handler mUIHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 101: // receive the result from SecondFragment
                Object result = msg.obj;
                // do something according to the result
                break;
            }
        };
    };

    void onStartSecondFragments() {
        Message msg = Message.obtain(mUIHandler, 101, 102, 103, new Object()); // replace Object with a Parcelable if you want to across Save/Restore
                                                                               // instance
        putParcelable(new SecondFragment(), msg).show(getFragmentManager().beginTransaction(), null);
    }
}

static class SecondFragment extends DialogFragment {
    Message mMsg; // arguments from the caller/FirstFragment

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);
        mMsg = getParcelable(this);
    }

    void onClickOK() {
        mMsg.obj = new Object(); // send the result to the caller/FirstFragment
        mMsg.sendToTarget();
    }
}

static <T extends Fragment> T putParcelable(T f, Parcelable arg) {
    if (f.getArguments() == null) {
        f.setArguments(new Bundle());
    }
    f.getArguments().putParcelable("extra_args", arg);
    return f;
}
static <T extends Parcelable> T getParcelable(Fragment f) {
    return f.getArguments().getParcelable("extra_args");
}

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

how to find seconds since 1970 in java

Based on your desire that 1317427200 be the output, there are several layers of issue to address.

  • First as others have mentioned, java already uses a UTC 1/1/1970 epoch. There is normally no need to calculate the epoch and perform subtraction unless you have weird locale rules.

  • Second, when you create a new Calendar it's initialized to 'now' so it includes the time of day. Changing the year/month/day doesn't affect the time of day fields. So if you want it to represent midnight of the date, you need to zero out the calendar before you set the date.

  • Third, you haven't specified how you're supposed to handle time zones. Daylight Savings can cause differences in the absolute number of seconds represented by a particular calendar-on-the-wall-date, depending on where your JVM is running. Since epoch is in UTC, we probably want to work in UTC times? You may need to seek clarification from the makers of the system you're interfacing with.

  • Fourth, months in Java are zero indexed. January is 0, October is 9.

Putting all that together

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;

that will give you 1317427200

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

How to cast Object to its actual type?

Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :

(abc)(obj)).MyFunction();

if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.

"Fatal error: Cannot redeclare <function>"

If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.

Import a file from a subdirectory?

Try import .lib.BoxTime. For more information read about relative import in PEP 328.

"Android library projects cannot be launched"?

In Eclipse Project -> Clean Modify project.properties like this :

target=android-10
android.library.reference.1=F:/svn/WiEngine_library

What is the difference between Scala's case class and class?

Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.

This functional concept allows us to

  • use a compact initialization syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

In combination with inheritance, case classes are used to mimic algebraic datatypes.

If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Take multiple lists into dataframe

you can simple use this following code

train_data['labels']= train_data[["LABEL1","LABEL1","LABEL2","LABEL3","LABEL4","LABEL5","LABEL6","LABEL7"]].values.tolist()
train_df = pd.DataFrame(train_data, columns=['text','labels'])

How to delete specific rows and columns from a matrix in a smarter way?

You can also remove rows and columns by feeding a vector of logical boolean values to the matrix. This handles the situation where you have multiple non-contiguous rows or non-contiguous columns that need to be deleted.

# TRUE = Keep a row/column
# FALSE = Delete a row/column
#
# FALSE for rows 4, 5, and 6
# Row:            1     2     3     4      5      6      7     8     9     10
rows_to_keep <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
    
# FALSE for columns 7, 8, and 9
# Column:         1     2     3     4     5     6     7      8      9      10
cols_to_keep <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE) 

To remove just the rows:

t1 <- t1[rows_to_keep,]

To remove just the columns:

t1 <- t1[,cols_to_keep]

To remove both the rows and columns:

t1 <- t1[rows_to_keep, cols_to_keep]

This coding technique is useful if you don't know in advance what rows or columns you need to remove. The rows_to_keep and cols_to_keep vectors can be calculated as appropriate by your code.

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

Firebug like plugin for Safari browser

Why do you want to use Firebug if Safari already comes with great Developer tools? :)

As Matt said, you can enable them from the preferences menu.

Here you will find an overview, summarized, of the Safari's Web inspector, and how to use it:

biggest integer that can be stored in a double

Wikipedia has this to say in the same context with a link to IEEE 754:

On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit.

2^53 is just over 9 * 10^15.

Where IN clause in LINQ

The "IN" clause is built into linq via the .Contains() method.

For example, to get all People whose .States's are "NY" or "FL":

using (DataContext dc = new DataContext("connectionstring"))
{
    List<string> states = new List<string>(){"NY", "FL"};
    List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

How to prevent colliders from passing through each other?

How about set the Collision Detection of rigidbody to Continuous or Continuous Dynamic?

http://unity3d.com/support/documentation/Components/class-Rigidbody.html

how to split the ng-repeat data with three columns using bootstrap

This example produces a nested repeater where the outer data includes an inner array which I wanted to list in two column. The concept would hold true for three or more columns.

In the inner column I repeat the "row" until the limit is reached. The limit is determined by dividing the length of the array of items by the number of columns desired, in this case by two. The division method sits on the controller and is passed the current array length as a parameter. The JavaScript slice(0, array.length / columnCount) function then applied the limit to the repeater.

The second column repeater is then invoked and repeats slice( array.length / columnCount, array.length) which produces the second half of the array in column two.

<div class="row" ng-repeat="GroupAccess in UsersController.SelectedUser.Access" ng-class="{even: $even, odd: $odd}">
    <div class="col-md-12 col-xs-12" style=" padding-left:15px;">
        <label style="margin-bottom:2px;"><input type="checkbox" ng-model="GroupAccess.isset" />{{GroupAccess.groupname}}</label>
    </div>
    <div class="row" style=" padding-left:15px;">
        <div class="col-md-1 col-xs-0"></div>
        <div class="col-md-3 col-xs-2">
            <div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice(0, state.DivideBy2(GroupAccess.features.length))">
                <span class="GrpFeature">{{Feature.featurename}}</span>
            </div>
        </div>
        <div class="col-md-3 col-xs-2">
            <div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice( state.DivideBy2(GroupAccess.features.length), GroupAccess.features.length )">
                <span class="GrpFeature">{{Feature.featurename}}</span>
            </div>
        </div>
        <div class="col-md-5 col-xs-8">
        </div>
    </div>
</div>


// called to format two columns
state.DivideBy2 = function(nValue) {
    return Math.ceil(nValue /2);
};

Hope this helps to look at the solution in yet another way. (PS this is my first post here! :-))

How can I refresh c# dataGridView after update ?

I know thats an old topic but i suddenly found the best way of doing it and it does not require nullifying the datasource and reassigning it. Just use a BindingList instead of a List.

for example:

//declare your list
private BindingList<myclass> mMyList = new BindingList<myclass>();

//then bind it to your datagrid, i usually do it on the Load event
private void Form1_Load(object sender, EventArgs e)
{
    _dgMyDatagrig.DataSource = mMyList;
}

//start populating your list 
private void addItem(mycclass item)
{
    mMylist.add(item);

//the datagrid will show automatically the new added/updated items, no need to do anything else

}

How to convert a char array to a string?

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

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

What does "|=" mean? (pipe equal operator)

| is the bitwise-or operator, and it is being applied like +=.

Origin is not allowed by Access-Control-Allow-Origin

This is because of same-origin policy. See more at Mozilla Developer Network or Wikipedia.

Basically, in your example, you need load the http://nqatalog.negroesquisso.pt/login.php page only from nqatalog.negroesquisso.pt, not localhost.

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

Returning IEnumerable<T> vs. IQueryable<T>

Both will give you deferred execution, yes.

As for which is preferred over the other, it depends on what your underlying datasource is.

Returning an IEnumerable will automatically force the runtime to use LINQ to Objects to query your collection.

Returning an IQueryable (which implements IEnumerable, by the way) provides the extra functionality to translate your query into something that might perform better on the underlying source (LINQ to SQL, LINQ to XML, etc.).

How to find the number of days between two dates

To find the number of days between two dates, you use:

DATEDIFF ( d, startdate , enddate )

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

Warning: Found conflicts between different versions of the same dependent assembly

This warning means that two projects reference the same assembly (e.g. System.Windows.Forms) but the two projects require different versions. You have a few options:

  1. Recompile all projects to use the same versions (e.g. move all to .Net 3.5). This is the preferred option because all code is running with the versions of dependencies they were compiled with.

  2. Add a binding redirect. This will suppress the warning. However, your .Net 2.0 projects will (at runtime) be bound to the .Net 3.5 versions of dependent assemblies such as System.Windows.Forms. You can quickly add a binding redirect by double-clicking on error in Visual Studio.

  3. Use CopyLocal=true. I'm not sure if this will suppress the warning. It will, like option 2 above, mean that all projects will use the .Net 3.5 version of System.Windows.Forms.

Here are a couple of ways to identify the offending reference(s):

  • You can use a utility such as the one found at https://gist.github.com/1553265
  • Another simple method is to set Build output verbosity (Tools, Options, Projects and Solutions, Build and Run, MSBuild project build output verbosity, Detailed) and after building, search the output window for the warning, and look at the text just above it. (Hat tip to pauloya who suggested this in the comments on this answer).

Why Choose Struct Over Class?

Similarities between structs and classes.

I created gist for this with simple examples. https://github.com/objc-swift/swift-classes-vs-structures

And differences

1. Inheritance.

structures can't inherit in swift. If you want

class Vehicle{
}

class Car : Vehicle{
}

Go for an class.

2. Pass By

Swift structures pass by value and class instances pass by reference.

Contextual Differences

Struct constant and variables

Example (Used at WWDC 2014)

struct Point{
 
   var x = 0.0;
   var y = 0.0;

} 

Defines a struct called Point.

var point = Point(x:0.0,y:2.0)

Now if I try to change the x. Its a valid expression.

point.x = 5

But if I defined a point as constant.

let point = Point(x:0.0,y:2.0)
point.x = 5 //This will give compile time error.

In this case entire point is immutable constant.

If I used a class Point instead this is a valid expression. Because in a class immutable constant is the reference to the class itself not its instance variables (Unless those variables defined as constants)

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

insert data from one table to another in mysql

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC));

Using @property versus getters and setters

I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.

Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.

In Python, people actually care for that kind of overhead, so that you can embrace the following practice :

  • Do not use getters and setters at first, when if they not needed
  • Use @property to implement them without changing the syntax of the rest of your code.

ASP.Net 2012 Unobtrusive Validation with jQuery

I suggest to instead this lines

<div>
    <asp:TextBox runat="server" ID="username" />
    <asp:RequiredFieldValidator ErrorMessage="The username is required" ControlToValidate="username" runat="server" Text=" - Required" />
</div>

by this line

<div>
    <asp:TextBox runat="server" ID="username" required />
</div>

Center an element with "absolute" position and undefined width in CSS?

Flexbox can be used to center an absolute positioned div.

display: flex;
align-items: center;
justify-content: center;

_x000D_
_x000D_
.relative {
  width: 275px;
  height: 200px;
  background: royalblue;
  color: white;
  margin: auto;
  position: relative;
}

.absolute-block {
  position: absolute;
  height: 36px;
  background: orange;
  padding: 0px 10px;
  bottom: -5%;
  border: 1px solid black;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 10px 2px rgba(0, 0, 0, 0.3);
}
_x000D_
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>
_x000D_
_x000D_
_x000D_

How to open/run .jar file (double-click not working)?

There are two different types of Java to download: The JDK, which is used to write Java programs, and the RE (runtime environment), which is used to actually run Java programs. Are you sure that you installed the RE instead of the SDK?

Get a list of numbers as input from the user

try this one ,

n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
    a=raw_input()
    if(a.isdigit()):
        l1.insert(i,float(a)) #statement1
    else:
        l1.insert(i,a)        #statement2

If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.

How to find Current open Cursors in Oracle

Total cursors open, by session:

select a.value, s.username, s.sid, s.serial#
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic#  and s.sid=a.sid
and b.name = 'opened cursors current';

Source: http://www.orafaq.com/node/758

As far as I know queries on v$ views are based on pseudo-tables ("x$" tables) that point directly to the relevant portions of the SGA, so you can't get more accurate than that; however this also means that it is point-in-time (i.e. dirty read).

SQL Server® 2016, 2017 and 2019 Express full download

Scott Hanselman put together a great summary page with all of the various SQL downloads here https://www.hanselman.com/blog/DownloadSQLServerExpress.aspx.

For offline installers, see this answer https://stackoverflow.com/a/42952186/407188

ViewBag, ViewData and TempData

Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.

How to style the parent element when hovering a child element?

Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.

But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:

<parent>
    <sibling></sibling>
    <child></child>
</parent>

The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!

Now, how to style the sibling?

When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:

parent sibling { }
parent sibling:hover { }
parent:hover sibling { }

These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:

div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}

Style parent image example

Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.

Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.

How can I find out what version of git I'm running?

In a command prompt:

$ git --version

How to copy directories with spaces in the name

After some trial and error and observing the results (in other words, I hacked it), I got it to work.

Quotes ARE required to use a path name with spaces. The trick is there MUST be a space after the path names before the closing quote...like this...

robocopy "C:\Source Path " "C:\Destination Path " /option1 /option2...

This almost seems like a bug and certainly not very intuitive.

Todd K.

Easy way to export multiple data.frame to multiple Excel worksheets

I do it in this way for openxlsx using following function

mywritexlsx<-function(fname="temp.xlsx",sheetname="Sheet1",data,
                  startCol = 1, startRow = 1, colNames = TRUE, rowNames = FALSE)
{
  if(! file.exists(fname))
    wb = createWorkbook()
  else
   wb <- loadWorkbook(file =fname)
  sheet = addWorksheet(wb, sheetname)

  writeData(wb,sheet,data,startCol = startCol, startRow = startRow, 
          colNames = colNames, rowNames = rowNames)
  saveWorkbook(wb, fname,overwrite = TRUE)
}

How to declare a static const char* in your header file?

The error is that you cannot initialize a static const char* within the class. You can only initialize integer variables there.

You need to declare the member variable in the class, and then initialize it outside the class:

// header file

class Foo {
    static const char *SOMETHING;
    // rest of class
};

// cpp file

const char *Foo::SOMETHING = "sommething";

If this seems annoying, think of it as being because the initialization can only appear in one translation unit. If it was in the class definition, that would usually be included by multiple files. Constant integers are a special case (which means the error message perhaps isn't as clear as it might be), and compilers can effectively replace uses of the variable with the integer value.

In contrast, a char* variable points to an actual object in memory, which is required to really exist, and it's the definition (including initialization) which makes the object exist. The "one definition rule" means you therefore don't want to put it in a header, because then all translation units including that header would contain the definition. They could not be linked together, even though the string contains the same characters in both, because under current C++ rules you've defined two different objects with the same name, and that's not legal. The fact that they happen to have the same characters in them doesn't make it legal.

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

How to open child forms positioned within MDI parent in VB.NET?

Try the code below and.....

1 - change the name of the MENU as in my sample the menuitem was called 'Form7ToolStripMenuItem_Click'

2 - make SURE to paste it into an MDIFORM and not just a basic FORM

Then let me know if the CHILD form still shows OUTSIDE the parent form

Private Sub Form7ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Form7ToolStripMenuItem.Click

    Dim NewForm As System.Windows.Forms.Form
    NewForm = New System.Windows.Forms.Form
    'USE THE NEXT LINE - to add an existing CUSTOM form you already have
    'NewForm = Form7                         
    NewForm.Width = 400
    NewForm.Height = 250
    NewForm.MdiParent = Me
    NewForm.Text = "CAPTION"
    NewForm.Show()
    DockChildForm(NewForm, "left")          'dock left
    'DockChildForm(NewForm, "right")         'dock right
    'DockChildForm(NewForm, "top")           'dock top
    'DockChildForm(NewForm, "bottom")        'doc bottom
    'DockChildForm(NewForm, "full")          'fill the client area (maximise the child INSIDE the parent)
    'DockChildForm(NewForm, "Anything-Else") 'center the form

End Sub

Private Sub DockChildForm(ByRef Form2Dock As Form, ByVal Position As String)

    Dim XYpoint As Point
    Select Case Position
        Case "left"
            Form2Dock.Dock = DockStyle.Left
        Case "top"
            Form2Dock.Dock = DockStyle.Top
        Case "right"
            Form2Dock.Dock = DockStyle.Right
        Case "bottom"
            Form2Dock.Dock = DockStyle.Bottom
        Case "full"
            Form2Dock.Dock = DockStyle.Fill
        Case Else
            XYpoint = New Point
            XYpoint.X = ((Me.ClientSize.Width - Form2Dock.Width) / 2)
            XYpoint.Y = ((Me.ClientSize.Height - Form2Dock.Height) / 2)
            Form2Dock.Location = XYpoint
    End Select
End Sub

How to rename a table column in Oracle 10g

alter table table_name 
rename column old_column_name/field_name to new_column_name/field_name;

example: alter table student column name to username;

SQL Server : Transpose rows to columns

SQL Server has a PIVOT command that might be what you are looking for.

select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;

If the columns are not constant, you'll have to combine this with some dynamic SQL.

DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);

select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);

SELECT @sql =

'SELECT *
FROM TAG
PIVOT 
(
  MAX(Value) 
  FOR TagID IN( ' + @columns + ' )) as TagTime;';

 execute(@sql);

sql like operator to get the numbers only

what might get you where you want in plain SQL92:

select * from tbl where lower(answer) = upper(answer)

or, if you also want to be robust for leading/trailing spaces:

select * from tbl where lower(answer) = trim(upper(answer))

How to convert all tables in database to one collation?

@Namphibian's suggestion helped me a lot...
went a little further though and added columns and views to the script

just enter your schema's name below and it will do the rest

-- set your table name here
SET @MY_SCHEMA = "";

-- tables
SELECT DISTINCT
    CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=@MY_SCHEMA
  AND TABLE_TYPE="BASE TABLE"

UNION

-- table columns
SELECT DISTINCT
    CONCAT("ALTER TABLE ", C.TABLE_NAME, " CHANGE ", C.COLUMN_NAME, " ", C.COLUMN_NAME, " ", C.COLUMN_TYPE, " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.COLUMNS as C
    LEFT JOIN INFORMATION_SCHEMA.TABLES as T
        ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLLATION_NAME is not null
    AND C.TABLE_SCHEMA=@MY_SCHEMA
    AND T.TABLE_TYPE="BASE TABLE"

UNION

-- views
SELECT DISTINCT
    CONCAT("CREATE OR REPLACE VIEW ", V.TABLE_NAME, " AS ", V.VIEW_DEFINITION, ";") as queries
FROM INFORMATION_SCHEMA.VIEWS as V
    LEFT JOIN INFORMATION_SCHEMA.TABLES as T
        ON V.TABLE_NAME = T.TABLE_NAME
WHERE V.TABLE_SCHEMA=@MY_SCHEMA
    AND T.TABLE_TYPE="VIEW";

How to fix committing to the wrong Git branch?

So if your scenario is that you've committed to master but meant to commit to another-branch (which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.

// if your branch doesn't exist, then add the -b argument 
git checkout -b another-branch
git branch --force master origin/master

Now all your commits to master will be on another-branch.

Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

JavaScript checking for null vs. undefined and difference between == and ===

The spec is the place to go for full answers to these questions. Here's a summary:

  1. For a variable x, you can:

    • check whether it's null by direct comparison using ===. Example: x === null
    • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.

  2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

More reading:

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

Running a Python script from PHP

This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:

sh: blabla.py: command not found

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

$command = escapeshellcmd('python blabla.py');

Python datetime to string without microsecond component

As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.

isoformat(timespec='seconds', sep=' ')

Usage:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To declare a function that takes a pointer to an int:

void Foo(int *x);

To use this function:


int x = 4;
int *x_ptr = &x;
Foo(x_ptr);
Foo(&x);

If you want a pointer for another type of object, it's much the same:

void Foo(Object *o);

But, you may prefer to use references. They are somewhat less confusing than pointers:


// pass a reference
void Foo(int &x)
{
  x = 2;
}

//pass a pointer
void Foo_p(int *p)
{
   *x = 9;
}

// pass by value
void Bar(int x)
{
   x = 7;
}
int x = 4;
Foo(x);  // x now equals 2.
Foo_p(&x); // x now equals 9.
Bar(x);  // x still equals 9.

With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.

As recommended by others, check out the C++FAQLite. It's an excellent resource for this.

Edit 3 response:

bar = &foo means: Make bar point to foo in memory

Yes.

*bar = foo means Change the value that bar points to to equal whatever foo equals

Yes.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

bar will point to whatever oof points to. They will both point to the same thing.

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.

Converting File to MultiPartFile

This is a solution without creating manually a file on disc :

MultipartFile fichier = new MockMultipartFile("fileThatDoesNotExists.txt",
            "fileThatDoesNotExists.txt",
            "text/plain",
            "This is a dummy file content".getBytes(StandardCharsets.UTF_8));

java: ArrayList - how can I check if an index exists?

If your index is less than the size of your list then it does exist, possibly with null value. If index is bigger then you may call ensureCapacity() to be able to use that index.

If you want to check if a value at your index is null or not, call get()

Is it possible to make input fields read-only through CSS?

You don't set the behavior of controls via CSS, only their styling.You can use jquery or simple javascript to change the property of the fields.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}