Programs & Examples On #Centura

Team Developer (previously Centura), or SQLWindows, is a programming language based on Win32 by Gupta Technologies. It is a rapid application development language and considered world's first client/server relational database software that would run on Personal Computers (PC) rather than Mini Computers.

What is the worst programming language you ever worked with?

There are just two kinds of languages: the ones everybody complains about and the ones nobody uses.

Bjarne Stroustrup

Computational complexity of Fibonacci Sequence

The naive recursion version of Fibonacci is exponential by design due to repetition in the computation:

At the root you are computing:

F(n) depends on F(n-1) and F(n-2)

F(n-1) depends on F(n-2) again and F(n-3)

F(n-2) depends on F(n-3) again and F(n-4)

then you are having at each level 2 recursive calls that are wasting a lot of data in the calculation, the time function will look like this:

T(n) = T(n-1) + T(n-2) + C, with C constant

T(n-1) = T(n-2) + T(n-3) > T(n-2) then

T(n) > 2*T(n-2)

...

T(n) > 2^(n/2) * T(1) = O(2^(n/2))

This is just a lower bound that for the purpose of your analysis should be enough but the real time function is a factor of a constant by the same Fibonacci formula and the closed form is known to be exponential of the golden ratio.

In addition, you can find optimized versions of Fibonacci using dynamic programming like this:

static int fib(int n)
{
    /* memory */
    int f[] = new int[n+1];
    int i;

    /* Init */
    f[0] = 0;
    f[1] = 1;

    /* Fill */
    for (i = 2; i <= n; i++)
    {
        f[i] = f[i-1] + f[i-2];
    }

    return f[n];
}

That is optimized and do only n steps but is also exponential.

Cost functions are defined from Input size to the number of steps to solve the problem. When you see the dynamic version of Fibonacci (n steps to compute the table) or the easiest algorithm to know if a number is prime (sqrt(n) to analyze the valid divisors of the number). you may think that these algorithms are O(n) or O(sqrt(n)) but this is simply not true for the following reason: The input to your algorithm is a number: n, using the binary notation the input size for an integer n is log2(n) then doing a variable change of

m = log2(n) // your real input size

let find out the number of steps as a function of the input size

m = log2(n)
2^m = 2^log2(n) = n

then the cost of your algorithm as a function of the input size is:

T(m) = n steps = 2^m steps

and this is why the cost is an exponential.

Loading resources using getClass().getResource()

getClass().getResource(path) loads resources from the classpath, not from a filesystem path.

Singleton design pattern vs Singleton beans in Spring container

I find "per container per bean" difficult to apprehend. I would say "one bean per bean id in a container".Lets have an example to understand it. We have a bean class Sample. I have defined two beans from this class in bean definition, like:

<bean id="id1" class="com.example.Sample" scope="singleton">
        <property name="name" value="James Bond 001"/>    
</bean>    
<bean id="id7" class="com.example.Sample" scope="singleton">
        <property name="name" value="James Bond 007"/>    
</bean>

So when ever I try to get the bean with id "id1",the spring container will create one bean, cache it and return same bean where ever refered with id1. If I try to get it with id7, another bean will be created from Sample class, same will be cached and returned each time you referred that with id7.

This is unlikely with Singleton pattern. In Singlton pattern one object per class loader is created always. However in Spring, making the scope as Singleton does not restrict the container from creating many instances from that class. It just restricts new object creation for the same ID again, returning previously created object when an object is requested for the same id. Reference

How do you see the entire command history in interactive Python?

If you want to write the history to a file:

import readline
readline.write_history_file('python_history.txt')

The help function gives:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

How to add AUTO_INCREMENT to an existing column?

Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:

  1. Make a copy of the table with the data using INSERT SELECT:

    CREATE TABLE backupTable LIKE originalTable; 
    INSERT backupTable SELECT * FROM originalTable;
    
  2. Delete data from originalTable (to remove duplicate entries):

    TRUNCATE TABLE originalTable;
    
  3. To add AUTO_INCREMENT and PRIMARY KEY

    ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT;
    
  4. Copy data back to originalTable (do not include the newly created column (id), since it will be automatically populated)

    INSERT originalTable (col1, col2, col3) 
    SELECT col1, col2,col3
    FROM backupTable;
    
  5. Delete backupTable:

    DROP TABLE backupTable;
    

I hope this is useful!

More on the duplication of tables using CREATE LIKE:

Duplicating a MySQL table, indexes and data

How to validate phone numbers using regex

Although the answer to strip all whitespace is neat, it doesn't really solve the problem that's posed, which is to find a regex. Take, for instance, my test script that downloads a web page and extracts all phone numbers using the regex. Since you'd need a regex anyway, you might as well have the regex do all the work. I came up with this:

1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?

Here's a perl script to test it. When you match, $1 contains the area code, $2 and $3 contain the phone number, and $5 contains the extension. My test script downloads a file from the internet and prints all the phone numbers in it.

#!/usr/bin/perl

my $us_phone_regex =
        '1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?';


my @tests =
(
"1-234-567-8901",
"1-234-567-8901 x1234",
"1-234-567-8901 ext1234",
"1 (234) 567-8901",
"1.234.567.8901",
"1/234/567/8901",
"12345678901",
"not a phone number"
);

foreach my $num (@tests)
{
        if( $num =~ m/$us_phone_regex/ )
        {
                print "match [$1-$2-$3]\n" if not defined $4;
                print "match [$1-$2-$3 $5]\n" if defined $4;
        }
        else
        {
                print "no match [$num]\n";
        }
}

#
# Extract all phone numbers from an arbitrary file.
#
my $external_filename =
        'http://web.textfiles.com/ezines/PHREAKSANDGEEKS/PnG-spring05.txt';
my @external_file = `curl $external_filename`;
foreach my $line (@external_file)
{
        if( $line =~ m/$us_phone_regex/ )
        {
                print "match $1 $2 $3\n";
        }
}

Edit:

You can change \W* to \s*\W?\s* in the regex to tighten it up a bit. I wasn't thinking of the regex in terms of, say, validating user input on a form when I wrote it, but this change makes it possible to use the regex for that purpose.

'1?\s*\W?\s*([2-9][0-8][0-9])\s*\W?\s*([2-9][0-9]{2})\s*\W?\s*([0-9]{4})(\se?x?t?(\d*))?';

Win32Exception (0x80004005): The wait operation timed out

The problem you are having is the query command is taking too long. I believe that the default timeout for a query to execute is 15 seconds. You need to set the CommandTimeout (in seconds) so that it is long enough for the command to complete its execution. The "CommandTimeout" is different than the "Connection Timeout" in your connection string and must be set for each command.

In your sql Selecting Event, use the command:

e.Command.CommandTimeout = 60

for example:

Protected Sub SqlDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
    e.Command.CommandTimeout = 60
End Sub

What's the name for hyphen-separated case?

I've always called it, and heard it be called, 'dashcase.'

How to convert currentTimeMillis to a date in Java?

The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

Byte[] to InputStream or OutputStream

output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )

Convert Pixels to Points

points = (pixels / 96) * 72 on a standard XP/Vista/7 machine (factory defaults)

points = (pixels / 72) * 72 on a standard Mac running OSX (Factory defaults)

Windows runs as default at 96dpi (display) Macs run as default at 72 dpi (display)

72 POSTSCRIPT Points = 1 inch 12 POSTSCRIPT Points = 1 POSTSCRIPT Pica 6 POSTSCRIPT Picas = 72 Points = 1 inch

1 point = 1/72 inches = 25.4/72 mm = 0.3527 mm

DPI = Dots Per Inch PPI = Pixels Per Inch LPI = Lines per inch

More info if using em as measuring

16px = 1em (default for normal text) 8em = 16px * 8 Pixels/16 = em

PHP - Extracting a property from an array of objects

You can do it easily with ouzo goodies

$result = array_map(Functions::extract()->id, $arr);

or with Arrays (from ouzo goodies)

$result = Arrays::map($arr, Functions::extract()->id);

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

See also functional programming with ouzo (I cannot post a link).

Facebook Oauth Logout

Here's an alternative to the accepted answer that works in the current (2.12) version of the API.

<a href="#" onclick="logoutFromFacebookAndRedirect('/logout')">Logout</a>

<script>
    FB.init({
        appId: '{your-app-id}',
        cookie: true,
        xfbml: true,
        version: 'v2.12'
    });

    function logoutFromFacebookAndRedirect(redirectUrl) {
        FB.getLoginStatus(function (response) {
            if (response.status == 'connected')
                FB.logout(function (response) {
                    window.location.href = redirectUrl;
                });
            else
                window.location.href = redirectUrl;
        });
    }
</script>

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

What's the best UML diagramming tool?

I will add UMLet which I haven't tried yet, but have been selected at my office to start doing diagrams.
Looks simple, diagrams aren't sexy, but it seems quite complete with regard to the kind of diagrams you can do. Seems to have good export capabilities too (important!), is flexible can support custom components) and can be used as Eclipse plugin.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

