Programs & Examples On #Find by sql

Executes a custom SQL query against your database and returns all the results. The results will be returned as an array with columns requested encapsulated as attributes of the model you call this method from.

How to Customize a Progress Bar In Android

If you want to do this in code, here is a sample:

pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();

Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.

Count rows with not empty value

In Google Sheets, to count the number of rows which contain at least one non-empty cell within a two-dimensional range:

=ARRAYFORMULA(
  SUM(
    N(
      MMULT(
        N(A1:C5<>""),
        TRANSPOSE(COLUMN(A1:C5)^0)
      )
      >0
    )
  )
)

Where A1:C5 is the range you're checking for non-empty rows.

The formula comes from, and is explained in the following article from EXCELXOR - https://excelxor.com/2015/03/30/counting-rows-where-at-least-one-condition-is-met/

How to include js and CSS in JSP with spring MVC

You cant directly access anything under the WEB-INF foldere. When browsers request your CSS file, they can not see inside the WEB-INF folder.

Try putting your files css/css folder under WebContent.

And add the following in dispatcher servlet to grant access ,

<mvc:resources mapping="/css/**" location="/css/" />

similarly for your js files . A Nice example here on this

Method to find string inside of the text file. Then getting the following lines up to a certain limit

When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?

Scanner scanner = new Scanner("Student.txt");
String currentLine;

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Perform logic
    }
}

You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:

Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

Things possible in IntelliJ that aren't possible in Eclipse?

Idea 8.0 has the lovely ctrl+shift+space x 2 that does the following autocomplete:

 City city = customer.<ctrl-shift-space twice>

resolves to

 City city = customer.getAddress().getCity();

through any number of levels of getters/setters.

How to convert dataframe into time series?

Late to the party, but the tsbox package is designed to perform conversions like this. To convert your data into a ts-object, you can do:

dta <- data.frame(
  Dates = c("3/14/2013", "3/15/2013", "3/18/2013", "3/19/2013"),
  Bajaj_close = c(1854.8, 1850.3, 1812.1, 1835.9),
  Hero_close = c(1669.1, 1684.45, 1690.5, 1645.6)
)

dta
#>       Dates Bajaj_close Hero_close
#> 1 3/14/2013      1854.8    1669.10
#> 2 3/15/2013      1850.3    1684.45
#> 3 3/18/2013      1812.1    1690.50
#> 4 3/19/2013      1835.9    1645.60

library(tsbox)
ts_ts(ts_long(dta))
#> Time Series:
#> Start = 2013.1971293045 
#> End = 2013.21081883954 
#> Frequency = 365.2425 
#>          Bajaj_close Hero_close
#> 2013.197      1854.8    1669.10
#> 2013.200      1850.3    1684.45
#> 2013.203          NA         NA
#> 2013.205          NA         NA
#> 2013.208      1812.1    1690.50
#> 2013.211      1835.9    1645.60

It automatically parses the dates, detects the frequency and makes the missing values at the weekends explicit. With ts_<class>, you can convert the data to any other time series class.

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

Its should work for all version of eclipse even in Spring tool suit(STS). Here is the steps

Go to the URl Follow The link to download or click the bellow link to direct download Click Here to download

Download JD-Eclipse. Download and unzip the JD-Eclipse Update Site,

Launch Eclipse,

Click on "Help > Install New Software...",

Click on button "Add..." to add an new repository,

Enter "JD-Eclipse Update Site" and select the local site directory,

enter image description here

Select extracted folder and give any name. I have given JDA. and click ok.

enter image description here

Check "Java Decompiler Eclipse Plug-in",

enter image description here

Next, next, next... and restart Eclipse.

Is JavaScript object-oriented?

JavaScript is a prototype-based programming language (probably prototype-based scripting language is more correct definition). It employs cloning and not inheritance. A prototype-based programming language is a style of object-oriented programming without classes. While object-oriented programming languages encourages development focus on taxonomy and relationships, prototype-based programming languages encourages to focus on behavior first and then later classify.

The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean

only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. (source)

In object-oriented programming, each object is capable of receiving messages, processing data, and sending messages to other objects.

For a language to be object-oriented in may include features as encapsulation, modularity, polymorphism, and inheritance, but it is not a requirement. Object-oriented programming languages that make use of classes are often referred to as classed-based programming languages, but it is by no means a must to make use of classes to be object-oriented.

JavaScript uses prototypes to define object properties, including methods and inheritance.

Conclusion: JavaScript IS object-oriented.

How do I export a project in the Android studio?

1.- Export signed packages:

  • Use the Extract a Signed Android Application Package Wizard (On the main menu, choose Build | Generate Signed APK). The package will be signed during extraction.

    OR

  • Configure the .apk file as an artifact by creating an artifact definition of the type Android application with the Release signed package mode.

2.- Export unsigned packages: this can only be done through artifact definitions with the Debug or Release unsigned package mode specified.

Changing the default icon in a Windows Forms application

select Main form -> properties -> Windows style -> icon -> browse your ico

this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

What does the term "Tuple" Mean in Relational Databases?

Tuple is used to refer to a row in a relational database model. But tuple has little bit difference with row.

How do I divide so I get a decimal value?

quotient = 3 / 2;
remainder = 3 % 2;

// now you have them both

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Delaying function in swift

Swift 3 and Above Version(s) for a delay of 10 seconds

    DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
        self.functionToCall()
    }

Conda: Installing / upgrading directly from github

The answers are outdated. You simply have to conda install pip and git. Then you can use pip normally:

  1. Activate your conda environment source activate myenv

  2. conda install git pip

  3. pip install git+git://github.com/scrappy/scrappy@master

Regular expression to match standard 10 digit phone number

How about this?

^(\+?[01])?[-.\s]?\(?[1-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}

EDIT: I forgot about the () one. EDIT 2: Got the first 3 digit part wrong.

How to execute shell command in Javascript

This depends entirely on the JavaScript environment. Please elaborate.

For example, in Windows Scripting, you do things like:

var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");

Difficulty with ng-model, ng-repeat, and inputs

This seems to be a binding issue.

The advice is don't bind to primitives.

Your ngRepeat is iterating over strings inside a collection, when it should be iterating over objects. To fix your problem

<body ng-init="models = [{name:'Sam'},{name:'Harry'},{name:'Sally'}]">
    <h1>Fun with Fields and ngModel</h1>
    <p>names: {{models}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="model in models">
        Value: {{model.name}}
        <input ng-model="model.name">                         
    </div>

jsfiddle: http://jsfiddle.net/jaimem/rnw3u/5/

How to add text to a WPF Label in code?

Label myLabel = new Label (); myLabel.Content = "Hello World!";

Trusting all certificates using HttpClient over HTTPS

Trusting all certificates was no real alternative for me, so I did the following to get HttpsURLConnection to trust a new certificate (see also http://nelenkov.blogspot.jp/2011/12/using-custom-certificate-trust-store-on.html).

  1. Get the certificate; I got this done by exporting the certificate in Firefox (click on the little lock icon, get certificate details, click export), then used portecle to export a truststore (BKS).

  2. Load the Truststore from /res/raw/geotrust_cert.bks with the following code:

        final KeyStore trustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(
                R.raw.geotrust_cert);
        trustStore.load(in, null);
    
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
    
        final SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(null, tmf.getTrustManagers(),
                new java.security.SecureRandom());
    
        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx
                .getSocketFactory());
    

How to post a file from a form with Axios

How to post file using an object in memory (like a JSON object):

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

Change the class from factor to numeric of many columns in a data frame

df$colname <- as.numeric(df$colname)

I tried this way for changing one column type and I think it is better than many other versions, if you are not going to change all column types

df$colname <- as.character(df$colname)

for the vice versa.

Amazon S3 - HTTPS/SSL - Is it possible?

This is a response I got from their Premium Services

Hello,

This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:

http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html

The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with

https://furniture-retailcatalog-us.s3.amazonaws.com/

You could, of course, put a CNAME DNS record to make that more friendly. For example,

images-furniture.retailcatalog.us IN CNAME furniture-retailcatalog-us.s3.amazonaws.com.

Hope that helps. Let us know if you have any other questions.

Amazon Web Services

Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.


UPDATE 10/2/2012

From @mpoisot:

The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page: http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html


UPDATE 6/17/2013

From @Joseph Lust:

Just got it! Check it out and sign up for an invite: http://aws.amazon.com/cloudfront/custom-ssl-domains

Javascript return number of days,hours,minutes,seconds between two dates

We can do it by simple method

_x000D_
_x000D_
/*Declare the function */
function Clock(){
    let d1 = new Date("1 Jan 2021");
    let d2 = new Date();

    let difference = Math.abs(d1 - d2); //to get absolute value
    //calculate for each one
    let Days = Math.floor(difference / ( 1000 * 60 * 60 * 24 ));
    let Hours = Math.floor((difference / ( 1000 * 60 * 60 )) % 24);
    let Mins = Math.floor((difference / ( 1000 * 60 )) % 60);
    let Seconds = Math.floor((difference / ( 1000 )) % 60);

    //getting nodes and change the text inside
    let getday = document.querySelector(".big_text_days");
    let gethour = document.querySelector(".big_text_hours");
    let getmins = document.querySelector(".big_text_mins");
    let getsec = document.querySelector(".big_text_sec");

    getday.textContent = Check_Zero(Days); 
    gethour.textContent = Check_Zero(Hours);
    getmins.textContent = Check_Zero(Mins)
    getsec.textContent = Check_Zero(Seconds);
}

//call the funcion for every 1 second
setInterval(Clock , 1000);


//check and add zero in front, if it is lessthan 10
function Check_Zero(mytime){
    return mytime < 10 ? "0"+mytime : mytime;

}
_x000D_
*{
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
}
body{
    max-width: 900px;
    margin: 0px auto;
    background-color:whitesmoke;
    background-size: cover;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 5rem;
}
.main_container{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}
h1{
    font-size: 3rem;
    color: #3D4B72;
}
.big_text_days , .big_text_hours , .big_text_mins , .big_text_sec{
    font-size: 2rem;
    font-weight: bold;
    line-height: 2;
    color: #AC7591;
    text-align: center;
}
p{
    padding: 20px 0px 20px 0px;
    font-size: 3rem;
    text-align: center;
}
.spantext{
    color: #103c28;
    margin: 0px 3rem;
    font-size: 2rem;
    font-style: italic;
}
.text_sec{
    color : #005259;
}
_x000D_
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="description" content="Responsive site">
        <meta name="keywords" content="HTML,CSS,JS">
        <meta name="author" content="Ranjan">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Home</title>

        <link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One|Bree+Serif|Exo|Exo+2|Lato|Mansalva|Playfair+Display&display=swap" rel="stylesheet">
       
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

</head>

    <body>
        
    <section>
      <h1>CountDown Timer</h1>
        </section>
                
         <section>
          <div class="main_container">
                
            <div class="days_container">
             <p class="big_text_days">1</p>
              <span class="spantext spantextdays">Days</span>
            </div>
    
            <div class="hours_container">
             <p class="big_text_hours">1</p>
              <span class="spantext spantexthours">Hours</span>
            </div>
    
            <div class="mins_container">
             <p class="big_text_mins">1</p>
              <span class="spantext spantextmins">Minutes</span>
            </div>
            
            <div class="sec_container">
             <p class="big_text_sec text_sec">1</p>
              <span class="spantext spantextsec">Seconds</span>
            </div>
         </div>
        </section>

    </body>
</html>
_x000D_
_x000D_
_x000D_

How can I create a self-signed cert for localhost?

After spending a good amount of time on this issue I found whenever I followed suggestions of using IIS to make a self signed certificate, I found that the Issued To and Issued by was not correct. SelfSSL.exe was the key to solving this problem. The following website not only provided a step by step approach to making self signed certificates, but also solved the Issued To and Issued by problem. Here is the best solution I found for making self signed certificates. If you'd prefer to see the same tutorial in video form click here.

A sample use of SelfSSL would look something like the following:

SelfSSL /N:CN=YourWebsite.com /V:1000 /S:2

SelfSSL /? will provide a list of parameters with explanation.

Asp.net Validation of viewstate MAC failed

There are another scenario which was happening for my customers. This was happening normally in certain time because of shift changes and users needed to login with different user. Here is a scenario which Anti forgery system protects system by generation this error:

1- Once close/open your browser. 2- Go to your website and login with "User A" 3- Open new Tab in browser and enter the same address site. (You can see your site Home page without any authentication) 4- Logout from your site and Login with another User(User B) in second tab. 5- Now go back to the first Tab which you logged in by "User A". You can still see the page but any action in this tab will make the error. Because your cookie is already updated by "User B" and you are trying to send a request by an invalid user. (User A)

How can I have grep not print out 'No such file or directory' errors?

I redirect stderr to stdout and then use grep's invert-match (-v) to exclude the warning/error string that I want to hide:

grep -r <pattern> * 2>&1 | grep -v "No such file or directory"

Delete duplicate elements from an array

As elements are yet ordered, you don't have to build a map, there's a fast solution :

var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
   if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}

If your array weren't sorted, you would use a map :

var newarr = (function(arr){
  var m = {}, newarr = []
  for (var i=0; i<arr.length; i++) {
    var v = arr[i];
    if (!m[v]) {
      newarr.push(v);
      m[v]=true;
    }
  }
  return newarr;
})(arr);

Note that this is, by far, much faster than the accepted answer.

Managing large binary files with Git

I am looking for opinions of how to handle large binary files on which my source code (web application) is dependent. What are your experiences/thoughts regarding this?

I personally have run into synchronisation failures with Git with some of my cloud hosts once my web applications binary data notched above the 3 GB mark. I considered BFT Repo Cleaner at the time, but it felt like a hack. Since then I've begun to just keep files outside of Git purview, instead leveraging purpose-built tools such as Amazon S3 for managing files, versioning and back-up.

Does anybody have experience with multiple Git repositories and managing them in one project?

Yes. Hugo themes are primarily managed this way. It's a little kudgy, but it gets the job done.


My suggestion is to choose the right tool for the job. If it's for a company and you're managing your codeline on GitHub pay the money and use Git-LFS. Otherwise you could explore more creative options such as decentralized, encrypted file storage using blockchain.

Additional options to consider include Minio and s3cmd.

export html table to csv

Used the answer above, but altered it for my needs.

I used the following function and imported to my REACT file where I needed to download the csv file.

I had a span tag within my th elements. Added comments to what most functions/methods do.

import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';


export function tableToCSV(){
  let tableHeaders = Array.from(document.querySelectorAll('th'))
    .map(item => {
      // title = splits elem tags on '\n',
      // then filter out blank "" that appears in array.
      // ex ["Timestamp", "[Full time]", ""]
      let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
      return title
    }).join(",")

  const rows = Array.from(document.querySelectorAll('tr'))
  .reduce((arr, currRow) => {
    // if tr tag contains th tag.
    // if null return array.
    if (currRow.querySelector('th')) return arr

    // concats individual cells into csv format row.
    const cells = Array.from(currRow.querySelectorAll('td'))
      .map(item => item.innerText)
      .join(',')
    return arr.concat([cells])
  }, [])

return tableHeaders + '\n' + rows.join('\n')
}

export function downloadCSV(csv){
  const csvFile = new Blob([csv], { type: 'text/csv' })
  const downloadLink =  document.createElement('a')
  // sets the name for the download file
  downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
  // sets the url to the window URL created from csv file above
  downloadLink.href = window.URL.createObjectURL(csvFile)
  // creates link, but does not display it.
  downloadLink.style.display = 'none'
  // add link to body so click function below works
  document.body.appendChild(downloadLink)

  downloadLink.click()
}

When user click export to csv it trigger the following function in react.

  handleExport = (e) => {
    e.preventDefault();
    const csv = tableToCSV()
    return downloadCSV(csv)
  }

Example html table elems.

  <table id="datatable">
        <tbody>
          <tr id="tableHeader" className="t-header">
            <th>Timestamp
              <span className="block">full time</span></th>
            <th>current rate
              <span className="block">alt view</span>
            </th>
            <th>Battery Voltage
              <span className="block">current voltage
              </span>
            </th>
            <th>Temperature 1
              <span className="block">[C]</span>
            </th>
            <th>Temperature 2
              <span className="block">[C]</span>
            </th>
            <th>Time & Date </th>
          </tr>

        </tbody>
        <tbody>
          {this.renderData()}
        </tbody>
      </table>
    </div>

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

Formatting a Date String in React Native

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

I believe python arrays just admit values. So convert it to list:

kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

I suggest you use Promise

myApp.service('dataService', function($http,$q) {

  delete $http.defaults.headers.common['X-Requested-With'];
  this.getData = function() {
     deferred = $q.defer();
     $http({
         method: 'GET',
         url: 'https://www.example.com/api/v1/page',
         params: 'limit=10, sort_by=created:desc',
         headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
     }).success(function(data){
         // With the data succesfully returned, we can resolve promise and we can access it in controller
         deferred.resolve();
     }).error(function(){
          alert("error");
          //let the function caller know the error
          deferred.reject(error);
     });
     return deferred.promise;
  }
});

so In your controller you can use the method

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(response) {
        $scope.data = response;
    });
});

promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

I had the same issue. but fixed it by downloading composer & installing it from scratch.

How / can I display a console window in Intellij IDEA?

More IntelliJ 13+ Shortcuts for Terminal

Mac OS X:

alt ?F12

cmd ?shift ?A then type Terminal then hit Enter

shift ?shift ?shift ?shift ? then type Terminal then hit Enter

Windows:

altF12 press Enter

ctrlshift ?A start typing Terminal then hit Enter

shift ?shift ? then type Terminal then hit Enter

Insert multiple rows into single column

to insert values for a particular column with other columns remain same:-

INSERT INTO `table_name`(col1,col2,col3)
   VALUES (1,'val1',0),(1,'val2',0),(1,'val3',0)

iPhone UILabel text soft shadow

Additionally to IIDan's answer: For some purposes it is necessary to set

label.layer.shouldRasterize = YES

I think this is due to the blend mode that is used to render the shadow. For example I had a dark background and white text on it and wanted to "highlight" the text using a black shadowy glow. It wasn't working until I set this property.

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Make sure, following jar file included in your class path and lib folder.

spring-core-3.0.5.RELEASE.jar

enter image description here

if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
</dependency>

Note : Replace ${org.springframework.version} with version number.

How to use HTTP_X_FORWARDED_FOR properly?

In the light of the latest httpoxy vulnerabilities, there is really a need for a full example, how to use HTTP_X_FORWARDED_FOR properly.

So here is an example written in PHP, how to detect a client IP address, if you know that client may be behind a proxy and you know this proxy can be trusted. If you don't known any trusted proxies, just use REMOTE_ADDR

<?php

function get_client_ip ()
{
    // Nothing to do without any reliable information
    if (!isset ($_SERVER['REMOTE_ADDR'])) {
        return NULL;
    }

    // Header that is used by the trusted proxy to refer to
    // the original IP
    $proxy_header = "HTTP_X_FORWARDED_FOR";

    // List of all the proxies that are known to handle 'proxy_header'
    // in known, safe manner
    $trusted_proxies = array ("2001:db8::1", "192.168.50.1");

    if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {

        // Get the IP address of the client behind trusted proxy
        if (array_key_exists ($proxy_header, $_SERVER)) {

            // Header can contain multiple IP-s of proxies that are passed through.
            // Only the IP added by the last proxy (last IP in the list) can be trusted.
            $proxy_list = explode (",", $_SERVER[$proxy_header]);
            $client_ip = trim (end ($proxy_list));

            // Validate just in case
            if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
                return $client_ip;
            } else {
                // Validation failed - beat the guy who configured the proxy or
                // the guy who created the trusted proxy list?
                // TODO: some error handling to notify about the need of punishment
            }
        }
    }

    // In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
    return $_SERVER['REMOTE_ADDR'];
}

print get_client_ip ();

?>

process.env.NODE_ENV is undefined

We ran into this problem when working with node on Windows.

Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.

var environment = process.env.NODE_ENV || 'development';

In a production environment, we would define it per the usual methods (SET/export).

Shift elements in a numpy array

If you want a one-liner from numpy and aren't too concerned about performance, try:

np.sum(np.diag(the_array,1),0)[:-1]

Explanation: np.diag(the_array,1) creates a matrix with your array one-off the diagonal, np.sum(...,0) sums the matrix column-wise, and ...[:-1] takes the elements that would correspond to the size of the original array. Playing around with the 1 and :-1 as parameters can give you shifts in different directions.

Updating a local repository with changes from a GitHub repository

With an already-set origin master, you just have to use the below command -

git pull "https://github.com/yourUserName/yourRepo.git"

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

Is there a way to get rid of accents and convert a whole string to regular letters?

In case anyone is strugling to do this in kotlin, this code works like a charm. To avoid inconsistencies I also use .toUpperCase and Trim(). then i cast this function:

   fun stripAccents(s: String):String{

   if (s == null) {
      return "";
   }

val chars: CharArray = s.toCharArray()

var sb = StringBuilder(s)
var cont: Int = 0

while (chars.size > cont) {
    var c: kotlin.Char
    c = chars[cont]
    var c2:String = c.toString()
   //these are my needs, in case you need to convert other accents just Add new entries aqui
    c2 = c2.replace("Ã", "A")
    c2 = c2.replace("Õ", "O")
    c2 = c2.replace("Ç", "C")
    c2 = c2.replace("Á", "A")
    c2 = c2.replace("Ó", "O")
    c2 = c2.replace("Ê", "E")
    c2 = c2.replace("É", "E")
    c2 = c2.replace("Ú", "U")

    c = c2.single()
    sb.setCharAt(cont, c)
    cont++

}

return sb.toString()

}

to use these fun cast the code like this:

     var str: String
     str = editText.text.toString() //get the text from EditText
     str = str.toUpperCase().trim()

     str = stripAccents(str) //call the function

How to exit when back button is pressed?

finish your current_activity using method finish() onBack method of your current_activity

and then add below lines in onDestroy of the current_activity for Removing Force close

@Override
public void onDestroy()
{
    android.os.Process.killProcess(android.os.Process.myPid());
    super.onDestroy();
}

Where to download Microsoft Visual c++ 2003 redistributable

Another way:

using Unofficial (Full Size: 26.1 MB) VC++ All in one that contained your needed files:

http://www.wincert.net/forum/topic/9790-aio-microsoft-visual-bcfj-redistributable-x86x64/

OR (Smallest 5.10 MB) Microsoft Visual Basic/C++ Runtimes 1.1.1 RePacked Here:

http://www.wincert.net/forum/topic/9794-bonus-microsoft-visual-basicc-runtimes-111/

jQuery Validation using the class instead of the name value

Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.

On submit, find everything with class x, remove class x, add rule x.

$('#form').on('submit', function(e) {
    $('.alphanumeric_dash').each(function() {
        var $this = $(this);
        $this.removeClass('alphanumeric_dash');
        $(this).rules('add', {
            alphanumeric_dash: true
        });
    });
});

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

How do you input command line arguments in IntelliJ IDEA?

To do this in IntelliJ IDEA 2020.2.3 (Community edition) on Windows 10:

  1. ALT-SHIFT-F10
  2. 0
  3. [TAB] 7 times

Updated for 11/2020.

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

gcc makefile error: "No rule to make target ..."

In my case, the source and/or old object file(s) were locked (read-only) by a semi-crashed IDE or from a backup cloud service that stopped working properly. Restarting all programs and services that were associated with the folder structure solved the problem.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Displaying a message in iOS which has the same functionality as Toast in Android

For me this solution works fine: https://github.com/cruffenach/CRToast

enter image description here

Example how use it:

    NSDictionary *options = @{
                          kCRToastTextKey : @"Hello World!",
                          kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                          kCRToastBackgroundColorKey : [UIColor redColor],
                          kCRToastAnimationInTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionLeft),
                          kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionRight)
                          };
[CRToastManager showNotificationWithOptions:options
                            completionBlock:^{
                                NSLog(@"Completed");
                            }];

What is setBounds and how do I use it?

The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

I was having the same problem, but using Long type. I changed for INT and it worked for me.

CREATE TABLE lists (
 id INT NOT NULL AUTO_INCREMENT,
 desc varchar(30),
 owner varchar(20),
 visibility boolean,
 PRIMARY KEY (id)
 );

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You have included a dependency on the SLF4J API, which is what you use in your application for logging, but you must also include an implementation that does the real logging work.

For example to log through Log4J you would add this dependency:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.5.2</version>
    </dependency>

The recommended implementation would be logback-classic, which is the successor of Log4j, made by the same guys that made SLF4J and Log4J:

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>0.9.24</version>
</dependency>

Note: The versions may be incorrect.

No connection string named 'MyEntities' could be found in the application config file

are you using more than one project on your solution?

Because if you are, the web config you must check is the one on the same project as de .edmx file

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

It happens when one project dll is failing and that is referenced by number of projects. So first fix it and then Build individuals.

Range with step of type float

This is what I would use:

numbers = [float(x)/10 for x in range(10)]

rather than:

numbers = [x*0.1 for x in range(10)]
that would return :
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

hope it helps.

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

Jquery click not working with ipad

We have a similar problem: the click event on a button doesn't work, as long as the user has not scrolled the page. The bug appears only on iOS.

We solved it by scrolling the page a little bit:

$('#modal-window').animate({scrollTop:$("#next-page-button-anchor").offset().top}, 500);