The simplest way is to use the below code before you define your Driver.

System.setProperty("webdriver.firefox.bin",
                    "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Apache 13 permission denied in user's home directory

Have you changed the permissions on the individual files as well as just the directory?

chmod -R 777 /home/user/xxx

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

You need to provide a key.

Try doing this in your ListView Rows if you have a key property:

<TouchableHighlight key={item.key} underlayColor='#dddddd'>

If not, try just adding the item as the key:

<TouchableHighlight key={item} underlayColor='#dddddd'>

How to edit default dark theme for Visual Studio Code?

You cannot "edit" a default theme, they are "locked in"

However, you can copy it into your own custom theme, with the exact modifications you'd like.

For more info, see these articles: https://code.visualstudio.com/Docs/customization/themes https://code.visualstudio.com/docs/extensions/install-extension#_your-extensions-folder

If all you want to change is the colors for C++ code, you should look at overwriting the c++ support colorizer. For info about that, go here: https://code.visualstudio.com/docs/customization/colorizer

EDIT: The dark theme is found here: https://github.com/Microsoft/vscode/tree/80f8000c10b4234c7b027dccfd627442623902d2/extensions/theme-colorful-defaults

EDIT2: To clarify:

What is the "right" way to iterate through an array in Ruby?

Using the same method for iterating through both arrays and hashes makes sense, for example to process nested hash-and-array structures often resulting from parsers, from reading JSON files etc..

One clever way that has not yet been mentioned is how it's done in the Ruby Facets library of standard library extensions. From here:

class Array

  # Iterate over index and value. The intention of this
  # method is to provide polymorphism with Hash.
  #
  def each_pair #:yield:
    each_with_index {|e, i| yield(i,e) }
  end

end

There is already Hash#each_pair, an alias of Hash#each. So after this patch, we also have Array#each_pair and can use it interchangeably to iterate through both Hashes and Arrays. This fixes the OP's observed insanity that Array#each_with_index has the block arguments reversed compared to Hash#each. Example usage:

my_array = ['Hello', 'World', '!']
my_array.each_pair { |key, value| pp "#{key}, #{value}" }

# result: 
"0, Hello"
"1, World"
"2, !"

my_hash = { '0' => 'Hello', '1' => 'World', '2' => '!' }
my_hash.each_pair { |key, value| pp "#{key}, #{value}" }

# result: 
"0, Hello"
"1, World"
"2, !"

How to search for an element in a golang slice

As other guys commented before you can write your own procedure with anonymous function to solve this issue.

I used two ways to solve it:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Second method with less computational cost:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

The most common case I've seen for seemingly mysterious ArrayIndexOutOfBoundsExceptions, i.e. apparently not caused by your own array handling code, is the concurrent use of SimpleDateFormat. Particularly in a servlet or controller:

public class MyController {
  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

  public void handleRequest(ServletRequest req, ServletResponse res) {
    Date date = dateFormat.parse(req.getParameter("date"));
  }
}

If two threads enter the SimplateDateFormat.parse() method together you will likely see an ArrayIndexOutOfBoundsException. Note the synchronization section of the class javadoc for SimpleDateFormat.

Make sure there is no place in your code that are accessing thread unsafe classes like SimpleDateFormat in a concurrent manner like in a servlet or controller. Check all instance variables of your servlets and controllers for likely suspects.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

Simple JavaScript problem: onClick confirm not preventing default action

I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:

 $('.deleteObject').click(function () {
    var url = this.href;
    var confirmText = "Are you sure you want to delete this object?";
    if(confirm(confirmText)) {
        $.ajax({
            type:"POST",
            url:url,
            success:function () {
            // Here goes something...
            },
        });
    }
    return false;
});

Is there any way to call a function periodically in JavaScript?

The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

var intervalId = setInterval(function() {
  alert("Interval reached every 5s")
}, 5000);

// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);

See more @ setInterval() @ MDN Web Docs

mssql '5 (Access is denied.)' error during restoring database

A good solution that can work is go to files > and check the reallocate all files

Files relocate

Prevent HTML5 video from being downloaded (right-click saved)?

PHP sends the html5 video tag together with a session where the key is a random string and the value is the filename.

ini_set('session.use_cookies',1);
session_start();
$ogv=uniqid(); 
$_SESSION[$ogv]='myVideo.ogv';
$webm=uniqid(); 
$_SESSION[$webm]='myVideo.webm';
echo '<video autoplay="autoplay">'
    .'<source src="video.php?video='.$ogv.' type="video/ogg">'
    .'<source src="video.php?video='.$webm.' type="video/webm">'
    .'</video>'; 

Now PHP is asked to send the video. PHP recovers the filename; deletes the session and sends the video instantly. Additionally all the 'no cache' and mime-type headers must be present.

ini_set('session.use_cookies',1);
session_start();
$file='myhiddenvideos/'.$_SESSION[$_GET['video']];
$_SESSION=array();
$params = session_get_cookie_params();
setcookie(session_name(),'', time()-42000,$params["path"],$params["domain"],
                                         $params["secure"], $params["httponly"]);
if(!file_exists($file) or $file==='' or !is_readable($file)){
  header('HTTP/1.1 404 File not found',true);
  exit;
  }
readfile($file);
exit:

Now if the user copy the url in a new tab or use the context menu he will have no luck.

How do I correctly setup and teardown for my pytest class with tests?

import pytest
class Test:
    @pytest.fixture()
    def setUp(self):
        print("setup")
        yield "resource"
        print("teardown")

    def test_that_depends_on_resource(self, setUp):
        print("testing {}".format(setUp))

In order to run:

pytest nam_of_the_module.py -v 

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

Java Date cut off time information

With Joda-Time since version 2.0 you can use LocalDate.toDate().

Simply

// someDatetime is whatever java.util.Date you have.
Date someDay = new LocalDate(someDatetime).toDate();

Why should I use a container div in HTML?

The container div, and sometimes content div, are almost always used to allow for more sophisticated CSS styling. The body tag is special in some ways. Browsers don't treat it like a normal div; its position and dimensions are tied to the browser window.

But a container div is just a div and you can style it with margins and borders. You can give it a fixed width, and you can center it with margin-left: auto; margin-right: auto.

Plus, content, like a copyright notice for example, can go on the outside of the container div, but it can't go on the outside of the body, allowing for content on the outside of a border.

Session timeout in ASP.NET

If you are using Authentication, I recommend adding the following in web.config file.

In my case, users are redirected to the login page upon timing out:

<authentication mode="Forms">
    <forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

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

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

How to correctly dismiss a DialogFragment?

Why don't you try using only this code:

dismiss();

If you want to dismiss the Dialog Fragment by its own. You can simply put this code inside the dialog fragment where you want to dismiss the Dialog.

For example:

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

This will close the recent Dialog Fragment that is shown on the screen.

Hope it helps for you.

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

How to get class object's name as a string in Javascript?

As a more elementary situation it would be nice IF this had a property that could reference it's referring variable (heads or tails) but unfortunately it only references the instantiation of the new coinSide object.

javascript:  /* it would be nice but ... a solution NOT! */
function coinSide(){this.ref=this};
/* can .ref be set so as to identify it's referring variable? (heads or tails) */
heads = new coinSide();
tails = new coinSide();
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
alert(["FF's Gecko engine shows:\n\ntoss.toSource()  is  ", toss.toSource()])

which always displays

[object Object]

and Firefox's Gecko engine shows:

toss.toSource()  is  ,#1={ref:#1#}

Of course, in this example, to resolve #1, and hence toss, it's simple enough to test toss==heads and toss==tails. This question, which is really asking if javascript has a call-by-name mechanism, motivates consideration of the counterpart, is there a call-by-value mechanism to determine the ACTUAL value of a variable? The example demonstrates that the "values" of both heads and tails are identical, yet alert(heads==tails) is false.

The self-reference can be coerced as follows:
(avoiding the object space hunt and possible ambiguities as noted in the How to get class object's name as a string in Javascript? solution)

javascript:
function assign(n,v){ eval( n +"="+ v ); eval( n +".ref='"+ n +"'" ) }
function coinSide(){};
assign("heads", "new coinSide()");
assign("tails", "new coinSide()");
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);

to display heads or tails.

It is perhaps an anathema to the essence of Javascript's language design, as an interpreted prototyping functional language, to have such capabilities as primitives.

A final consideration:

 javascript:
     item=new Object(); refName="item"; deferAgain="refName";
     alert([deferAgain,eval(deferAgain),eval(eval(deferAgain))].join('\n'));

so, as stipulated ...

javascript:
  function bindDIV(objName){ 
    return eval( objName +'=new someObject("'+objName+'")' )
  };
  function someObject(objName){
    this.div="\n<DIV onclick='window.opener."+   /* window.opener - hiccup!! */
               objName+
             ".someFunction()'>clickable DIV</DIV>\n";
    this.someFunction=function(){alert(['my variable object name is ',objName])}
  };
  with(window.open('','test').document){         /*     see above hiccup    */
    write('<html>'+
      bindDIV('DIVobj1').div+
      bindDIV('DIV2').div+
      (alias=bindDIV('multiply')).div+
      'an aliased DIV clone'+multiply.div+
      '</html>');
    close();
  };
  void (0);

Is there a better way ... ?

"better" as in easier? Easier to program? Easier to understand? Easier as in faster execution? Or is it as in "... and now for something completely different"?

Splitting dataframe into multiple dataframes

In addition to Gusev Slava's answer, you might want to use groupby's groups:

{key: df.loc[value] for key, value in df.groupby("name").groups.items()}

This will yield a dictionary with the keys you have grouped by, pointing to the corresponding partitions. The advantage is that the keys are maintained and don't vanish in the list index.

javac: invalid target release: 1.8

Your javac is not pointing to correct java.

Check where your javac is pointing using following command -

update-alternatives --config javac

If it is not pointed to the javac you want to compile with, point it to "/JAVA8_HOME/bin/javac", or which ever java you want to compile with.

MessageBodyWriter not found for media type=application/json

Below should be in your pom.xml above other jersy/jackson dependencies. In my case it as below jersy-client dep-cy and i got MessageBodyWriter not found for media type=application/json.

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

Sql Server trigger insert values from new row into another table

try this for sql server

CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS

INSERT INTO yourDestinationTable
        (col1, col2    , col3, user_id, user_name)
    SELECT
        'a'  , default , null, user_id, user_name
        FROM inserted

go

CSS Layout - Dynamic width DIV

Or, if you know the width of the two "side" images and don't want to deal with floats:

<div class="container">
    <div class="left-panel"><img src="myleftimage" /></div>
    <div class="center-panel">Content goes here...</div>
    <div class="right-panel"><img src="myrightimage" /></div>
</div>

CSS:

.container {
    position:relative;
    padding-left:50px;
    padding-right:50px;
}

.container .left-panel {
    width: 50px;
    position:absolute;
    left:0px;
    top:0px;
}

.container .right-panel {
    width: 50px;
    position:absolute;
    right:0px;
    top:0px;
}

.container .center-panel {
    background: url('mymiddleimage');
}

Notes:

Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

The above solutions are great, but if you're using WampServer you might find setting the curl.cainfo variable in php.ini doesn't work.

I eventually found WampServer has two php.ini files:

C:\wamp\bin\apache\Apachex.x.x\bin
C:\wamp\bin\php\phpx.x.xx

The first is apparently used for when PHP files are invoked through a web browser, while the second is used when a command is invoked through the command line or shell_exec().

TL;DR

If using WampServer, you must add the curl.cainfo line to both php.ini files.

Convert an image to grayscale

"I want a Bitmap d, that is grayscale. I do see a consructor that includes System.Drawing.Imaging.PixelFormat, but I don't understand how to use that."

Here is how to do this

Bitmap grayScaleBP = new 
         System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

EDIT: To convert to grayscale

             Bitmap c = new Bitmap("fromFile");
             Bitmap d;
             int x, y;

             // Loop through the images pixels to reset color.
             for (x = 0; x < c.Width; x++)
             {
                 for (y = 0; y < c.Height; y++)
                 {
                     Color pixelColor = c.GetPixel(x, y);
                     Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
                     c.SetPixel(x, y, newColor); // Now greyscale
                 }
             }
            d = c;   // d is grayscale version of c  

Faster Version from switchonthecode follow link for full analysis:

public static Bitmap MakeGrayscale3(Bitmap original)
{
   //create a blank bitmap the same size as original
   Bitmap newBitmap = new Bitmap(original.Width, original.Height);

   //get a graphics object from the new image
   using(Graphics g = Graphics.FromImage(newBitmap)){

       //create the grayscale ColorMatrix
       ColorMatrix colorMatrix = new ColorMatrix(
          new float[][] 
          {
             new float[] {.3f, .3f, .3f, 0, 0},
             new float[] {.59f, .59f, .59f, 0, 0},
             new float[] {.11f, .11f, .11f, 0, 0},
             new float[] {0, 0, 0, 1, 0},
             new float[] {0, 0, 0, 0, 1}
          });

       //create some image attributes
       using(ImageAttributes attributes = new ImageAttributes()){

           //set the color matrix attribute
           attributes.SetColorMatrix(colorMatrix);

           //draw the original image on the new image
           //using the grayscale color matrix
           g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                       0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
       }
   }
   return newBitmap;
}

Directory.GetFiles: how to get only filename, not full path?

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

It means that the standard now defines multi-threading, and it defines what happens in the context of multiple threads. Of course, people used varying implementations, but that's like asking why we should have a std::string when we could all be using a home-rolled string class.

When you're talking about POSIX threads or Windows threads, then this is a bit of an illusion as actually you're talking about x86 threads, as it's a hardware function to run concurrently. The C++0x memory model makes guarantees, whether you're on x86, or ARM, or MIPS, or anything else you can come up with.

How to use CMAKE_INSTALL_PREFIX

There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

How to see JavaDoc in IntelliJ IDEA?

IntelliJ IDEA 15 added this feature

Now it is available as EAP.

As you can see in the picture below, the caret position doesn't influence the cursor position: enter image description here

This feature was implemented in IntelliJ IDEA 15 142.4675.3 Release Notes.

How to see data from .RData file?

It sounds like the only varaible stored in the .RData file was one named isfar.

Are you really sure that you saved the table? The command should have been:

save(the_table, file = "isfar.RData")

There are many ways to examine a variable.

Type it's name at the command prompt to see it printed. Then look at str, ls.str, summary, View and unclass.

How do you tell if a checkbox is selected in Selenium for Java?

The mechanism of selenium framework:

Here selenium make request to the its server and fetch first subelement with tagname input

WebElement e = e.findElement(By.tagName("input"));

Than you try to receive attribute on that element

object attribute = e.getAttribute("checked")

So either use

findElement(By.attribute("checked")

or use

findElement(By.xpath("\\input[@checked='true']")

P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.

How to reload or re-render the entire page using AngularJS

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();

How to show imageView full screen on imageView click?

use following property of ImageView for full size of image

 android:scaleType="fitXY"

ex :

      <ImageView
        android:id="@+id/tVHeader2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:gravity="center"
        android:src="@drawable/done_sunheading" />

1)Switch on other activity when click on image.

2)pass url in intent

3)Take imageview on that Activity and set above property of imageview