(It doesn't answer the ultimate cause, though. Maybe some kind of bug in Safari mobile ?)

Suppress warning messages using mysql from within Terminal, but password written in bash script

You can also just redirect the standard error STDERR output to /dev/null

So just do:

mysql -u $user -p$password -e "statement" 2> /dev/null

How can I get javascript to read from a .json file?

You can do it like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
             <script type="text/javascript" >
                function load() {
                     var mydata = JSON.parse(data);
                     alert(mydata.length);

                     var div = document.getElementById('data');

                     for(var i = 0;i < mydata.length; i++)
                     {
                        div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                     }
                 }
        </script>
    </head>
    <body onload="load()">
    <div id= "data">

    </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

Add data dynamically to an Array

You should use method array_push to add value or array to array exists

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

In my case these steps solved my problem:

  1. terminating npm process (CTRL + C)
  2. deleting entire folder
  3. creating new one
  4. running npm again

How to get main div container to align to centre?

I would omit the * { text-align:center } declaration, as it sets center alignment for all elements.

Usually with a fixed width container margin: 0 auto should be enough

How to call a shell script from python code?

In case the script is having multiple arguments

#!/usr/bin/python

import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output

Output will give the status code. If script runs successfully it will give 0 otherwise non-zero integer.

podname=xyz  serial=1234
0

Below is the test.sh shell script.

#!/bin/bash

podname=$1
serial=$2
echo "podname=$podname  serial=$serial"

Export MySQL data to Excel in PHP

This is new version of php code

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_dbname";
//mysql and db connection

$con = new mysqli($servername, $username, $password, $dbname);

if ($con->connect_error) {  //error check
    die("Connection failed: " . $con->connect_error);
}
else
{

}


$DB_TBLName = "your_table_name"; 
$filename = "excelfilename";  //your_file_name
$file_ending = "xls";   //file_extention

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.'.'.$file_ending");  
header("Pragma: no-cache"); 
header("Expires: 0");

$sep = "\t";

$sql="SELECT * FROM $DB_TBLName"; 
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field name
    echo $property->name."\t";
}

print("\n");    

while($row = mysqli_fetch_row($resultt))  //fetch_table_data
{
    $schema_insert = "";
    for($j=0; $j< mysqli_num_fields($resultt);$j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
}

How do I use PHP to get the current year?

best shortcode for this section:

<?= date("Y"); ?>

What charset does Microsoft Excel use when saving files?

I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.

Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.

Get user input from textarea

Remove the spaces around your =:

<div>    
  <input type="text" [(ngModel)]="str" name="str">
</div>

But you need to have the variable named str on back-end, than its should work fine.

"A referral was returned from the server" exception when accessing AD from C#

A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.

In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.

If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl as appropriate).

  1. Download (by right click and "save target") get-pip to local drive.

  2. At the command prompt, navigate to the directory containing get-pip.py and run

    python get-pip.py

    which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

  3. Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl into the above directory (C:\Python27\Scripts)

  4. Still at the command prompt, navigate to the above directory and run:

    pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"

How to resize the jQuery DatePicker control

you can change jquery-ui-1.10.4.custom.css as follows

.ui-widget
{
    font-family: Lucida Grande,Lucida Sans,Arial,sans-serif;
    font-size: 0.6em;
}

HTML input field hint

I think for your situation, the easy and simple for your html input , you can probably add the attribute title

<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">

Intellij JAVA_HOME variable

Bit counter-intuitive, but you must first setup a SDK for Java projects. On the bottom right of the IntelliJ welcome screen, select 'Configure > Project Defaults > Project Structure'.

The Project tab on the left will show that you have no SDK selected:

Therefore, you must click the 'New...' button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should be populated with your JAVA_HOME variable, providing you have this set.

Changing the default title of confirm() in JavaScript?

You can always use a hidden div and use javascript to "popup" the div and have buttons that are like yes and or no. Pretty easy stuff to do.

Installing a pip package from within a Jupyter Notebook not working

Using pip2 worked for me:

!pip2 install geocoder
...
import geocoder
g = geocoder.google('Mountain View, CA')
g.latlng
[37.3860517, -122.0838511]

intelliJ IDEA 13 error: please select Android SDK

there is a button by name android monitor on the left bottom of the screen. if u have an issue with sdk it will show u confugure link.Change the path to your sdk folder. things will work

set initial viewcontroller in appdelegate - swift

I used this thread to help me convert the objective C to swift, and its working perfectly.

Instantiate and Present a viewController in Swift

Swift 2 code:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginSignupVC")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

    return true
}

Swift 3 code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginSignupVC")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

    return true
}

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

image has a shape of (64,64,3).

Your input placeholder _x have a shape of (?, 64,64,3).

The problem is that you're feeding the placeholder with a value of a different shape.

You have to feed it with a value of (1, 64, 64, 3) = a batch of 1 image.

Just reshape your image value to a batch with size one.

image = array(img).reshape(1, 64,64,3)

P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel. You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)

Getting Textbox value in Javascript

<script type="text/javascript" runat="server">
 public void Page_Load(object Sender, System.EventArgs e)
    {
        double rad=0.0;
        TextBox1.Attributes.Add("Visible", "False");
        if (TextBox1.Text != "") 
        rad = Convert.ToDouble(TextBox1.Text);    
        Button1.Attributes.Add("OnClick","alert("+ rad +")");
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Diameter" 
            style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server" 
            AutoPostBack="true" 
            style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>

use the help of this, hope it will be usefull

How to enable CORS in ASP.NET Core

Applies to .NET Core 1 and .Net Core 2 (further down)

If using .Net-Core 1.1

Unfortunately the docs are very confusing in this specific case. So I'll make it dead-simple:

  • Add Microsoft.AspNetCore.Cors nuget package to your project
  • In ConfigureServices method, add services.AddCors();
  • In Configure method, before calling app.UseMvc() and app.UseStaticFiles(), add:

    app.UseCors(builder => builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
    

That's it. Every client has access to your ASP.NET Core Website/API.


If using .Net-Core 2.0

  • Add Microsoft.AspNetCore.Cors nuget package to your project
  • in ConfigureServices method, before calling services.AddMvc(), add:

     services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder
                    .AllowAnyOrigin() 
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
        });
    
  • (Important) In Configure method, before calling app.UseMvc(), add app.UseCors("AllowAll");

    AllowAll is the policy name which we need to mention in app.UserCors. It could be any name.

How to set a timer in android

Probably Timerconcept

new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

 public void onTick(long millisUntilFinished) {
  }
  public void onFinish() {
 }
}.start();

or

Method 2 ::

Program the timer

Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

Go into the run method and add the following code.

//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {

    @Override
    public void run() {
        TextView tv = (TextView) findViewById(R.id.main_timer_text);
        tv.setText(String.valueOf(time));
        time += 1;
    }

});

How to perform a for loop on each character in a string in Bash?

You can use a C-style for loop:

foo=string
for (( i=0; i<${#foo}; i++ )); do
  echo "${foo:$i:1}"
done

${#foo} expands to the length of foo. ${foo:$i:1} expands to the substring starting at position $i of length 1.

How can I see the entire HTTP request that's being sent by my Python application?

If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

Best way to specify whitespace in a String.Split operation

If you just call:

string[] ssize = myStr.Split(null); //Or myStr.Split()

or:

string[] ssize = myStr.Split(new char[0]);

then white-space is assumed to be the splitting character. From the string.Split(char[]) method's documentation page.

If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.

Always, always, always read the documentation!

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

How to find out the server IP address (using JavaScript) that the browser is connected to?

I am sure the following code will help you to get ip address.

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>

Convert base64 png data to javascript file objects

Way 1: only works for dataURL, not for other types of url.

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
    console.log(file);
})

Both works in Chrome and Firefox.

How to write a:hover in inline CSS?

You can do this. But not in inline styles. You can use onmouseover and onmouseout events:

_x000D_
_x000D_
<div style="background: #333; padding: 10px; cursor: pointer"_x000D_
   onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">_x000D_
      Hover on me!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

IF you want to handle 'standard' JSON representation of the Date then better to use this pattern: "yyyy-MM-dd'T'HH:mm:ssX".

Notice the X on the end. It will handle timezones in ISO 8601 standard, and ISO 8601 is exactly what produces this statement in Javascript new Date().toJSON()

Comparing to other answers it has some benefits:

  1. You don't need to require your clients to send date in GMT
  2. You don't need to explicitly convert your Date object to GMT using this: sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case, .composer was owned by root, so I did sudo rm -fr .composer and then my global require worked.

Be warned! You don't wanna use that command if you are not sure what you are doing.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

Here is the best solution I've found so far. It works great and it's cross-browser (IE 8+).

ul {
    list-style: none;
    margin-left: 0;
    padding-left: 1.2em;
    text-indent: -1.2em;
}

li:before {
    content: "?";
    display: block;
    float: left;
    width: 1.2em;
    color: #ff0000;
}

The important thing is to have the character in a floating block with a fixed width so that the text remains aligned if it's too long to fit on a single line. 1.2em is the width you want for your character, change it for your needs.

SQLAlchemy IN clause

Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session is your database session here, while User is the ORM class with __tablename__ equal to "users".

Manually Triggering Form Validation using jQuery

Html Code:

<form class="validateDontSubmit">
....
<button style="dislay:none">submit</button>
</form>
<button class="outside"></button>

javascript( using Jquery):

<script type="text/javascript">

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

$(document).ready(function(){
// using button outside trigger click
    $('.outside').click(function() {
        $('.validateDontSubmit button').trigger('click');
    });
});
</script>

Hope this will help you

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

Despite answer from CaioToOn above, I still had problems getting this to work initially.

After multiple attempts, finally got it working. Am pasting my final version here - hoping it will benefit somebody else.

    <build> 
        <plugins>
            <!--
            Copy all Maven Dependencies (-MD) into libMD/ folder to use in classpath via shellscript
             --> 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/libMD</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <!--  
        Above maven-dependepcy-plugin gives a validation error in m2e. 
        To fix that, add the plugin management step below. Per: http://stackoverflow.com/a/12109018
        -->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-dependency-plugin</artifactId>
                                        <versionRange>[2.0,)</versionRange>
                                        <goals>
                                            <goal>copy-dependencies</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

In bootstrap how to add borders to rows without adding up?

On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:

First give all of the rows children a border on the right and bottom

.borders div{
    border-right:1px solid #999;
    border-bottom:1px solid #999;
}

Next give the first child of each or a left border

.borders div:first-child{
    border-left:
    1px solid #999;
}

Last make sure to clear the borders for their child elements

.borders div > div{
    border:0;
}

HTML:

<div class="row borders">
    <div class="col-xs-5 col-md-2">Email</div>
    <div class="col-xs-7 col-md-4">[email protected]</div>
    <div class="col-xs-5 col-md-2">Phone</div>
    <div class="col-xs-7 col-md-4">555-123-4567</div>
</div>

How to express a One-To-Many relationship in Django

To handle One-To-Many relationships in Django you need to use ForeignKey.

The documentation on ForeignKey is very comprehensive and should answer all the questions you have:

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

If you want the reverse relationship, you would need to add two ForeignKey fields to your PhoneNumber model, one to Dude and one to Business. This would allow each number to belong to either one Dude or one Business, and have Dudes and Businesses able to own multiple Numbers. I think this might be what you are after.

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results

enter image description here

DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size

Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)

DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit

Bash Templating: How to build configuration files from templates with Bash?

To follow up on plockc's answer on this page, here is a dash-suitable version, for those of you looking to avoid bashisms.

eval "cat <<EOF >outputfile
$( cat template.in )
EOF
" 2> /dev/null

How do you change the server header returned by nginx?

Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. http://wiki.codemongers.com/NginxHttpHeadersModule

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to parse XML in Bash?

This is sufficient...

xpath xhtmlfile.xhtml '/html/head/title/text()' > titleOfXHTMLPage.txt

Any way to limit border length?

This is a CSS trick, not a formal solution. I leave the code with the period black because it helps me position the element. Afterward, color your content (color:white) and (margin-top:-5px or so) to make it as though the period is not there.

div.yourdivname:after {
content: ".";
  border-bottom:1px solid grey;
  width:60%;
  display:block;
  margin:0 auto;
}

Using Spring RestTemplate in generic method with generic parameter

I am using org.springframework.core.ResolvableType for a ListResultEntity :

    ResolvableType resolvableType = ResolvableType.forClassWithGenerics(ListResultEntity.class, itemClass);
    ParameterizedTypeReference<ListResultEntity<T>> typeRef = ParameterizedTypeReference.forType(resolvableType.getType());

So in your case:

public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        ParameterizedTypeReference.forType(ResolvableType.forClassWithGenerics(ResponseWrapper.class, clazz)));
    return response;
}

This only makes use of spring and of course requires some knowledge about the returned types (but should even work for things like Wrapper>> as long as you provide the classes as varargs )

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

What is the difference between static_cast<> and C style casting?

static_cast checks at compile time that conversion is not between obviously incompatible types. Contrary to dynamic_cast, no check for types compatibility is done at run time. Also, static_cast conversion is not necessarily safe.

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int.

The user of static_cast must make sure that the conversion is safe.

The C-style cast does not perform any check, either at compile or at run time.

#pragma once vs include guards?

After engaging in an extended discussion about the supposed performance tradeoff between #pragma once and #ifndef guards vs. the argument of correctness or not (I was taking the side of #pragma once based on some relatively recent indoctrination to that end), I decided to finally test the theory that #pragma once is faster because the compiler doesn't have to try to re-#include a file that had already been included.

For the test, I automatically generated 500 header files with complex interdependencies, and had a .c file that #includes them all. I ran the test three ways, once with just #ifndef, once with just #pragma once, and once with both. I performed the test on a fairly modern system (a 2014 MacBook Pro running OSX, using XCode's bundled Clang, with the internal SSD).

First, the test code:

#include <stdio.h>

//#define IFNDEF_GUARD
//#define PRAGMA_ONCE

int main(void)
{
    int i, j;
    FILE* fp;

    for (i = 0; i < 500; i++) {
        char fname[100];

        snprintf(fname, 100, "include%d.h", i);
        fp = fopen(fname, "w");

#ifdef IFNDEF_GUARD
        fprintf(fp, "#ifndef _INCLUDE%d_H\n#define _INCLUDE%d_H\n", i, i);
#endif
#ifdef PRAGMA_ONCE
        fprintf(fp, "#pragma once\n");
#endif


        for (j = 0; j < i; j++) {
            fprintf(fp, "#include \"include%d.h\"\n", j);
        }

        fprintf(fp, "int foo%d(void) { return %d; }\n", i, i);

#ifdef IFNDEF_GUARD
        fprintf(fp, "#endif\n");
#endif

        fclose(fp);
    }

    fp = fopen("main.c", "w");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "#include \"include%d.h\"\n", i);
    }
    fprintf(fp, "int main(void){int n;");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "n += foo%d();\n", i);
    }
    fprintf(fp, "return n;}");
    fclose(fp);
    return 0;
}

And now, my various test runs:

folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.164s
user    0m0.105s
sys 0m0.041s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.140s
user    0m0.097s
sys 0m0.018s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.193s
user    0m0.143s
sys 0m0.024s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.031s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.170s
user    0m0.109s
sys 0m0.033s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.155s
user    0m0.105s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.181s
user    0m0.133s
sys 0m0.020s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.167s
user    0m0.119s
sys 0m0.021s
folio[~/Desktop/pragma] fluffy$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

As you can see, the versions with #pragma once were indeed slightly faster to preprocess than the #ifndef-only one, but the difference was quite negligible, and would be far overshadowed by the amount of time that actually building and linking the code would take. Perhaps with a large enough codebase it might actually lead to a difference in build times of a few seconds, but between modern compilers being able to optimize #ifndef guards, the fact that OSes have good disk caches, and the increasing speeds of storage technology, it seems that the performance argument is moot, at least on a typical developer system in this day and age. Older and more exotic build environments (e.g. headers hosted on a network share, building from tape, etc.) may change the equation somewhat but in those circumstances it seems more useful to simply make a less fragile build environment in the first place.

The fact of the matter is, #ifndef is standardized with standard behavior whereas #pragma once is not, and #ifndef also handles weird filesystem and search path corner cases whereas #pragma once can get very confused by certain things, leading to incorrect behavior which the programmer has no control over. The main problem with #ifndef is programmers choosing bad names for their guards (with name collisions and so on) and even then it's quite possible for the consumer of an API to override those poor names using #undef - not a perfect solution, perhaps, but it's possible, whereas #pragma once has no recourse if the compiler is erroneously culling an #include.

Thus, even though #pragma once is demonstrably (slightly) faster, I don't agree that this in and of itself is a reason to use it over #ifndef guards.

EDIT: Thanks to feedback from @LightnessRacesInOrbit I've increased the number of header files and changed the test to only run the preprocessor step, eliminating whatever small amount of time was being added in by the compile and link process (which was trivial before and nonexistent now). As expected, the differential is about the same.

Pass an array of integers to ASP.NET Web API?

You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI

 public class CategoryController : ApiController
 {
     public List<Category> Get(String categoryIDs)
     {
         List<Category> categoryRepo = new List<Category>();

         String[] idRepo = categoryIDs.Split(',');

         foreach (var id in idRepo)
         {
             categoryRepo.Add(new Category()
             {
                 CategoryID = id,
                 CategoryName = String.Format("Category_{0}", id)
             });
         }
         return categoryRepo;
     }
 }

 public class Category
 {
     public String CategoryID { get; set; }
     public String CategoryName { get; set; }
 } 

Output :

[
{"CategoryID":"4","CategoryName":"Category_4"}, 
{"CategoryID":"5","CategoryName":"Category_5"}, 
{"CategoryID":"3","CategoryName":"Category_3"} 
]

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

Best way to concatenate List of String objects?

In java 8 you can also use a reducer, something like:

public static String join(List<String> strings, String joinStr) {
    return strings.stream().reduce("", (prev, cur) -> prev += (cur + joinStr));
}

Checking if date is weekend PHP

The working version of your code (from the errors pointed out by BoltClock):

<?php
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
    echo "true";
} else {
    echo "false";
}

?>

The stray "{" is difficult to see, especially without a decent PHP editor (in my case). So I post the corrected version here.

What can be the reasons of connection refused errors?