4)Get the url from intent and set that image.

but using this your image may be starched if it will of small size.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This happened to me when deleting some Equinox package from my plugins directory, make sure this is not the case.

Regular Expression for matching parentheses

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

jQuery loop over JSON result from AJAX Success?

If you use Fire Fox, just open up a console (use F12 key) and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

Finding all the subsets of a set

Here's some pseudocode. You can cut same recursive calls by storing the values for each call as you go and before recursive call checking if the call value is already present.

The following algorithm will have all the subsets excluding the empty set.

list * subsets(string s, list * v){
    if(s.length() == 1){
        list.add(s);    
        return v;
    }
    else
    {
        list * temp = subsets(s[1 to length-1], v);     
        int length = temp->size();

        for(int i=0;i<length;i++){
            temp.add(s[0]+temp[i]);
        }

        list.add(s[0]);
        return temp;
    }
}

How do I pass data to Angular routed components?

3rd approach is most common way to share data between components. you may inject the item service which you want to use in related component.

import { Injectable } from '@angular/core';
import { Predicate } from '../interfaces'

import * as _ from 'lodash';

@Injectable()
export class ItemsService {

    constructor() { }


    removeItemFromArray<T>(array: Array<T>, item: any) {
        _.remove(array, function (current) {
            //console.log(current);
            return JSON.stringify(current) === JSON.stringify(item);
        });
    }

    removeItems<T>(array: Array<T>, predicate: Predicate<T>) {
        _.remove(array, predicate);
    }

    setItem<T>(array: Array<T>, predicate: Predicate<T>, item: T) {
        var _oldItem = _.find(array, predicate);
        if(_oldItem){
            var index = _.indexOf(array, _oldItem);
            array.splice(index, 1, item);
        } else {
            array.push(item);
        }
    }


    addItemToStart<T>(array: Array<T>, item: any) {
        array.splice(0, 0, item);
    }


    getPropertyValues<T, R>(array: Array<T>, property : string) : R
    {
        var result = _.map(array, property);
        return <R><any>result;
    }

    getSerialized<T>(arg: any): T {
        return <T>JSON.parse(JSON.stringify(arg));
    }
}



export interface Predicate<T> {
    (item: T): boolean
}

SQL Server 2008: How to query all databases sizes?

Not to steal your answer and adapt it for points or anything, but here is another factorization:

select d.name, 
    sum(m0.size*8.0/1024) data_file_size_mb, 
    sum(m1.size*8.0/1024) log_file_size_mb 
from sys.databases d
inner join sys.master_files m0 on m0.database_id = d.database_id
inner join sys.master_files m1 on m1.database_id = d.database_id
where m0.type = 0 and m1.type = 1
group by d.name, d.database_id
order by d.database_id

How to pass Multiple Parameters from ajax call to MVC Controller

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "ChnagePassword.aspx/AutocompleteSuggestions",
  data: "{'searchstring':'" + request.term + "','st':'Arb'}",
  dataType: "json",
  success: function (data) {
     response($.map(data.d, function (item) {
         return { value: item }
     }))
  },
  error: function (result) {
      alert("Error");
  }
});

Get Android Phone Model programmatically

Build.DEVICE // The name of the industrial design.

Build.DEVICE Gives the human readable name for some devices than Build.MODEL

Build.DEVICE = OnePlus6
Build.MANUFACTURER = OnePlus
Build.MODEL = ONEPLUS A6003

How to Remove the last char of String in C#?

If this is something you need to do a lot in your application, or you need to chain different calls, you can create an extension method:

public static String TrimEnd(this String str, int count)
{
    return str.Substring(0, str.Length - count);
}

and call it:

string oldString = "...Hello!";
string newString = oldString.Trim(1); //returns "...Hello"

or chained:

string newString = oldString.Substring(3).Trim(1);  //returns "Hello"

UICollectionView Set number of columns

Expanding on noob's answer:

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let totalSpace = flowLayout.sectionInset.left
            + flowLayout.sectionInset.right
            + (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
        let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
        return CGSize(width: size, height: size)
}

This allows for any spacing between the cells. It assumes an Int member variable called numberOfItemsPerRow and also that all the cells are square and the same size. As noted in jhilgert00's answer we must also react to orientation changes, but now by using viewWillTransitionToSize as willRotateToInterfaceOrientation is depreciated.

Set height of <div> = to height of another <div> through .css

If you don't care for IE6 and IE7 users, simply use display: table-cell for your divs:

demo

Note the use of wrapper with display: table.

For IE6/IE7 users - if you have them - you'll probably need to fallback to Javascript.

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

How to output only captured groups with sed?

Give up and use Perl

Since sed does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep GNU extensions are not :-)

  • Print the entire matching part, no matching groups or lookbehind needed:

    cat <<EOS | perl -lane 'print m/\d+/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    12
    3456
    
  • Single match per line, often structured data fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
    a1 b2
    a34 b56
    EOS
    

    Output:

    1
    34
    

    With lookbehind:

    cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
    a1 b2
    a34 b56
    EOS
    
  • Multiple fields:

    cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
    a1 c0 b2 c0
    a34 c0 b56 c0
    EOS
    

    Output:

    1 2
    34 56
    
  • Multiple matches per line, often unstructured data:

    cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1 
    34 78
    

    With lookbehind:

    cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
    a1 b2
    a34 b56 a78 b90
    EOS
    

    Output:

    1
    3478
    

psql: command not found Mac

Open the file .bash_profile in your Home folder. It is a hidden file.

Add this path below to the end export PATH line in you .bash_profile file :/Applications/Postgres.app/Contents/Versions/latest/bin

The symbol : separates the paths.

Example:

If the file contains: export PATH=/usr/bin:/bin:/usr/sbin:/sbin

it will become: export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/latest/bin

How to show hidden files

In Terminal, paste the following: defaults write com.apple.finder AppleShowAllFiles YES

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

http://example.com

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

MessageBox Buttons?

This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
            if (d == DialogResult.Yes)
            {
                //Contents
            }
            else if (d == DialogResult.No)
            {
                //Contents
            }

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

Add data dynamically to an Array

Adding array elements dynamically to an Array And adding new element to an Array

$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
        $arr['feeds'][$count]['feed_id'] = $row->feed_id;
        $arr['feeds'][$count]['feed_title'] = $row->feed_title;
        $arr['feeds'][$count]['feed_url'] = $row->feed_url;
        $arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
        foreach ($newelt as $cat) {
            array_push($samplearr, $cat);              
        }
        ++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING

$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);

Reminder - \r\n or \n\r?

\r\n for Windows will do just fine.

Writing an mp4 video using python opencv

just change the codec to "DIVX". This codec works with all formats.

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

i hope this works for you!

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

How can I easily view the contents of a datatable or dataview in the immediate window

What I do is have a static class with the following code in my project:

    #region Dataset -> Immediate Window
public static void printTbl(DataSet myDataset)
{
    printTbl(myDataset.Tables[0]);
}
public static void printTbl(DataTable mytable)
{
    for (int i = 0; i < mytable.Columns.Count; i++)
    {
        Debug.Write(mytable.Columns[i].ToString() + " | ");
    }
    Debug.Write(Environment.NewLine + "=======" + Environment.NewLine);
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
    {
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
        {
            Debug.Write(mytable.Rows[rrr][ccc] + " | ");
        }
        Debug.Write(Environment.NewLine);
    }
}
public static void ResponsePrintTbl(DataTable mytable)
{
    for (int i = 0; i < mytable.Columns.Count; i++)
    {
        HttpContext.Current.Response.Write(mytable.Columns[i].ToString() + " | ");
    }
    HttpContext.Current.Response.Write("<BR>" + "=======" + "<BR>");
    for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
    {
        for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
        {
            HttpContext.Current.Response.Write(mytable.Rows[rrr][ccc] + " | ");
        }
        HttpContext.Current.Response.Write("<BR>");
    }
}

public static void printTblRow(DataSet myDataset, int RowNum)
{
    printTblRow(myDataset.Tables[0], RowNum);
}
public static void printTblRow(DataTable mytable, int RowNum)
{
    for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
    {
        Debug.Write(mytable.Columns[ccc].ToString() + " : ");
        Debug.Write(mytable.Rows[RowNum][ccc]);
        Debug.Write(Environment.NewLine);
    }
}
#endregion

I then I will call one of the above functions in the immediate window and the results will appear there as well. For example if I want to see the contents of a variable 'myDataset' I will call printTbl(myDataset). After hitting enter, the results will be printed to the immediate window

How to create Windows EventLog source from command line?

Or just use the command line command:

Eventcreate

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

Where does System.Diagnostics.Debug.Write output appear?

While debugging System.Diagnostics.Debug.WriteLine will display in the output window (Ctrl+Alt+O), you can also add a TraceListener to the Debug.Listeners collection to specify Debug.WriteLine calls to output in other locations.

Note: Debug.WriteLine calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu Tools ? Options ? Debugging ? General. To display "Tools ? Options ? Debugging", check the box next to "Tools ? Options ? Show All Settings".

Spring boot: Unable to start embedded Tomcat servlet container

For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Convert NSArray to NSString in Objective-C

I recently found a really good tutorial on Objective-C Strings:

http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/

And I thought that this might be of interest:

If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:

NSString *yourString = @"This is a test string";
    NSArray *yourWords = [myString componentsSeparatedByString:@" "];

    // yourWords is now: [@"This", @"is", @"a", @"test", @"string"]

if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:

NSString *yourString = @"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
                  [NSCharacterSet characterSetWithCharactersInString:@"-/"]
                ];

// yourWords is now: [@"Foo", @"bar", @"iOS", @"Blog"]

Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

python: how to send mail with TO, CC and BCC?

You can try MIMEText

msg = MIMEText('text')
msg['to'] = 
msg['cc'] = 

then send msg.as_string()

https://docs.python.org/3.6/library/email.examples.html

ValueError: Wrong number of items passed - Meaning and suggestions?

for i in range(100):
try:
  #Your code here
  break
except:
  continue

This one worked for me.

Compile to a stand-alone executable (.exe) in Visual Studio

If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.

There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).

In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.

Hope it helps!

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

Java compile error: "reached end of file while parsing }"

You need to enclose your class in { and }. A few extra pointers: According to the Java coding conventions, you should

  • Put your { on the same line as the method declaration:
  • Name your classes using CamelCase (with initial capital letter)
  • Name your methods using camelCase (with small initial letter)

Here's how I would write it:

public class ModMyMod extends BaseMod {

    public String version() {
         return "1.2_02";
    }

    public void addRecipes(CraftingManager recipes) {
       recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
          "#", Character.valueOf('#'), Block.dirt
       });
    }
}

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Bootstrap $('#myModal').modal('show') is not working

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>

the first googleapis script is not working now a days use this second scripe given by jquery

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

How to clear the entire array?

For deleting a dynamic array in VBA use the instruction Erase.

Example:

Dim ArrayDin() As Integer    
ReDim ArrayDin(10)    'Dynamic allocation 
Erase ArrayDin        'Erasing the Array   

Hope this help!

CSS/HTML: Create a glowing border around an Input Field

Use a normal blue border, a medium border-radius, and a blue box-shadow with position 0 0.

Capture HTML Canvas as gif/jpg/png/pdf?

function exportCanvasAsPNG(id, fileName) {

    var canvasElement = document.getElementById(id);

    var MIME_TYPE = "image/png";

    var imgURL = canvasElement.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
}