If you try to open a TCP connection to another host and see the error "Connection refused," it means that

  1. You sent a TCP SYN packet to the other host.
  2. Then you received a TCP RST packet in reply.

RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.

See https://tools.ietf.org/html/rfc793 page 69:

SYN-RECEIVED STATE

If the RST bit is set

If this connection was initiated with a passive OPEN (i.e., came from the LISTEN state), then return this connection to LISTEN state and return. The user need not be informed. If this connection was initiated with an active OPEN (i.e., came from SYN-SENT state) then the connection was refused, signal the user "connection refused". In either case, all segments on the retransmission queue should be removed. And in the active OPEN case, enter the CLOSED state and delete the TCB, and return.

Best way to split string into lines

string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

Inline SVG in CSS

For people who are still struggling, I managed to get this working on all modern browsers IE11 and up.

base64 was no option for me because I wanted to use SASS to generate SVG icons based on any given color. For example: @include svg_icon(heart, #FF0000); This way I can create a certain icon in any color, and only have to embed the SVG shape once in the CSS. (with base64 you'd have to embed the SVG in every single color you want to use)

There are three things you need be aware of:

  1. URL ENCODE YOUR SVG As others have suggested, you need to URL encode your entire SVG string for it to work in IE11. In my case, I left out the color values in fields such as fill="#00FF00" and stroke="#FF0000" and replaced them with a SASS variable fill="#{$color-rgb}" so these can be replaced with the color I want. You can use any online converter to URL encode the rest of the string. You'll end up with an SVG string like this:

    %3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%2041.012%2010.535%2079.541%2028.973%20113.104L3.825%20464.586c345%2012.797%2041.813%2012.797%2015.467%200%2029.872-4.721%2041.813-12.797v158.184z%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E


  1. OMIT THE UTF8 CHARSET IN THE DATA URL When creating your data URL, you need to leave out the charset for it to work in IE11.

    NOT background-image: url( data:image/svg+xml;utf-8,%3Csvg%2....)
    BUT background-image: url( data:image/svg+xml,%3Csvg%2....)


  1. USE RGB() INSTEAD OF HEX colors Firefox does not like # in the SVG code. So you need to replace your color hex values with RGB ones.

    NOT fill="#FF0000"
    BUT fill="rgb(255,0,0)"

In my case I use SASS to convert a given hex to a valid rgb value. As pointed out in the comments, it's best to URL encode your RGB string as well (so comma becomes %2C)

@mixin svg_icon($id, $color) {
   $color-rgb: "rgb(" + red($color) + "%2C" + green($color) + "%2C" + blue($color) + ")";
   @if $id == heart {
      background-image: url('data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%204%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E');
   }
}

I realize this might not be the best solution for very complex SVG's (inline SVG never is in that case), but for flat icons with only a couple of colors this really works great.

I was able to leave out an entire sprite bitmap and replace it with inline SVG in my CSS, which turned out to only be around 25kb after compression. So it's a great way to limit the amount of requests your site has to do, without bloating your CSS file.

How to show what a commit did?

I found out that "git show --stat" is the best out of all here, gives you a brief summary of the commit, what files did you add and modify without giving you whole bunch of stuff, especially if you changed a lot files.

What is a StackOverflowError?

Simple Java example, that cause java.lang.StackOverflowError because of bad recursive call

class Human {
    Human(){
        new Animal();       
    }
}

class Animal extends Human {
    Animal(){
        super();
    }
}

public class Test01 {
    public static void main(String[] args) {
        new Animal();
    }
}

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Create file path from variables

Yes there is such a built-in function: os.path.join.

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

Resize image with javascript canvas (smoothly)

I wrote small js-utility to crop and resize image on front-end. Here is link on GitHub project. Also you can get blob from final image to send it.

import imageSqResizer from './image-square-resizer.js'

let resizer = new imageSqResizer(
    'image-input',
    300,
    (dataUrl) => 
        document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);

//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;

How to add new line in Markdown presentation?

MarkDown file in three way to Break a Line

<br /> Tag Using

paragraph First Line <br /> Second Line

\ Using

First Line sentence \
Second Line sentence 

space keypress two times Using

First Line sentence??
Second Line sentence

Paragraphs in use <br /> tag.

Multiple sentences in using \ or two times press space key then Enter and write a new sentence.

if-else statement inside jsx: ReactJS

For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:-

//This is for if else

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)

}

//This is only for if or only for one condition

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') &&
           <Text>data</Text>
        }
    </View>
)

}

How can I get the current user directory?

Also very helpful, while investigating the Environment.SpecialFolder enum. Use LINQPad or create a solution and execute this code:

Enum.GetValues(typeof(Environment.SpecialFolder))
    .Cast<Environment.SpecialFolder>()
    .Select(specialFolder => new
    {
        Name = specialFolder.ToString(),
        Path = Environment.GetFolderPath(specialFolder)
    })
    .OrderBy(item => item.Path.ToLower())

Folder Paths

This is the result on my machine:

MyComputer
LocalizedResources
CommonOemLinks
ProgramFiles            C:\Program Files (x86) 
ProgramFilesX86         C:\Program Files (x86) 
CommonProgramFiles      C:\Program Files (x86)\Common Files 
CommonProgramFilesX86   C:\Program Files (x86)\Common Files 
CommonApplicationData   C:\ProgramData 
CommonStartMenu         C:\ProgramData\Microsoft\Windows\Start Menu 
CommonPrograms          C:\ProgramData\Microsoft\Windows\Start Menu\Programs 
CommonAdminTools        C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
CommonStartup           C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup 
CommonTemplates         C:\ProgramData\Microsoft\Windows\Templates 
UserProfile             C:\Users\fisch 
LocalApplicationData    C:\Users\fisch\AppData\Local 
CDBurning               C:\Users\fisch\AppData\Local\Microsoft\Windows\Burn\Burn 
History                 C:\Users\fisch\AppData\Local\Microsoft\Windows\History 
InternetCache           C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCache 
Cookies                 C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCookies 
ApplicationData         C:\Users\fisch\AppData\Roaming 
NetworkShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Network Shortcuts 
PrinterShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Printer Shortcuts 
Recent                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Recent 
SendTo                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\SendTo 
StartMenu               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu 
Programs                C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs 
AdminTools              C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
Startup                 C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 
Templates               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Templates 
Desktop                 C:\Users\fisch\Desktop 
DesktopDirectory        C:\Users\fisch\Desktop 
Favorites               C:\Users\fisch\Favorites 
MyMusic                 C:\Users\fisch\Music 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyPictures              C:\Users\fisch\OneDrive\Pictures 
MyVideos                C:\Users\fisch\Videos 
CommonDesktopDirectory  C:\Users\Public\Desktop 
CommonDocuments         C:\Users\Public\Documents 
CommonMusic             C:\Users\Public\Music 
CommonPictures          C:\Users\Public\Pictures 
CommonVideos            C:\Users\Public\Videos 
Windows                 C:\Windows 
Fonts                   C:\Windows\Fonts 
Resources               C:\Windows\resources 
System                  C:\Windows\system32 
SystemX86               C:\Windows\SysWoW64 

("fisch" is the first 5 letters of my last name. This is the user name assigned when signing in with a Microsoft Account.)

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Passing parameters to a JQuery function

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: "POST",
         url: "someurl.php",
         data: "id=" + id + "&name=" + name,
         success: function(msg){
                     alert( "Data Saved: " + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: "GET",
          url: "someurl.php",
          data: "id=" + id + "&name=" + name,
          success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
     });
}

EDIT:

A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.

<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>

<script type="text/javascript">
$(function() {
   $('.ajax-link').click( function() {
         $.get( $(this).attr('href'), function(msg) {
              alert( "Data Saved: " + msg );
         });
         return false; // don't follow the link!
   });
});
</script>

What does -> mean in C++?

a->b means (*a).b.

If a is a pointer, a->b is the member b of which a points to.

a can also be a pointer like object (like a vector<bool>'s stub) override the operators.

(if you don't know what a pointer is, you have another question)

setting an environment variable in virtualenv

Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.

The second way if you're looking for a lighter approach is to have a .env file locally then run:

export $(cat .env)

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
 </a>

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    }

Try it out... It works (at least on Chrome)!

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

Create Excel files from C# without office

Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff

How I could add dir to $PATH in Makefile?

To set the PATH variable, within the Makefile only, use something like:

PATH := $(PATH):/my/dir

test:
@echo my new PATH = $(PATH)

JVM property -Dfile.encoding=UTF8 or UTF-8?

If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8), if you don't set it on the command-line with -Dfile.encoding, the JDK will default file.encoding and the default Charset like this:

System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

... yields:

file.encoding: UTF-8
defaultCharset: UTF-8

... suggesting the default is UTF-8 on such a platform.

Additionally, if java.nio.charset.Charset.defaultCharset() finds file.encoding not-set, it looks for java.nio.charset.Charset.forName("UTF-8"), suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.