How To Run PHP From Windows Command Line in WAMPServer

If you want to just run a quick code snippet you can use the -r option:

php -r "echo 'hi';"

-r allows to run code without using script tags <?..?>

Remove Style on Element

You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).

var element = document.getElementById('sample_id');

element.style.width = null;
element.style.height = null;

For more information, you can refer to HTMLElement.style documentation on MDN.

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

i think that is what you want.

SELECT 
      A.SalesOrderID, 
      A.OrderDate, 
      FooFromB.*

FROM A,
     (SELECT TOP 1 B.Foo
      FROM B
      WHERE A.SalesOrderID = B.SalesOrderID
      ) AS FooFromB

WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

Need a query that returns every field that contains a specified letter

There's most likely a more elegant way, but this does find every record with a letter in it, both upper or lower case:

select * from your_table
where UPPER(your_field) like '%A%'
or UPPER(your_field) like '%B%'
or UPPER(your_field) like '%C%'
or UPPER(your_field) like '%D%'
or UPPER(your_field) like '%E%'
or UPPER(your_field) like '%F%'
or UPPER(your_field) like '%G%'
or UPPER(your_field) like '%H%'
or UPPER(your_field) like '%I%'
or UPPER(your_field) like '%J%'
or UPPER(your_field) like '%K%'
or UPPER(your_field) like '%L%'
or UPPER(your_field) like '%M%'
or UPPER(your_field) like '%N%'
or UPPER(your_field) like '%O%'
or UPPER(your_field) like '%P%'
or UPPER(your_field) like '%Q%'
or UPPER(your_field) like '%R%'
or UPPER(your_field) like '%S%'
or UPPER(your_field) like '%T%'
or UPPER(your_field) like '%U%'
or UPPER(your_field) like '%V%'
or UPPER(your_field) like '%W%'
or UPPER(your_field) like '%X%'
or UPPER(your_field) like '%Y%'
or UPPER(your_field) like '%Z%'

What's the difference between session.persist() and session.save() in Hibernate?

I did some mock testing to record the difference between save() and persist().

Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.

For the below example, take EmployeeVehicle as an Entity with PK as vehicleId which is a generated value and vehicleName as one of its properties.

Example 1 : Dealing with Transient Object

Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = new EmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();

Result:

select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)

Note the result is same when you get an already persisted object and save it

EmployeeVehicle entity =  (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
entity.setVehicleName("Toyota");
session.save(entity);    -------> **instead of session.update(entity);**
// session.persist(entity);

Repeat the same using persist(entity) and will result the same with new Id ( say 37 , honda ) ;

Example 2 : Dealing with Detached Object

// Session 1 
// Get the previously saved Vehicle Entity 
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();

// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it 
// (i) Using Save() to persist a detached object 
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();

Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"

select nextval ('hibernate_sequence')
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)

Using persist to persist detached entity

// (ii) Using Persist()  to persist a detached
// Session 1 
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();

// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it 
// (i) Using Save() to persist a detached
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();

Result:

Exception being thrown : detached entity passed to persist

So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with Transient object .

Important Note : In the above example , the pk of vehicle entity is a generated value , so when using save() to persist a detached entity , hibernate generates a new id to persist . However if this pk is not a generated value than it is result in a exception stating key violated.

How do I install command line MySQL client on mac?

For installing mysql-shell with homebrew, run

brew cask install mysql-shell

you can then launch the mysql shell with

mysqlsh

if you want to enter SQL mode directly, run

mysqlsh --sql

how do I change text in a label with swift?

swift solution

yourlabel.text = yourvariable

or self is use for when you are in async {brackets} or in some Extension

DispatchQueue.main.async{
    self.yourlabel.text = "typestring"
}

How to set HttpResponse timeout for Android in Java

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}

Remove the last line from a file in Bash

Here is a solution using sponge (from the moreutils package):

head -n -1 foo.txt | sponge foo.txt

Summary of solutions:

  1. If you want a fast solution for large files, use the efficient tail or dd approach.

  2. If you want something easy to extend/tweak and portable, use the redirect and move approach.

  3. If you want something easy to extend/tweak, the file is not too large, portability (i.e., depending on moreutils package) is not an issue, and you are a fan of square pants, consider the sponge approach.

A nice benefit of the sponge approach, compared to "redirect and move" approaches, is that sponge preserves file permissions.

Sponge uses considerably more RAM compared to the "redirect and move" approach. This gains a bit of speed (only about 20%), but if you're interested in speed the "efficient tail" and dd approaches are the way to go.

Centering in CSS Grid

Try using flex:

Plunker demo : https://plnkr.co/edit/nk02ojKuXD2tAqZiWvf9

/* Styles go here */

html,
body {
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 100vh;
  grid-gap: 0px 0px;
}

.left_bg {
  background-color: #3498db;
  grid-column: 1 / 1;
  grid-row: 1 / 1;
  z-index: 0;
  display: flex;
  justify-content: center;
  align-items: center;

}

.right_bg {
  background-color: #ecf0f1;
  grid-column: 2 / 2;
  grid_row: 1 / 1;
  z-index: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.text {
  font-family: Raleway;
  font-size: large;
  text-align: center;
}

HTML

    <div class="container">
  <!--everything on the page-->

  <div class="left_bg">
    <!--left background color of the page-->
    <div class="text">
      <!--left side text content-->
      <p>Review my stuff</p>
    </div>
  </div>

  <div class="right_bg">
    <!--right background color of the page-->
    <div class="text">
      <!--right side text content-->
      <p>Hire me!</p>
    </div>
  </div>
</div>

How to declare and display a variable in Oracle

Make sure that, server output is on otherwise output will not be display;

sql> set serveroutput on;

declare
  n number(10):=1;
begin
  while n<=10
 loop
   dbms_output.put_line(n);
   n:=n+1;
 end loop;
end;
/

Outout: 1 2 3 4 5 6 7 8 9 10

Find if a String is present in an array

Use Arrays.asList() to wrap the array in a List<String>, which does have a contains() method:

Arrays.asList(dan).contains(say.getText())

Can you set a border opacity in CSS?

It's easy, use a solid shadow with 0 offset:

#foo {
  border-radius: 1px;
  box-shadow: 0px 0px 0px 8px rgba(0,0,0,0.3);       
}

Also, if you set a border-radius to the element, it gives you pretty rounded borders

jsFiddle Demo

enter image description here

Installing SciPy and NumPy using pip

This worked for me on Ubuntu 14.04:

sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran
pip install scipy

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

How to test android apps in a real device with Android Studio?

I have a Nexus 4 and own a Thinkpad L430 Windows 8.1

My errors: "Waiting for device. USB device not found"

I went to: Device Manager > View > Drop to "Acer Device" > Right click on Acer Composite ADB Interface > Update it

Afterward, Reboot/Restart your computer. Once it turned on Plug Your USB Device onto the computer.

Go to: Setting > Enable "Developer options" > Check the "USB debugging" option > Check "Allow mock locations" > Check "Verify apps over USB".

Swipe down from the drop down menu of your phone where it Shows the USB Connection Icon. Tap on USB Computer Connection > Select the Check box "Camera (PTP)"

Run your Android Studio App and it should work

Using array map to filter results with if conditional

You're looking for the .filter() function:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

How to download a file from a URL in C#?

Below code contain logic for download file with original name

private string DownloadFile(string url)
    {

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        string filename = "";
        string destinationpath = Environment;
        if (!Directory.Exists(destinationpath))
        {
            Directory.CreateDirectory(destinationpath);
        }
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
        {
            string path = response.Headers["Content-Disposition"];
            if (string.IsNullOrWhiteSpace(path))
            {
                var uri = new Uri(url);
                filename = Path.GetFileName(uri.LocalPath);
            }
            else
            {
                ContentDisposition contentDisposition = new ContentDisposition(path);
                filename = contentDisposition.FileName;

            }

            var responseStream = response.GetResponseStream();
            using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
            {
                responseStream.CopyTo(fileStream);
            }
        }

        return Path.Combine(destinationpath, filename);
    }

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

Sorry, it is a reponse to an old thread, but might still be usefull.

In addition to above reponses, This genrally happens when two columns with same name, even from different tables are included in the same query. for example if we joining two tables city and state where tables have column name e.g. city.name and state.name. when such a query is added to the dataset, ssrs removes the table name or the table alias and only keeps the name, whih eventually appears twice in the query and errors as duplicate key. The best way to avoid it is to use alias such as calling the column names city.name as c_name state.name as s_name. This will resolve the issue.

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

How to read data from a zip file without having to unzip the entire file

Something like this will list and extract the files one by one, if you want to use SharpZipLib:

var zip = new ZipInputStream(File.OpenRead(@"C:\Users\Javi\Desktop\myzip.zip"));
var filestream = new FileStream(@"C:\Users\Javi\Desktop\myzip.zip", FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
     Console.WriteLine(item.Name);
     using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
     {
      // stream with the file
          Console.WriteLine(s.ReadToEnd());
     }
 }