If you run the same program on the same platform with java -Dfile.encoding=UTF8, without the hypen, it yields:

file.encoding: UTF8
defaultCharset: UTF-8

... noting that the default charset has been canonicalized from UTF8 to UTF-8.

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

Matplotlib-Animation "No MovieWriters Available"

I know this question is about Linux, but in case someone stumbles on this problem on Mac like I did here is the solution for that. I had the exact same problem on Mac because ffmpeg is not installed by default apparently, and so I could solve it using:

brew install yasm
brew install ffmpeg

How to execute XPath one-liners from shell?

In my search to query maven pom.xml files I ran accross this question. However I had the following limitations:

  • must run cross-platform.
  • must exist on all major linux distributions without any additional module installation
  • must handle complex xml-files such as maven pom.xml files
  • simple syntax

I have tried many of the above without success:

  • python lxml.etree is not part of the standard python distribution
  • xml.etree is but does not handle complex maven pom.xml files well, have not digged deep enough
  • python xml.etree does not handle maven pom.xml files for unknown reason
  • xmllint does not work either, core dumps often on ubuntu 12.04 "xmllint: using libxml version 20708"

The solution that I have come across that is stable, short and work on many platforms and that is mature is the rexml lib builtin in ruby:

ruby -r rexml/document -e 'include REXML; 
     puts XPath.first(Document.new($stdin), "/project/version/text()")' < pom.xml

What inspired me to find this one was the following articles:

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

How can I measure the similarity between two images?

You might look at the code for the open source tool findimagedupes, though it appears to have been written in perl, so I can't say how easy it will be to parse...

Reading the findimagedupes page that I liked, I see that there is a C++ implementation of the same algorithm. Presumably this will be easier to understand.

And it appears you can also use gqview.

Block Comments in a Shell Script

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

This is from Vegas's example found here

Subset dataframe by multiple logical conditions of rows to remove

data <- data[-which(data[,1] %in% c("b","d","e")),]

PHP error: "The zip extension and unzip command are both missing, skipping."

Not to belabor the point, but if you are working in a Dockerfile, you would solve this particular issue with Composer by installing the unzip utility. Below is an example using the official PHP image to install unzip and the zip PHP extension for good measure.

FROM php:7.4-apache

# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer

# Install unzip utility and libs needed by zip PHP extension 
RUN apt-get update && apt-get install -y \
    zlib1g-dev \
    libzip-dev \
    unzip
RUN docker-php-ext-install zip

This is a helpful GitHub issue where the above is lovingly lifted from.

How to set environment variable or system property in spring tests?

For Unit Tests, the System variable is not instantiated yet when I do "mvn clean install" because there is no server running the application. So in order to set the System properties, I need to do it in pom.xml. Like so:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.21.0</version>
    <configuration>
        <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <MY_ENV_VAR>newValue</MY_ENV_VAR>
            <ENV_TARGET>olqa</ENV_TARGET>
            <buildDirectory>${project.build.directory}</buildDirectory>
        </systemPropertyVariables>
    </configuration>
</plugin>

Android Fragment no view found for ID?

I got this error when I upgraded from com.android.support:support-v4:21.0.0 to com.android.support:support-v4:22.1.1.

I had to change my layout from this:

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

To this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container_frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</FrameLayout> 

So the layout MUST have a child view. I'm assuming they enforced this in the new library.

Magento - How to add/remove links on my account navigation?

If you want to selectively remove links without having to copy/edit entire xml files, a nice solution can be found in this post in the magento forums

In this solution, you override the Mage_Customer_Block_Account_Navigation block with a local version, that adds a removeLinkByName method, which you then use in your layout.xml files, like so:

<?xml version="1.0"?>
    <layout version="0.1.0">

    <customer_account>
        <reference name="customer_account_navigation" >
                <!-- remove the link using your custom method -->
                <action method="removeLinkByName">
                   <name>recurring_profiles</name>
                </action>
                <action method="removeLinkByName">
                   <name>billing_agreements</name>
                </action>
        </reference>
    </customer_account>
</layout>

Seeing the console's output in Visual Studio 2010?

Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.

This is a console application I just dug up that stops after processing but before exiting:

class Program
{
    static void Main(string[] args)
    {
        DummyObjectList dol = new DummyObjectList(2);
        dol.Add(new DummyObject("test1", (Decimal)25.36));
        dol.Add(new DummyObject("test2", (Decimal)0.698));
        XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
        dolxs.Serialize(Console.Out, dol);

        Console.WriteLine(string.Empty);
        Console.WriteLine(string.Empty);

        List<DummyObject> dolist = new List<DummyObject>(2);
        dolist.Add(new DummyObject("test1", (Decimal)25.36));
        dolist.Add(new DummyObject("test2", (Decimal)0.698));
        XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
        dolistxs.Serialize(Console.Out, dolist);
        Console.Read(); //  <--- Right here
    }
}

Alternatively, you can simply add a breakpoint on the last line.

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

npm start error with create-react-app

it's possible that conflict with other library, delete node_modules and again npm install.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

C# switch on type

I did it one time with a workaround, hope it helps.

string fullName = typeof(MyObj).FullName;

switch (fullName)
{
    case "fullName1":
    case "fullName2":
    case "fullName3":
}

How to Extract Year from DATE in POSTGRESQL

Choose one from, where :my_date is a string input parameter of yyyy-MM-dd format:

SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));

or

SELECT DATE_PART('year', CAST(:my_date AS DATE));

Better use CAST than :: as there may be conflicts with input parameters.

How can I change the user on Git Bash?

For any OS

This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1
   
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "[email protected]"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git

Can you create nested WITH clauses for Common Table Expressions?

we can create nested cte.please see the below cte in example

;with cte_data as 
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)

select * from cte_data,cte_data1

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I've had same problem with docker-compose:

  1. Killed docker-proxy processe .
  2. Restart docker
  3. Start docker-compose again.

Efficiently counting the number of lines of a text file. (200mb+)

Using a loop of fgets() calls is fine solution and the most straightforward to write, however:

  1. even though internally the file is read using a buffer of 8192 bytes, your code still has to call that function for each line.

  2. it's technically possible that a single line may be bigger than the available memory if you're reading a binary file.

This code reads a file in chunks of 8kB each and then counts the number of newlines within that chunk.

function getLines($file)
{
    $f = fopen($file, 'rb');
    $lines = 0;

    while (!feof($f)) {
        $lines += substr_count(fread($f, 8192), "\n");
    }

    fclose($f);

    return $lines;
}

If the average length of each line is at most 4kB, you will already start saving on function calls, and those can add up when you process big files.

Benchmark

I ran a test with a 1GB file; here are the results:

             +-------------+------------------+---------+
             | This answer | Dominic's answer | wc -l   |
+------------+-------------+------------------+---------+
| Lines      | 3550388     | 3550389          | 3550388 |
+------------+-------------+------------------+---------+
| Runtime    | 1.055       | 4.297            | 0.587   |
+------------+-------------+------------------+---------+

Time is measured in seconds real time, see here what real means

How can I make my string property nullable?

You don't need to do anything, the Model Binding will pass null to property without any problem.

How can I decrease the size of Ratingbar?

Working Example

             <RatingBar
                style="@style/RatingBar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:numStars="5"
                android:rating="3.5"
                android:stepSize="0.5" />

and add this in your styles xml file

<style name="RatingBar"   
parent="android:style/Widget.Material.RatingBar.Small">
<item name="colorControlNormal">@color/primary_light</item>
<item name="colorControlActivated">@color/primary_dark</item>
</style>

This way you dont need to customise ratingBar.

how to stop a loop arduino

This will turn off interrupts and put the CPU into (permanent until reset/power toggled) sleep:

cli();
sleep_enable();
sleep_cpu();

See also http://arduino.land/FAQ/content/7/47/en/how-to-stop-an-arduino-sketch.html, for more details.

Beautiful way to remove GET-variables with PHP?

basename($_SERVER['REQUEST_URI']) returns everything after and including the '?',

In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.

$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);

$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;

How to show image using ImageView in Android

Drag image from your hard drive to Drawable folder in your project and in code use it like this:

ImageView image;

image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);

AngularJS sorting by property

As you can see in the code of angular-JS ( https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js ) ng-repeat does not work with objects. Here is a hack with sortFunction.

http://jsfiddle.net/sunnycpp/qaK56/33/

<div ng-app='myApp'>
    <div ng-controller="controller">
    <ul>
        <li ng-repeat="test in testData | orderBy:sortMe()">
            Order = {{test.value.order}} -> Key={{test.key}} Name=:{{test.value.name}}
        </li>
    </ul>
    </div>
</div>