Based on this example: content inside zip file

Ping site and return result in PHP

Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

Example usage:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

What are DDL and DML?

DDL: Change the schema

DML: Change the data

Seems specific to MySQL limitations (rails's source code)

Order by multiple columns with Doctrine

The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

How to use 'find' to search for files created on a specific date?

I found this scriplet in a script that deletes all files older than 14 days:

CNT=0
for i in $(find -type f -ctime +14); do
  ((CNT = CNT + 1))
  echo -n "." >> $PROGRESS
  rm -f $i
done
echo deleted $CNT files, done at $(date "+%H:%M:%S") >> $LOG

I think a little additional "man find" and looking for the -ctime / -atime etc. parameters will help you here.

Is it possible to refresh a single UITableViewCell in a UITableView?

reloadRowsAtIndexPaths: is fine, but still will force UITableViewDelegate methods to fire.

The simplest approach I can imagine is:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];

It's important to invoke your configureCell: implementation on main thread, as it wont work on non-UI thread (the same story with reloadData/reloadRowsAtIndexPaths:). Sometimes it might be helpful to add:

dispatch_async(dispatch_get_main_queue(), ^
{
    [self configureCell:cell forIndexPath:indexPath];
});

It's also worth to avoid work that would be done outside of the currently visible view:

BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
    ....
}

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 });

//Or

using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
}

//Or

using(var context = new MyDataContext())
{
object[] parameters =  { param1, param2, param3 };

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
parameters).ToList();
}

//Or

using(var context = new MyDataContext())
{  
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
param1, param2, param3).ToList();
}

Trim last character from a string

In .NET 5 / C# 8:

You can write the code marked as the answer as:

public static class StringExtensions
{
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}

However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

A quick explanation for the new stuff in C# 8:

The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

An addition to the other answers concerning object comparison:

== compares objects using the name of the object and their values. If two objects are of the same type and have the same member values, $a == $b yields true.

=== compares the internal object id of the objects. Even if the members are equal, $a !== $b if they are not exactly the same object.

class TestClassA {
    public $a;
}

class TestClassB {
    public $a;
}

$a1 = new TestClassA();
$a2 = new TestClassA();
$b = new TestClassB();

$a1->a = 10;
$a2->a = 10;
$b->a = 10;

$a1 == $a1;
$a1 == $a2;  // Same members
$a1 != $b;   // Different classes

$a1 === $a1;
$a1 !== $a2; // Not the same object

How to access parameters in a Parameterized Build?

I tried a few of the solutions from this thread. It seemed to work, but my values were always true and I also encountered the following issue: JENKINS-40235

I managed to use parameters in groovy jenkinsfile using the following syntax: params.myVariable

Here's a working example:

Solution

print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"

A more detailed (and working) example:

node() {
   // adds job parameters within jenkinsfile
   properties([
     parameters([
       booleanParam(
         defaultValue: false,
         description: 'isFoo should be false',
         name: 'isFoo'
       ),
       booleanParam(
         defaultValue: true,
         description: 'isBar should be true',
         name: 'isBar'
       ),
     ])
   ])

   // test the false value
   print 'DEBUG: parameter isFoo = ' + params.isFoo
   print "DEBUG: parameter isFoo = ${params.isFoo}"
   sh "echo sh isFoo is ${params.isFoo}"
   if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }

   // test the true value
   print 'DEBUG: parameter isBar = ' + params.isBar
   print "DEBUG: parameter isBar = ${params.isBar}"
   sh "echo sh isBar is ${params.isBar}"
   if (params.isBar) { print "this should display" }
}

Output

[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

I sent a Pull Request to update the misleading pipeline tutorial#build-parameters quote that says "they are accessible as Groovy variables of the same name.". ;)

Edit: As Jesse Glick pointed out: Release notes go into more details

You should also update the Pipeline Job Plugin to 2.7 or later, so that build parameters are defined as environment variables and thus accessible as if they were global Groovy variables.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

Do it like this:

var value = $("#text").val(); // value = 9.61 use $("#text").text() if you are not on select box...
value = value.replace(".", ":"); // value = 9:61
// can then use it as
$("#anothertext").val(value);

Updated to reflect to current version of jQuery. And also there are a lot of answers here that would best fit to any same situation as this. You, as a developer, need to know which is which.

Replace all occurrences

To replace multiple characters at a time use some thing like this: name.replace(/&/g, "-"). Here I am replacing all & chars with -. g means "global"

Note - you may need to add square brackets to avoid an error - title.replace(/[+]/g, " ")

credits vissu and Dante Cullari

How can I add numbers in a Bash script?

 #!/bin/bash
read X
read Y
echo "$(($X+$Y))"

jQuery Mobile: Stick footer to bottom of page

http://ryanfait.com/sticky-footer/

You could possibly use this and use jQuery to update the css height of the elements to make sure it stays in place.

Echo equivalent in PowerShell for script testing

It should also be mentioned, that Set-PSDebug is similar to the old-school echo on batch command:

Set-PSDebug -Trace 1

This command will result in showing every line of the executing script:

When the Trace parameter has a value of 1, each line of script is traced as it runs. When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you're prompted before each line of the script runs.

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

How does one extract each folder name from a path?

string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);

Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:

int folderCount = directories.Length;

How to pass parameters in $ajax POST?

Your code was right except you are not passing the JSON keys as strings.

It should have double or single quotes around it

{ "field1": "hello", "field2" : "hello2"}

$.ajax(
   {
      type: 'post',
      url: 'superman',
      data: { 
        "field1": "hello", // Quotes were missing
        "field2": "hello1" // Here also
      },
      success: function (response) {
        alert(response);
      },
      error: function () {
        alert("error");
      }
   }
);

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

Maximum on http header values?

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

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

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

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

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

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

Source

Regular expression to match balanced parentheses

I want to add this answer for quickreference. Feel free to update.


.NET Regex using balancing groups.

\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)

Where c is used as the depth counter.

Demo at Regexstorm.com


PCRE using a recursive pattern.

\((?:[^)(]+|(?R))*+\)

Demo at regex101; Or without alternation:

\((?:[^)(]*(?R)?)*+\)

Demo at regex101; Or unrolled for performance:

\([^)(]*+(?:(?R)[^)(]*)*+\)

Demo at regex101; The pattern is pasted at (?R) which represents (?0).

Perl, PHP, Notepad++, R: perl=TRUE, Python: Regex package with (?V1) for Perl behaviour.


Ruby using subexpression calls.

With Ruby 2.0 \g<0> can be used to call full pattern.

\((?>[^)(]+|\g<0>)*\)

Demo at Rubular; Ruby 1.9 only supports capturing group recursion:

(\((?>[^)(]+|\g<1>)*\))

Demo at Rubular  (atomic grouping since Ruby 1.9.3)


JavaScript  API :: XRegExp.matchRecursive

XRegExp.matchRecursive(str, '\\(', '\\)', 'g');

JS, Java and other regex flavors without recursion up to 2 levels of nesting:

\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)

Demo at regex101. Deeper nesting needs to be added to pattern.
To fail faster on unbalanced parenthesis drop the + quantifier.


Java: An interesting idea using forward references by @jaytea.


Reference - What does this regex mean?

Convert byte to string in Java

This is my version:

public String convertBytestoString(InputStream inputStream)
{
    int bytes;
    byte[] buffer = new byte[1024];

    bytes = inputStream.read(buffer);
    String stringData = new String(buffer,0,bytes);

    return stringData;

}

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

How do I include a pipe | in my linux find -exec command?

I found that running a string shell command (sh -c) works best, for example:

find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

How to link to a named anchor in Multimarkdown?

In mdcharm it is like this:

* [Descripción](#descripcion)
* [Funcionamiento](#funcionamiento)
* [Instalación](#instalacion)
* [Configuración](#configuracion)

### Descripción {#descripcion}
### Funcionamiento {#funcionamiento}
### Instalación {#instalacion}
### Configuración {#configuracion}

I forgot the password I entered during postgres installation

Just a note, on Linux You can simply run sudo su - postgres to become the postgres user and from there change what required using psql.

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

suppose you need a label with text customername than you can achive it using 2 ways

[1]@Html.Label("CustomerName")

[2]@Html.LabelFor(a => a.CustomerName)  //strongly typed

2nd method used a property from your model. If your view implements a model then you can use the 2nd method.

More info please visit below link

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Using cURL with a username and password?

To securely pass the password in a script (i.e. prevent it from showing up with ps auxf or logs) you can do it with the -K- flag (read config from stdin) and a heredoc:

curl --url url -K- <<< "--user user:password"

How to compare strings in sql ignoring case?

You can use:

select * from your_table where upper(your_column) like '%ANGEL%'

Otherwise, you can use:

select * from your_table where upper(your_column) = 'ANGEL'

Which will be more efficient if you are looking for a match with no additional characters before or after your_column field as Gary Ray suggested in his comments.

Link vs compile vs controller

  • compile: used when we need to modify directive template, like add new expression, append another directive inside this directive
  • controller: used when we need to share/reuse $scope data
  • link: it is a function which used when we need to attach event handler or to manipulate DOM.

Sorting a DropDownList? - C#, ASP.NET

DropDownList takes any IEnumerable as a DataSource.

Just sort it using LINQ.

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

How to change the default encoding to UTF-8 for Apache?

In .htaccess add this line:

AddCharset utf-8 .html .css .php .txt .js

This is for those that do not have access to their server's conf file. It is just one more thing to try when other attempts failed.

As far as performance issues regarding the use of .htaccess I have not seen this. My typical page load times are 150-200 mS with or without .htaccess

What good is performance if your page does not render correctly. Most shared servers do not allow user access to the config file which is the preferred place to add a character set.

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

How to remove the border highlight on an input text element

In Bootstrap 4 to remove border outline you can use shadow-none, it will remove focus outline.

            <div class="form-group">
                <label for="exampleInputEmail1">Name</label>
                <input type="text" class="form-control form-control shadow-none" 
                id="exampleInputEmail1"aria-describedby="emailHelp">
            </div>

Java: Check the date format of current string is according to required format or not

Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)

    public Boolean checkDateformat(String dateToCheck){   
        String rex="([0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})+
        \/([0]{1}[1-9]{1}|[1]{1}[0-2]{2})+
        \/([1]{1}[9]{1}[5-9]{1}[0-9]{1}|[2]{1}[0]{1}([0-4]{1}+
        [0-9]{1}|[5]{1}[0]{1}))";

        return(dateToCheck.matches(rex));
    }

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

The strategy from Wikipedia for playing a perfect game (win or tie every time) seems like straightforward pseudo-code:

Quote from Wikipedia (Tic Tac Toe#Strategy)

A player can play a perfect game of Tic-tac-toe (to win or, at least, draw) if they choose the first available move from the following list, each turn, as used in Newell and Simon's 1972 tic-tac-toe program.[6]

  1. Win: If you have two in a row, play the third to get three in a row.

  2. Block: If the opponent has two in a row, play the third to block them.

  3. Fork: Create an opportunity where you can win in two ways.

  4. Block Opponent's Fork:

    Option 1: Create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork or winning. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)

    Option 2: If there is a configuration where the opponent can fork, block that fork.

  5. Center: Play the center.

  6. Opposite Corner: If the opponent is in the corner, play the opposite corner.

  7. Empty Corner: Play an empty corner.

  8. Empty Side: Play an empty side.

Recognizing what a "fork" situation looks like could be done in a brute-force manner as suggested.

Note: A "perfect" opponent is a nice exercise but ultimately not worth 'playing' against. You could, however, alter the priorities above to give characteristic weaknesses to opponent personalities.

How to resize JLabel ImageIcon?

I agree this code works, to size an ImageIcon from a file for display while keeping the aspect ratio I have used the below.

/*
 * source File of image, maxHeight pixels of height available, maxWidth pixels of width available
 * @return an ImageIcon for adding to a label
 */


public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
{
    int newHeight = 0, newWidth = 0;        // Variables for the new height and width
    int priorHeight = 0, priorWidth = 0;
    BufferedImage image = null;
    ImageIcon sizeImage;

    try {
            image = ImageIO.read(source);        // get the image
    } catch (Exception e) {

            e.printStackTrace();
            System.out.println("Picture upload attempted & failed");
    }

    sizeImage = new ImageIcon(image);

    if(sizeImage != null)
    {
        priorHeight = sizeImage.getIconHeight(); 
        priorWidth = sizeImage.getIconWidth();
    }

    // Calculate the correct new height and width
    if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
    {
        newHeight = maxHeight;
        newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
    }
    else 
    {
        newWidth = maxWidth;
        newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
    }


    // Resize the image

    // 1. Create a new Buffered Image and Graphic2D object
    BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();

    // 2. Use the Graphic object to draw a new image to the image in the buffer
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(image, 0, 0, newWidth, newHeight, null);
    g2.dispose();

    // 3. Convert the buffered image into an ImageIcon for return
    return (new ImageIcon(resizedImg));
}

How do I set the selenium webdriver get timeout?

You can set the timeout on the HTTP Client like this

int connectionTimeout=5000;
int socketTimeout=15000;
ApacheHttpClient.Factory clientFactory = new ApacheHttpClient.Factory(new HttpClientFactory(connectionTimeout, socketTimeout));
HttpCommandExecutor executor =
      new HttpCommandExecutor(new HashMap<String, CommandInfo>(), new URL(seleniumServerUrl), clientFactory);
RemoteWebDriver driver = new RemoteWebDriver(executor, capabilities);

Python truncate a long string

info = (data[:75] + '..') if len(data) > 75 else data

JavaScript ES6 promise for loop

As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.

Secondly, each promise that is created with new Promise needs to be resolved with a call to resolve (or reject). This should be done when the timer expires. That will trigger any then callback you would have on that promise. And such a then callback (or await) is a necessity in order to implement the chain.

With those ingredients, there are several ways to perform this asynchronous chaining:

  1. With a for loop that starts with an immediately resolving promise

  2. With Array#reduce that starts with an immediately resolving promise

  3. With a function that passes itself as resolution callback

  4. With ECMAScript2017's async / await syntax

  5. With ECMAScript2020's for await...of syntax

See a snippet and comments for each of these options below.

1. With for

You can use a for loop, but you must make sure it doesn't execute new Promise synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:

_x000D_
_x000D_
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
    p = p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ));
}
_x000D_
_x000D_
_x000D_

2. With reduce

This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:

_x000D_
_x000D_
[...Array(10)].reduce( (p, _, i) => 
    p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ))
, Promise.resolve() );
_x000D_
_x000D_
_x000D_

This is probably more useful when you actually have an array with data to be used in the promises.

3. With a function passing itself as resolution-callback

Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:

_x000D_
_x000D_
(function loop(i) {
    if (i < 10) new Promise((resolve, reject) => {
        setTimeout( () => {
            console.log(i);
            resolve();
        }, Math.random() * 1000);
    }).then(loop.bind(null, i+1));
})(0);
_x000D_
_x000D_
_x000D_

This creates a function named loop, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.

The call to resolve() will trigger the then callback which will call the function again. loop.bind(null, i+1) is just a different way of saying _ => loop(i+1).

4. With async/await

Modern JS engines support this syntax:

_x000D_
_x000D_
(async function loop() {
    for (let i = 0; i < 10; i++) {
        await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

It may look strange, as it seems like the new Promise() calls are executed synchronously, but in reality the async function returns when it executes the first await. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await, until it encounters the next one, and so it continues until the loop finishes.

As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout. It may improve the readability of the code:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

(async function loop() {
    for (let i = 0; i < 10; i++) {
        await delay(Math.random() * 1000);
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

5. With for await...of

With EcmaScript 2020, the for await...of found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
    for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}

(async function loop() {
    for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
_x000D_
_x000D_

Overwriting my local branch with remote branch

What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:

git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch

Then if you're sure you don't want anything from your old branch, remove it:

git branch -D branch-old

But usually I leave the old branch around locally, just in case I had something in there.

Convert JsonNode into POJO

String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
    new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);

If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)

mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

C# convert int to string with padding zeros?

Simply

int i=123;
string paddedI = i.ToString("D4");

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

How to escape apostrophe (') in MySql?

In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.

see https://www.php.net/manual/en/mysqli.real-escape-string.php

Serving favicon.ico in ASP.NET MVC

All you need to do is to add app.UseStaticFiles(); in your startup.cs -> public void Configure(IApplicationBuilder app, IHostingEnvironment env).

ASP.net core provides an excellent way to get static files. That is using the wwwroot folder. Please read Static files in ASP.NET Core.

Using the <Link /> is not a very good idea. Why would someone add the link tag on each HTML or cshtml for the favicon.ico?

Java 8 optional: ifPresent return object orElseThrow exception

I'd prefer mapping after making sure the value is available

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

or one liner

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
    Console.ReadLine()

End Sub()

Installing Apple's Network Link Conditioner Tool

  1. Remove "Network Link Conditioner", open "System Preferences", press CTRL and click the "Network Link Conditioner" icon. Select "Remove".
  2. Restart your computer
  3. Download the dmg "Hardware IO tools" for your XCode version from https://developer.apple.com/download/, you need to be logged in to do this.
  4. Open it and install "Network Link Conditioner"
  5. Restart your computer one last time.

Automatically set appsettings.json for dev and release environments in asp.net core?

Update for .NET Core 3.0+

  1. You can use CreateDefaultBuilder which will automatically build and pass a configuration object to your startup class:

    WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    
    public class Startup
    {
        public Startup(IConfiguration configuration) // automatically injected
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        /* ... */
    }
    
  2. CreateDefaultBuilder automatically includes the appropriate appsettings.Environment.json file so add a separate appsettings file for each environment:

    appsettings.env.json

  3. Then set the ASPNETCORE_ENVIRONMENT environment variable when running / debugging

How to set Environment Variables

Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:

  • For Visual Studio go to Project > Properties > Debug > Environment Variables:

    Visual Studio - Environment Variables

  • For Visual Studio Code, edit .vscode/launch.json > env:

    Visual Studio Code > Launch Environment

  • Using Launch Settings, edit Properties/launchSettings.json > environmentVariables:

    Launch Settings

    Which can also be selected from the Toolbar in Visual Studio

    Launch Settings Dropdown

  • Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS

    Note: When an app is launched with dotnet run, launchSettings.json is read if available, and environmentVariables settings in launchSettings.json override environment variables.

How does Host.CreateDefaultBuilder work?

.NET Core 3.0 added Host.CreateDefaultBuilder under platform extensions which will provide a default initialization of IConfiguration which provides default configuration for the app in the following order:

  1. appsettings.json using the JSON configuration provider.
  2. appsettings.Environment.json using the JSON configuration provider. For example:
    • appsettings.Production.json or
    • appsettings.Development.json
  3. App secrets when the app runs in the Development environment.
  4. Environment variables using the Environment Variables configuration provider.
  5. Command-line arguments using the Command-line configuration provider.

Further Reading - MS Docs

Max value of Xmx and Xms in Eclipse?

The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).

You may want to take a look at this question: Max amount of memory per java process in Windows?

Execution failed for task ':app:processDebugResources' even with latest build tools

Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:

finished with non-zero exit value 1

One reason for this error to occure is that the file path to a resource file is to long:

Error: File path too long on Windows, keep below 240 characters 

Fix: Move your project folder closer to the root of your disk

Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...

Do://folder/short_name/MyProject


Another reason could be duplicated resources or name spaces

Example:

  <style name="MyButton" parent="android:Widget.Button">
      <item name="android:textColor">@color/accent_color</item>
      <item name="android:textColor">#000000</item>
  </style>

And make sure all file names and extensions are in lowercase

Wrong

myimage.PNG
myImage.png

Correct

my_image.png

Make sure to Clean/Rebuild project

(delete the 'build' folder)

Using BufferedReader to read Text File

private void readFile() throws Exception {
      AsynchronousFileChannel input=AsynchronousFileChannel.open(Paths.get("E:/dicom_server_storage/abc.txt"),StandardOpenOption.READ);
      ByteBuffer buffer=ByteBuffer.allocate(1024);
      input.read(buffer,0,null,new CompletionHandler<Integer,Void>(){
        @Override public void completed(    Integer result,    Void attachment){
          System.out.println("Done reading the file.");
        }
        @Override public void failed(    Throwable exc,    Void attachment){
          System.err.println("An error occured:" + exc.getMessage());
        }
      }
    );
      System.out.println("This thread keeps on running");
      Thread.sleep(100);
    }

How to pass multiple parameters from ajax to mvc controller?

function toggleCheck(employeeId) {
    var data =  'referenceid= '+ employeeId +'&referencestatus=' 1;
    console.log(data);
    $.ajax({
        type : 'POST',
        url : 'edit',
        data : data,
        cache: false,
        async : false,
        success : function(employeeId) {
            alert("Success");
            window.redirect = "Users.jsp";
        }
    });

}

How to remove all the occurrences of a char in c++ string

This code removes repetition of characters i.e, if the input is aaabbcc then the output will be abc. (the array must be sorted for this code to work)

cin >> s;
ans = "";
ans += s[0];
for(int i = 1;i < s.length();++i)
if(s[i] != s[i-1])
    ans += s[i];
cout << ans << endl;

Try catch statements in C

If you're using C with Win32, you can leverage its Structured Exception Handling (SEH) to simulate try/catch.

If you're using C in platforms that don't support setjmp() and longjmp(), have a look at this Exception Handling of pjsip library, it does provide its own implementation

Setting a checkbox as checked with Vue.js

To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.

The following code will bind the checkbox with that property:

<input type="checkbox" v-model="module.checked" v-bind:id="module.id">

Notice that I removed v-bind:value="module.id". You shouldn't use v-model and v-bind:value on the same element. From the vue docs:

<input v-model="something">

is just syntactic sugar for:

<input v-bind:value="something" v-on:input="something = $event.target.value">

So, by using v-model and v-bind:value, you actually end up having v-bind:value twice, which could lead to undefined behavior.

How do I find files that do not contain a given string pattern?

grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

above command will give us the result as -v finds the inverse of the pattern being searched

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.

Entity Framework Migrations renaming tables and columns

To expand a bit on Hossein Narimani Rad's answer, you can rename both a table and columns using System.ComponentModel.DataAnnotations.Schema.TableAttribute and System.ComponentModel.DataAnnotations.Schema.ColumnAttribute respectively.

This has a couple benefits:

  1. Not only will this create the the name migrations automatically, but
  2. it will also deliciously delete any foreign keys and recreate them against the new table and column names, giving the foreign keys and constaints proper names.
  3. All this without losing any table data

For example, adding [Table("Staffs")]:

[Table("Staffs")]
public class AccountUser
{
    public long Id { get; set; }

    public long AccountId { get; set; }

    public string ApplicationUserId { get; set; }

    public virtual Account Account { get; set; }

    public virtual ApplicationUser User { get; set; }
}

Will generate the migration:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_AccountUsers_Accounts_AccountId",
            table: "AccountUsers");

        migrationBuilder.DropForeignKey(
            name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
            table: "AccountUsers");

        migrationBuilder.DropPrimaryKey(
            name: "PK_AccountUsers",
            table: "AccountUsers");

        migrationBuilder.RenameTable(
            name: "AccountUsers",
            newName: "Staffs");

        migrationBuilder.RenameIndex(
            name: "IX_AccountUsers_ApplicationUserId",
            table: "Staffs",
            newName: "IX_Staffs_ApplicationUserId");

        migrationBuilder.RenameIndex(
            name: "IX_AccountUsers_AccountId",
            table: "Staffs",
            newName: "IX_Staffs_AccountId");

        migrationBuilder.AddPrimaryKey(
            name: "PK_Staffs",
            table: "Staffs",
            column: "Id");

        migrationBuilder.AddForeignKey(
            name: "FK_Staffs_Accounts_AccountId",
            table: "Staffs",
            column: "AccountId",
            principalTable: "Accounts",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

        migrationBuilder.AddForeignKey(
            name: "FK_Staffs_AspNetUsers_ApplicationUserId",
            table: "Staffs",
            column: "ApplicationUserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_Staffs_Accounts_AccountId",
            table: "Staffs");

        migrationBuilder.DropForeignKey(
            name: "FK_Staffs_AspNetUsers_ApplicationUserId",
            table: "Staffs");

        migrationBuilder.DropPrimaryKey(
            name: "PK_Staffs",
            table: "Staffs");

        migrationBuilder.RenameTable(
            name: "Staffs",
            newName: "AccountUsers");

        migrationBuilder.RenameIndex(
            name: "IX_Staffs_ApplicationUserId",
            table: "AccountUsers",
            newName: "IX_AccountUsers_ApplicationUserId");

        migrationBuilder.RenameIndex(
            name: "IX_Staffs_AccountId",
            table: "AccountUsers",
            newName: "IX_AccountUsers_AccountId");

        migrationBuilder.AddPrimaryKey(
            name: "PK_AccountUsers",
            table: "AccountUsers",
            column: "Id");

        migrationBuilder.AddForeignKey(
            name: "FK_AccountUsers_Accounts_AccountId",
            table: "AccountUsers",
            column: "AccountId",
            principalTable: "Accounts",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

        migrationBuilder.AddForeignKey(
            name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
            table: "AccountUsers",
            column: "ApplicationUserId",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    }

Convert string to variable name in JavaScript

If it's a global variable then window[variableName] or in your case window["onlyVideo"] should do the trick.

.NET NewtonSoft JSON deserialize map to a different property name

Json.NET has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:

public class TeamScore
{
    [JsonProperty("eighty_min_score")]
    public string EightyMinScore { get; set; }
    [JsonProperty("home_or_away")]
    public string HomeOrAway { get; set; }
    [JsonProperty("score ")]
    public string Score { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    [JsonProperty("attributes")]
    public TeamScore TeamScores { get; set; }
}

public class RootObject
{
    public List<Team> Team { get; set; }
}

Documentation: Serialization Attributes

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

What do raw.githubusercontent.com URLs represent?

The raw.githubusercontent.com domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.

The URL in your question references the install file in the master branch of the Homebrew/install repository. The rest of that command just retrieves the file and runs ruby on its contents.

Convert RGB to Black & White in OpenCV

A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++

cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); 
cv::Mat bw = img > 128;

In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black

Optionally, and for me gave good results is to apply blur

cv::blur( bw, bw, cv::Size(3,3) );

Later you can save it as said before with:

cv::imwrite("image_bw.jpg", bw);

Close/kill the session when the browser or tab is closed

It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.