myApp.controller('controller', ['$scope', function ($scope) {

    var testData = {
        a:{name:"CData", order: 2},
        b:{name:"AData", order: 3},
        c:{name:"BData", order: 1}
    };
    $scope.testData = _.map(testData, function(vValue, vKey) {
        return { key:vKey, value:vValue };
    }) ;
    $scope.sortMe = function() {
        return function(object) {
            return object.value.order;
        }
    }
}]);

Convert a PHP script into a stand-alone windows executable

The current PHP Nightrain (4.0.0) is written in Python and it uses the wxPython libraries. So far wxPython has been working well to get PHP Nightrain where it is today but in order to push PHP Nightrain to its next level, we are introducing a sibling of PHP Nightrain, the PHPWebkit!

It's an update to PHP Nightrain.

https://github.com/entrypass/nightrain-ep

Advantages of std::for_each over for loop

I used to dislike std::for_each and thought that without lambda, it was done utterly wrong. However I did change my mind some time ago, and now I actually love it. And I think it even improves readability, and makes it easier to test your code in a TDD way.

The std::for_each algorithm can be read as do something with all elements in range, which can improve readability. Say the action that you want to perform is 20 lines long, and the function where the action is performed is also about 20 lines long. That would make a function 40 lines long with a conventional for loop, and only about 20 with std::for_each, thus likely easier to comprehend.

Functors for std::for_each are more likely to be more generic, and thus reusable, e.g:

struct DeleteElement
{
    template <typename T>
    void operator()(const T *ptr)
    {
        delete ptr;
    }
};

And in the code you'd only have a one-liner like std::for_each(v.begin(), v.end(), DeleteElement()) which is slightly better IMO than an explicit loop.

All of those functors are normally easier to get under unit tests than an explicit for loop in the middle of a long function, and that alone is already a big win for me.

std::for_each is also generally more reliable, as you're less likely to make a mistake with range.

And lastly, compiler might produce slightly better code for std::for_each than for certain types of hand-crafted for loop, as it (for_each) always looks the same for compiler, and compiler writers can put all of their knowledge, to make it as good as they can.

Same applies to other std algorithms like find_if, transform etc.

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( 'li.target' ).css("border", "3px double red");

Good Luck

How to add a title to a html select tag

You can add an option tag on top of the others with no value and a prompt like this:

<select>
        <option value="">Choose One</option>
        <option value ="sydney">Sydney</option>
        <option value ="melbourne">Melbourne</option>
        <option value ="cromwell">Cromwell</option>
        <option value ="queenstown">Queenstown</option>
</select>

Or leave it blank instead of saying Choose one if you want.

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

You can fix that by running this: On Fedora:

sudo dnf install redhat-rpm-config

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Why are there two ways to unstage a file in Git?

For versions 2.23 and above only,

Instead of these suggestions, you could use git restore --staged <file> in order to unstage the file(s).

Determine Pixel Length of String in Javascript/jQuery?

Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/

[1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"

I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas

Google was pretty competive for option 1 and 3, 2 bombed.

FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.

Edge 11 Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.

Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.

How to round up a number to nearest 10?

We can "cheat" via round with

$rounded = round($roundee / 10) * 10;

We can also avoid going through floating point division with

function roundToTen($roundee)
{
  $r = $roundee % 10;
  return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}

Edit: I didn't know (and it's not well documented on the site) that round now supports "negative" precision, so you can more easily use

$round = round($roundee, -1);

Edit again: If you always want to round up, you can try

function roundUpToTen($roundee)
{
  $r = $roundee % 10;
  if ($r == 0)
    return $roundee;
  return $roundee + 10 - $r;    
}

How to run a python script from IDLE interactive shell?

I tested this and it kinda works out :

exec(open('filename').read())  # Don't forget to put the filename between ' '

Can't concatenate 2 arrays in PHP

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

$array3 = array_merge($array1, $array2);

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.

What is the default maximum heap size for Sun's JVM from Java SE 6?

As of JDK6U18 following are configurations for the Heap Size.

In the Client JVM, the default Java heap configuration has been modified to improve the performance of today's rich client applications. Initial and maximum heap sizes are larger and settings related to generational garbage collection are better tuned.

The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte. For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes. The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. This amount is at least 8 megabytes and otherwise 1/64 of physical memory up to a physical memory size of 1 gigabyte.

Source : http://www.oracle.com/technetwork/java/javase/6u18-142093.html

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

Angular: Can't find Promise, Map, Set and Iterator

I also have the same problem--"Promise not found"--when the code wants to create a Promise object.

Tried some solution found on stackoverflow, including the one to take out System.config({ ... }) to form system.js and have it included in index.html.

Finally I solved the problem. The issue is that, in index.html, es6-shim.min.js is included. However, in tsconfig.json, the "target" property under "compilerOptions" has the value of "es5". After I changed it to "es6", error is gone.

Is there a JSON equivalent of XQuery/XPath?

Just to add to the choices, there's also XPath. XPath 3.1 handles JSON as well as XML. In XPath 3.1 your required query is ?0?Objects?*[?id=3]

How to set-up a favicon?

This method is recommended

<link rel="icon" 
  type="image/png" 
  href="/somewhere/myicon.png" />

535-5.7.8 Username and Password not accepted

I had the same problem. Now its working fine after doing below changes.

https://www.google.com/settings/security/lesssecureapps

You should change the "Access for less secure apps" to Enabled (it was enabled, I changed to disabled and than back to enabled). After a while I could send email.

Change a Git remote HEAD to point to something besides master

First, create the new branch you would like to set as your default, for example:

$>git branch main

Next, push that branch to the origin:

$>git push origin main

Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."

Then, if you so choose, you can delete the master branch:

$>git push origin :master

Difference between Inheritance and Composition

Composition is just as it sounds - you create an object by plugging in parts.

EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,

Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel

So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.

Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.

For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.

With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).

Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,

iFuelable Interface:
   void AddSomeFuel()
   void UseSomeFuel()
   int  percentageFull()

then you can have a method somewhere else

private void FillHerUp(iFuelable : objectToFill) {

   Do while (objectToFill.percentageFull() <= 100)  {

        objectToFill.AddSomeFuel();
   }

Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.

If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.

How to make input type= file Should accept only pdf and xls

You can try following way

<input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">

OR (in asp.net mvc)

@Html.TextBoxFor(x => x.FileName, new { @id = "doc", @type = "file", @accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })

How can I check if a Perl array contains a particular value?

@eakssjo's benchmark is broken - measures creating hashes in loop vs creating regexes in loop. Fixed version (plus I've added List::Util::first and List::MoreUtils::any):

use List::Util qw(first);
use List::MoreUtils qw(any);
use Benchmark;

my @list = ( 1..10_000 );
my $hit = 5_000;
my $hit_regex = qr/^$hit$/; # precompute regex
my %params;
$params{$_} = 1 for @list;  # precompute hash
timethese(
    100_000, {
        'any' => sub {
            die unless ( any { $hit_regex } @list );
        },
        'first' => sub {
            die unless ( first { $hit_regex } @list );
        },
        'grep' => sub {
            die unless ( grep { $hit_regex } @list );
        },
        'hash' => sub {
            die unless ( $params{$hit} );
        },
    });

And result (it's for 100_000 iterations, ten times more than in @eakssjo's answer):

Benchmark: timing 100000 iterations of any, first, grep, hash...
       any:  0 wallclock secs ( 0.67 usr +  0.00 sys =  0.67 CPU) @ 149253.73/s (n=100000)
     first:  1 wallclock secs ( 0.63 usr +  0.01 sys =  0.64 CPU) @ 156250.00/s (n=100000)
      grep: 42 wallclock secs (41.95 usr +  0.08 sys = 42.03 CPU) @ 2379.25/s (n=100000)
      hash:  0 wallclock secs ( 0.01 usr +  0.00 sys =  0.01 CPU) @ 10000000.00/s (n=100000)
            (warning: too few iterations for a reliable count)

Git and nasty "error: cannot lock existing info/refs fatal"

This is what I did to get rid of all the lock ref issues:

git gc --prune=now
git remote prune origin

This is probably what you only need to do too.

Getting a count of objects in a queryset in django

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

How to get the current time in Python

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

Unable to find velocity template resources

you can try to add these code:

VelocityEngine ve = new VelocityEngine();
String vmPath = request.getSession().getServletContext().getRealPath("${your dir}");
Properties p = new Properties();
p.setProperty("file.resource.loader.path", vmPath+"//");
ve.init(p);

I do this, and pass!

How to check date of last change in stored procedure or function in SQL server

This is the correct solution for finding a function:

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'fn'
AND name = 'fn_NAME'

Remove last characters from a string in C#. An elegant way?

Use:

public static class StringExtensions
{
    /// <summary>
    /// Cut End. "12".SubstringFromEnd(1) -> "1"
    /// </summary>
    public static string SubstringFromEnd(this string value, int startindex)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Substring(0, value.Length - startindex);
    }
}

I prefer an extension method here for two reasons:

  1. I can chain it with Substring. Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
  2. Speed.