Programs & Examples On #Verilog

Verilog is a hardware description language (HDL) used to model electronic systems. It is most commonly used in the design, verification, and implementation of digital logic chips.

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

Using wire or reg with input or output in Verilog

basically reg is used to store values.For example if you want a counter(which will count and thus will have some value for each count),we will use a reg. On the other hand,if we just have a plain signal with 2 values 0 and 1,we will declare it as wire.Wire can't hold values.So assigning values to wire leads to problems....

Verilog generate/genvar in an always block

Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.

In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.

//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;

    always @(posedge sysclk) //Procedural context starts here
    begin
        for (c = 0; c < ROWBITS; c = c + 1) begin: test
            temp[c] <= 1'b0; //Still a genvar
        end
    end

' << ' operator in verilog

<< is a binary shift, shifting 1 to the left 8 places.

4'b0001 << 1 => 4'b0010

>> is a binary right shift adding 0's to the MSB.
>>> is a signed shift which maintains the value of the MSB if the left input is signed.

4'sb1011 >>  1 => 0101
4'sb1011 >>> 1 => 1101

Three ways to indicate left operand is signed:

module shift;
  logic        [3:0] test1 = 4'b1000;
  logic signed [3:0] test2 = 4'b1000;

  initial begin
    $display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
    $display("%b", test2          >>> 1 ); //Declared as signed type
    $display("%b", 4'sb1000       >>> 1 ); //Signed constant
    $finish;
  end
endmodule

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

How to get just numeric part of CSS property with jQuery?

With the replace method, your css value is a string, and not a number.

This method is more clean, simple, and returns a number :

parseFloat($(this).css('marginBottom'));

Maximum value of maxRequestLength?

Right value is below. (Tried)

maxRequestLength="2147483647" targetFramework="4.5.2"/>

Upload files from Java client to a HTTP server

click link get example file upload clint java with apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

and library downalod link

https://hc.apache.org/downloads.cgi

use 4.5.3.zip it's working fine in my code

and my working code..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

     public static void main(String[] args) throws Exception {

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}

Spaces cause split in path with PowerShell

Would this do what you want?:

& "C:\Windows Services\MyService.exe"

Use &, the call operator, to invoke commands whose names or paths are stored in quoted strings and/or are referenced via variables, as in the accepted answer. Invoke-Expression is not only the wrong tool to use in this particular case, it should generally be avoided.

How to remove text from a string?

you can use slice() it returens charcters between start to end (included end point)

   string.slice(start , end);

here is some exmp to show how it works:

var mystr = ("data-123").slice(5); // jast define start point so output is "123"
var mystr = ("data-123").slice(5,7); // define start and end  so output is "12"
var mystr=(",246").slice(1); // returens "246"

Demo

How to debug Google Apps Script (aka where does Logger.log log to?)

UPDATE:

As written in this answer,


Logger.log will either send you an email (eventually) of errors that have happened in your scripts, or, if you are running things from the Script Editor, you can view the log from the last run function by going to View->Logs (still in script editor). Again, that will only show you anything that was logged from the last function you ran from inside Script Editor.

The script I was trying to get working had to do with spreadsheets - I made a spreadsheet todo-checklist type thing that sorted items by priorities and such.

The only triggers I installed for that script were the onOpen and onEdit triggers. Debugging the onEdit trigger was the hardest one to figure out, because I kept thinking that if I set a breakpoint in my onEdit function, opened the spreadsheet, edited a cell, that my breakpoint would be triggered. This is not the case.

To simulate having edited a cell, I did end up having to do something in the actual spreadsheet though. All I did was make sure the cell that I wanted it to treat as "edited" was selected, then in Script Editor, I would go to Run->onEdit. Then my breakpoint would be hit.

However, I did have to stop using the event argument that gets passed into the onEdit function - you can't simulate that by doing Run->onEdit. Any info I needed from the spreadsheet, like which cell was selected, etc, I had to figure out manually.

Anyways, long answer, but I figured it out eventually.


EDIT:

If you want to see the todo checklist I made, you can check it out here

(yes, I know anybody can edit it - that's the point of sharing it!)

I was hoping it'd let you see the script as well. Since you can't see it there, here it is:

function onOpen() {
  setCheckboxes();
};

function setCheckboxes() {
  var checklist = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("checklist");
  var checklist_data_range = checklist.getDataRange();
  var checklist_num_rows = checklist_data_range.getNumRows();
  Logger.log("checklist num rows: " + checklist_num_rows);

  var coredata = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
  var coredata_data_range = coredata.getDataRange();

  for(var i = 0 ; i < checklist_num_rows-1; i++) {
    var split = checklist_data_range.getCell(i+2, 3).getValue().split(" || ");
    var item_id = split[split.length - 1];
    if(item_id != "") {
      item_id = parseInt(item_id);
      Logger.log("setting value at ("+(i+2)+",2) to " + coredata_data_range.getCell(item_id+1, 3).getValue());
      checklist_data_range.getCell(i+2,2).setValue(coredata_data_range.getCell(item_id+1, 3).getValue());
    }
  }
}

function onEdit() {
  Logger.log("TESTING TESTING ON EDIT");
  var active_sheet = SpreadsheetApp.getActiveSheet();
  if(active_sheet.getName() == "checklist") {
    var active_range = SpreadsheetApp.getActiveSheet().getActiveRange();
    Logger.log("active_range: " + active_range);
    Logger.log("active range col: " + active_range.getColumn() + "active range row: " + active_range.getRow());
    Logger.log("active_range.value: " + active_range.getCell(1, 1).getValue());
    Logger.log("active_range. colidx: " + active_range.getColumnIndex());
    if(active_range.getCell(1,1).getValue() == "?" || active_range.getCell(1,1).getValue() == "?") {
      Logger.log("made it!");
      var next_cell = active_sheet.getRange(active_range.getRow(), active_range.getColumn()+1, 1, 1).getCell(1,1);
      var val = next_cell.getValue();
      Logger.log("val: " + val);
      var splits = val.split(" || ");
      var item_id = splits[splits.length-1];
      Logger.log("item_id: " + item_id);

      var core_data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
      var sheet_data_range = core_data.getDataRange();
      var num_rows = sheet_data_range.getNumRows();
      var sheet_values = sheet_data_range.getValues();
      Logger.log("num_rows: " + num_rows);

      for(var i = 0; i < num_rows; i++) {
        Logger.log("sheet_values[" + (i) + "][" + (8) + "] = " + sheet_values[i][8]);
        if(sheet_values[i][8] == item_id) {
          Logger.log("found it! tyring to set it...");
          sheet_data_range.getCell(i+1, 2+1).setValue(active_range.getCell(1,1).getValue());
        }
      }

    }
  }

  setCheckboxes();
};

Simple Vim commands you wish you'd known earlier

You can use a whole set of commands to change text inside brackets / parentheses / quotation marks/ tags. It's super useful to avoid having to find the start and finish of the group. Try ci(, ci{, ci<, ci", ci', ct depending on what kind of object you want to change. And the ca(, ca{, ... variants delete the brackets / quotation marks as well.

Easy to remember: change inside a bracketed statement / change a bracketed statement.

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

Get the last three chars from any string - Java

I would consider right method from StringUtils class from Apache Commons Lang: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)

It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.

Example usage:

StringUtils.right("abcdef", 3)

You can find more examples under the above link.

Truststore and Keystore Definitions

  1. A keystore contains private keys. You only need this if you are a server, or if the server requires client authentication.

  2. A truststore contains CA certificates to trust. If your server’s certificate is signed by a recognized CA, the default truststore that ships with the JRE will already trust it (because it already trusts trustworthy CAs), so you don’t need to build your own, or to add anything to the one from the JRE.

Source

Passing an array by reference

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

Android Animation Alpha

<ImageView
    android:id="@+id/listViewIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/settings"/>  

Remove android:alpha=0.2 from XML-> ImageView.

Split a string into array in Perl

Having $line as it is now, you can simply split the string based on at least one whitespace separator

my @answer = split(' ', $line); # creates an @answer array

then

print("@answer\n");               # print array on one line

or

print("$_\n") for (@answer);      # print each element on one line

I prefer using () for split, print and for.

Check if a parameter is null or empty in a stored procedure

What about combining coalesce and nullif?

SET @PreviousStartDate = coalesce(nullif(@PreviousStartDate, ''), '01/01/2010')

Remove insignificant trailing zeros from a number?

Here's a possible solution:

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

eval(x) --> 1.234
eval(y) --> 1.234001

What is the simplest method of inter-process communication between 2 C# processes?

There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx

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

You can use PowerShell to generate a self-signed certificate with the new-selfsignedcertificate cmdlet:

New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"

Note: makecert.exe is deprecated.

Cmdlet Reference: https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

android.content.Context.getPackageName()' on a null object reference

You solve the issue with a try/ catch. This crash happens when user close the app before the start intent.

try
{
    Intent mIntent = new Intent(getActivity(),MusicHome.class);
    mIntent.putExtra("SigninFragment.user_details", bundle);
    startActivity(mIntent);
}
catch (Exception e) {
    e.printStackTrace();
}

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

Capture characters from standard input without waiting for enter to be pressed

C and C++ take a very abstract view of I/O, and there is no standard way of doing what you want. There are standard ways to get characters from the standard input stream, if there are any to get, and nothing else is defined by either language. Any answer will therefore have to be platform-specific, perhaps depending not only on the operating system but also the software framework.

There's some reasonable guesses here, but there's no way to answer your question without knowing what your target environment is.

Get JavaScript object from array of objects by value of property

If I understand correctly, you want to find the object in the array whose b property is 6?

var found;
jsObjects.some(function (obj) {
  if (obj.b === 6) {
    found = obj;
    return true;
  }
});

Or if you were using underscore:

var found = _.select(jsObjects, function (obj) {
  return obj.b === 6;
});

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can simply do some kind of ajax response filter for incomming responses with $.ajaxSetup. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:

$.ajaxSetup({
    dataFilter: function (data, type) {
        if (data && typeof data == "string") {
            if (data.indexOf('window.location') > -1) {
                eval(data);
            }
        }
        return data;
    }
});

If data is: "window.location = '/Acount/Login'" above filter will catch that and evaluate to make the redirection.

How to get the return value from a thread in python?

Define your target to
1) take an argument q
2) replace any statements return foo with q.put(foo); return

so a function

def func(a):
    ans = a * a
    return ans

would become

def func(a, q):
    ans = a * a
    q.put(ans)
    return

and then you would proceed as such

from Queue import Queue
from threading import Thread

ans_q = Queue()
arg_tups = [(i, ans_q) for i in xrange(10)]

threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]
_ = [t.start() for t in threads]
_ = [t.join() for t in threads]
results = [q.get() for _ in xrange(len(threads))]

And you can use function decorators/wrappers to make it so you can use your existing functions as target without modifying them, but follow this basic scheme.

How can I print the contents of a hash in Perl?

Data::Dumper is your friend.

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

What does PHP keyword 'var' do?

So basically it is an old style and do not use it for newer version of PHP. Better to use Public keyword instead;if you are not in love with var keyword. So instead of using

class Test {
    var $name;
}

Use

class Test {
   public $name;
}

C# Convert a Base64 -> byte[]

You're looking for the FromBase64Transform class, used with the CryptoStream class.

If you have a string, you can also call Convert.FromBase64String.

How to write to file in Ruby?

Zambri's answer found here is the best.

File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }

where your options for <OPTION> are:

r - Read only. The file must exist.

w - Create an empty file for writing.

a - Append to a file.The file is created if it does not exist.

r+ - Open a file for update both reading and writing. The file must exist.

w+ - Create an empty file for both reading and writing.

a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, w is preferable.

How to use java.net.URLConnection to fire and handle HTTP requests?

if you are using http get please remove this line

urlConnection.setDoOutput(true);

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

A longer but more robust version of the accepted answer:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})?;substr($1,0,int(length($1)/2)).($2&&length($1)%2?$2:$ENV{$3||$4});eg' template.txt

This expands all instances of $VAR or ${VAR} to their environment values (or, if they're undefined, the empty string).

It properly escapes backslashes, and accepts a backslash-escaped $ to inhibit substitution (unlike envsubst, which, it turns out, doesn't do this).

So, if your environment is:

FOO=bar
BAZ=kenny
TARGET=backslashes
NOPE=engi

and your template is:

Two ${TARGET} walk into a \\$FOO. \\\\
\\\$FOO says, "Delete C:\\Windows\\System32, it's a virus."
$BAZ replies, "\${NOPE}s."

the result would be:

Two backslashes walk into a \bar. \\
\$FOO says, "Delete C:\Windows\System32, it's a virus."
kenny replies, "${NOPE}s."

If you only want to escape backslashes before $ (you could write "C:\Windows\System32" in a template unchanged), use this slightly-modified version:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\});substr($1,0,int(length($1)/2)).(length($1)%2?$2:$ENV{$3||$4});eg' template.txt

what is the unsigned datatype?

unsigned really is a shorthand for unsigned int, and so defined in standard C.

ASP.NET MVC: Custom Validation by DataAnnotation

Self validated model

Your model should implement an interface IValidatableObject. Put your validation code in Validate method:

public class MyModel : IValidatableObject
{
    public string Title { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Title == null)
            yield return new ValidationResult("*", new [] { nameof(Title) });

        if (Description == null)
            yield return new ValidationResult("*", new [] { nameof(Description) });
    }
}

Please notice: this is a server-side validation. It doesn't work on client-side. You validation will be performed only after form submission.

Need a row count after SELECT statement: what's the optimal SQL approach?

Why don't you put your results into a vector? That way you don't have to know the size before hand.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Help --> Install New Software In work with select box , only I have selected Kepler - http://download.eclipse.org/releases/kepler And then under Programming language category you can find PHP Development tool.

fyi :I have ubuntu

Why does Vim save files with a ~ extension?

Put this line into your vimrc:

set nobk nowb noswf noudf " nobackup nowritebackup noswapfile noundofile


In that would be the:

C:\Program Files (x86)\vim\_vimrc

file for system-wide vim configuration for all users.

Setting the last one noundofile is important in Windows to prevent the creation of *~ tilda files after editing.


I wish Vim had that line included by default. Nobody likes ugly directories.

Let the user choose if and how she wants to enable advanced backup/undo file features first.

This is the most annoying part of Vim.

The next step might be setting up:

set noeb vb t_vb= " errorbells visualbell

to disable beeping in as well :-)

Cannot create PoolableConnectionFactory

try

jdbc:sqlserver://hostname:port;databaseName=TEST

It worked for me after adding colon before port number instead of a comma

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

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

Single huge .css file vs. multiple smaller specific .css files?

You want both worlds.

You want multiple CSS files because your sanity is a terrible thing to waste.

At the same time, it's better to have a single, large file.

The solution is to have some mechanism that combines the multiple files in to a single file.

One example is something like

<link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />

Then, the allcss.php script handles concatenating the files and delivering them.

Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.

This gives you the best of both worlds. Works great for JS as well.

Should functions return null or an empty object?

I tend to

  • return null if the object id doesn't exist when it's not known beforehand whether it should exist.
  • throw if the object id doesn't exist when it should exist.

I differentiate these two scenarios with these three types of methods. First:

Boolean TryGetSomeObjectById(Int32 id, out SomeObject o)
{
    if (InternalIdExists(id))
    {
        o = InternalGetSomeObject(id);

        return true;
    }
    else
    {
        return false;
    }
}

Second:

SomeObject FindSomeObjectById(Int32 id)
{
    SomeObject o;

    return TryGetObjectById(id, out o) ? o : null;
}

Third:

SomeObject GetSomeObjectById(Int32 id)
{
    SomeObject o;

    if (!TryGetObjectById(id, out o))
    {
        throw new SomeAppropriateException();
    }

    return o;
}

Android - Using Custom Font

I've successfully used this before. The only difference between our implementations is that I wasn't using a subfolder in assets. Not sure if that will change anything, though.

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

equivalent of vbCrLf in c#

try this:

AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);

or

AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);

Get the cell value of a GridView row

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="??">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

Constructors in JavaScript objects

Here's a template I sometimes use for OOP-similar behavior in JavaScript. As you can see, you can simulate private (both static and instance) members using closures. What new MyClass() will return is an object with only the properties assigned to the this object and in the prototype object of the "class."

var MyClass = (function () {
    // private static
    var nextId = 1;

    // constructor
    var cls = function () {
        // private
        var id = nextId++;
        var name = 'Unknown';

        // public (this instance only)
        this.get_id = function () { return id; };

        this.get_name = function () { return name; };
        this.set_name = function (value) {
            if (typeof value != 'string')
                throw 'Name must be a string';
            if (value.length < 2 || value.length > 20)
                throw 'Name must be 2-20 characters long.';
            name = value;
        };
    };

    // public static
    cls.get_nextId = function () {
        return nextId;
    };

    // public (shared across instances)
    cls.prototype = {
        announce: function () {
            alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
                  'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
        }
    };

    return cls;
})();

I've been asked about inheritance using this pattern, so here goes:

// It's a good idea to have a utility class to wire up inheritance.
function inherit(cls, superCls) {
    // We use an intermediary empty constructor to create an
    // inheritance chain, because using the super class' constructor
    // might have side effects.
    var construct = function () {};
    construct.prototype = superCls.prototype;
    cls.prototype = new construct;
    cls.prototype.constructor = cls;
    cls.super = superCls;
}

var MyChildClass = (function () {
    // constructor
    var cls = function (surName) {
        // Call super constructor on this instance (any arguments
        // to the constructor would go after "this" in call(…)).
        this.constructor.super.call(this);

        // Shadowing instance properties is a little bit less
        // intuitive, but can be done:
        var getName = this.get_name;

        // public (this instance only)
        this.get_name = function () {
            return getName.call(this) + ' ' + surName;
        };
    };
    inherit(cls, MyClass); // <-- important!

    return cls;
})();

And an example to use it all:

var bob = new MyClass();
bob.set_name('Bob');
bob.announce(); // id is 1, name shows as "Bob"

var john = new MyChildClass('Doe');
john.set_name('John');
john.announce(); // id is 2, name shows as "John Doe"

alert(john instanceof MyClass); // true

As you can see, the classes correctly interact with each other (they share the static id from MyClass, the announce method uses the correct get_name method, etc.)

One thing to note is the need to shadow instance properties. You can actually make the inherit function go through all instance properties (using hasOwnProperty) that are functions, and automagically add a super_<method name> property. This would let you call this.super_get_name() instead of storing it in a temporary value and calling it bound using call.

For methods on the prototype you don't need to worry about the above though, if you want to access the super class' prototype methods, you can just call this.constructor.super.prototype.methodName. If you want to make it less verbose you can of course add convenience properties. :)

Initial bytes incorrect after Java AES/CBC decryption

Another solution using java.util.Base64 with Spring Boot

Encryptor Class

package com.jmendoza.springboot.crypto.cipher;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class Encryptor {

    @Value("${security.encryptor.key}")
    private byte[] key;
    @Value("${security.encryptor.algorithm}")
    private String algorithm;

    public String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8))));
    }

    public String decrypt(String cipherText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
    }
}

EncryptorController Class

package com.jmendoza.springboot.crypto.controller;

import com.jmendoza.springboot.crypto.cipher.Encryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cipher")
public class EncryptorController {

    @Autowired
    Encryptor encryptor;

    @GetMapping(value = "encrypt/{value}")
    public String encrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.encrypt(value);
    }

    @GetMapping(value = "decrypt/{value}")
    public String decrypt(@PathVariable("value") final String value) throws Exception {
        return encryptor.decrypt(value);
    }
}

application.properties

server.port=8082
security.encryptor.algorithm=AES
security.encryptor.key=M8jFt46dfJMaiJA0

Example

http://localhost:8082/cipher/encrypt/jmendoza

2h41HH8Shzc4BRU3hVDOXA==

http://localhost:8082/cipher/decrypt/2h41HH8Shzc4BRU3hVDOXA==

jmendoza

Abstraction VS Information Hiding VS Encapsulation

Abstraction

Abstraction is an act of representing essentail details without including the background details. A abstract class have only method signatures and implementing class can have its own implementation, in this way the complex details will be hidden from the user. Abstraction focuses on the outside view. In otherwords, Abstraction is sepration of interfaces from the actual implementation.

Encapsulation

Encapsulation explains binding the data members and methods into a single unit. Information hiding is the main purpose of encapsulation. Encapsulation is acheived by using access specifiers like private, public, protected. Class member variables are made private so that they cann't be accessible directly to outside world. Encapsulation focuses on the inner view. In otherwords, Encapsulation is a technique used to protect the information in an object from the other object.

Jquery in React is not defined

Add "ref" to h1 tag :

<h1 ref="source">Hey there.</h1>

and
const { source } = this.props; change to const { source } = this.refs;

Get random item from array

echo $items[array_rand($items)];

array_rand()

Table border left and bottom

Give a class .border-lb and give this CSS

.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}

And the HTML

<table width="770">
  <tr>
    <td class="border-lb">picture (border only to the left and bottom ) </td>
    <td>text</td>
  </tr>
  <tr>
    <td>text</td>
    <td class="border-lb">picture (border only to the left and bottom) </td>
  </tr>
</table>

Screenshot

Fiddle: http://jsfiddle.net/FXMVL/

Why is textarea filled with mysterious white spaces?

Furthermore: the textarea tag shows spaces for new lines, tabs, etc, in multiline code.

How do I debug error ECONNRESET in Node.js?

I just figured this out, at least in my use case.

I was getting ECONNRESET. It turned out that the way my client was set up, it was hitting the server with an API call a ton of times really quickly -- and it only needed to hit the endpoint once.

When I fixed that, the error was gone.

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

Browse and display files in a git repo without cloning

Not the exact, but a way around.

Use GitHub Developer API

  1. Opening this will get you the recent commits.

    https://api.github.com/repos/learningequality/ka-lite/commits

    You can get the specific commit details by attaching the commit hash in the end of above url.

  2. All the files ( You need sha for the main tree)

    https://api.github.com/repos/learningequality/ka-lite/git/trees/7b698a988683b161bdcd48a949b01e2b336b4c01

I hope this may help.

How to clear Flutter's Build cache?

If in android studio Tools->Flutter->Clean

enter image description here

gnuplot : plotting data from multiple input files in a single graph

You're so close!

Change

plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548"  using 1:2 title "Flow 3", \ 
plot "print_401125"  using 1:2 title "Flow 4", \
plot "print_401275"  using 1:2 title "Flow 5", \
plot "print_401276"  using 1:2 title "Flow 6"

to

plot "print_1012720" using 1:2 title "Flow 1", \
     "print_1058167" using 1:2 title "Flow 2", \
     "print_193548"  using 1:2 title "Flow 3", \ 
     "print_401125"  using 1:2 title "Flow 4", \
     "print_401275"  using 1:2 title "Flow 5", \
     "print_401276"  using 1:2 title "Flow 6"

The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).

Homebrew refusing to link OpenSSL

Just execute brew info openssland read the information where it says:

If you need to have this software first in your PATH run: echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

SQL - How do I get only the numbers after the decimal?

CAST(RIGHT(MyField, LEN( MyField)-CHARINDEX('.',MyField)+1 ) AS FLOAT)

How to Exit a Method without Exiting the Program?

@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):

Method SetY(int y) ...
Function CalculateY(int x) As Integer ...

Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.

How do I run Visual Studio as an administrator by default?

image showing how to run visual studio as adminstrator by mhamri step 1 to 3

1- either from start menu or when visual studio is open in the task bar, right click on the VS icon

2- in the context menu, right click again on the visual studio icon

3- left click on prorperties

image showing how to run visual studio as adminstrator by mhamri step 4

4- choose advanced

image showing how to run visual studio as adminstrator by mhamri step 5

5- choose Run as Administrator

click ok all the windows, close the visual studio and reopen again.

Accessing elements of Python dictionary by index

Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

And getting how many of them are American (16), do like this:

>>> mydict["Apple"]["American"]
'16'

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

How to fix: "HAX is not working and emulator runs in emulation mode"

Default memory assigned to HAX is 1024MB. And the emulator has 1536MB apparently for Nexus 5x api 25.

if you're using Android Studio,

  • just go to tools -> AVD manager.
  • Then select the emulator and click on pencil button on the right for editing.
  • Go to advanced settings in the new window and change the RAM value to 1024

Works like a charm. :)

screenshot of android studio

How to run a SQL query on an Excel table?

I suggest you to have a look at the MySQL csv storage engine which essentially allows you to load any csv file (easily created from excel) into the database, once you have that, you can use any SQL command you want.

It's worth to have a look at it.

How to change the docker image installation directory?

As recommneded by @mbarthelemy this can be done via the -g option when starting the docker daemon directly.

However, if docker is being started as a system service, it is not recommended to modify the /etc/default/docker file. There is a guideline to this located here.

The correct approach is to create an /etc/docker/daemon.json file on Linux (or Mac) systems or %programdata%\docker\config\daemon.json on Windows. If this file is not being used for anything else, the following fields should suffice:

{
    "graph": "/docker/daemon_files"
}

This is assuming the new location where you want to have docker persist its data is /docker/daemon_files

Update statement with inner join on Oracle

UPDATE table1 t1
SET t1.value = 
    (select t2.CODE from table2 t2 
     where t1.value = t2.DESC) 
WHERE t1.UPDATETYPE='blah';

jQuery $(document).ready and UpdatePanels?

An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.

What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready() for the initial load, then use Microsoft's PageRequestManager (available if you have an update panel on your page) to re-subscribe every update.

$(document).ready(function() {
    // bind your jQuery events here initially
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function() {
    // re-bind your jQuery events here
});

The PageRequestManager is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.

If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs) so you can see what raised the event and only re-bind if needed.

Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx


A better option you may have, depending on your needs, is to use jQuery's .on(). These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use .delegate() or .on(), so in those cases, you're better off re-subscribing.

Split array into chunks

One-liner in ECMA 6

const [list,chuckSize] = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 6]

[...Array(Math.ceil(list.length / chuckSize))].map(_ => list.splice(0,chuckSize))

Rails: Using greater than/less than with a where statement

Update

Rails core team decided to revert this change for a while, in order to discuss it in more detail. See this comment and this PR for more info.

I am leaving my answer only for educational purposes.


new 'syntax' for comparison in Rails 6.1 (Reverted)

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

User.where('id >': 200) 

Here is a link to PR where you can find more examples.

"You tried to execute a query that does not include the specified aggregate function"

I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By clause at the end.enter image description here

min and max value of data type in C

"But glyph", I hear you asking, "what if I have to determine the maximum value for an opaque type whose maximum might eventually change?" You might continue: "What if it's a typedef in a library I don't control?"

I'm glad you asked, because I just spent a couple of hours cooking up a solution (which I then had to throw away, because it didn't solve my actual problem).

You can use this handy maxof macro to determine the size of any valid integer type.

#define issigned(t) (((t)(-1)) < ((t) 0))

#define umaxof(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0xFULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define smaxof(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0x7ULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define maxof(t) ((unsigned long long) (issigned(t) ? smaxof(t) : umaxof(t)))

You can use it like so:

int main(int argc, char** argv) {
    printf("schar: %llx uchar: %llx\n", maxof(char), maxof(unsigned char));
    printf("sshort: %llx ushort: %llx\n", maxof(short), maxof(unsigned short));
    printf("sint: %llx uint: %llx\n", maxof(int), maxof(unsigned int));
    printf("slong: %llx ulong: %llx\n", maxof(long), maxof(unsigned long));
    printf("slong long: %llx ulong long: %llx\n",
           maxof(long long), maxof(unsigned long long));
    return 0;
}

If you'd like, you can toss a '(t)' onto the front of those macros so they give you a result of the type that you're asking about, and you don't have to do casting to avoid warnings.

How to close the current fragment by using Button like the back button?

Try this:

public void removeFragment(Fragment fragment){
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.remove(fragment);
    fragmentTransaction.commit();
}

nginx: send all requests to a single html page

This worked for me:

location / {
    try_files $uri $uri/ /base.html;
}

How to install pkg config in windows?

for w64-based computers you have to install mingw64. If pkg-config.exe is missing then, you can refer to http://ftp.acc.umu.se/pub/gnome/binaries/win64/dependencies/

Unzip and copy/merge pkg-config.exe into your C:\mingw-w64 installation, eg. into on my pc into C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also use the ignore syntax instead of using (or better the 'as any') notation:

// @ts-ignore
$("div.printArea").printArea();

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
{

if($user=="user" && $pass=="pass")

{

$_SESSION['user']= $user;   

//if correct password and name store in session 

}
else {

echo "Invalid user and password";

header("Locatin:form.php");

}

if(isset($_SESSION['user'])) 

{

//your home page code here

exit;
}

How does the "this" keyword work?

Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)

How to fit Windows Form to any screen resolution?

Set the form property to open in maximized state.

this.WindowState = FormWindowState.Maximized;

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

Might want to try

keytool -import -trustcacerts -noprompt -keystore <full path to cacerts> -storepass changeit -alias $REMHOST -file $REMHOST.pem

i honestly have no idea where it puts your certificate if you just write cacerts just give it a full path

Difference between string and StringBuilder in C#

A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.

A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.

Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.

For sample code I suggest you take a look here:

How to get last N records with activerecord?

we can use Model.last(5) or Model.limit(5).order(id: :desc) in rails 5.2

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

Align two divs horizontally side by side center to the page using bootstrap css

This should do the trick:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            ONE
        </div>
        <div class="col-xs-6">
            TWO
        </div>
    </div>
</div>

Have a read of the grid system section of the Bootstrap docs to familiarise yourself with how Bootstrap's grids work:

http://getbootstrap.com/css/#grid

go to link on button click - jquery

You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });

jQuery ui datepicker with Angularjs

I modified the code and wrapped view update inside $apply().

link: function (scope, elem, attrs, ngModelCtrl){   
var updateModel = function(dateText){
    // call $apply to update the model
    scope.$apply(function(){
        ngModelCtrl.$setViewValue(dateText);
    });
};
var options = {
    dateFormat: "dd/mm/yy",
     // handle jquery date change
    onSelect: function(dateText){
        updateModel(dateText);
    }
};
 // jqueryfy the element
elem.datepicker(options);

}

working fiddle - http://jsfiddle.net/hsfid/SrDV2/1/embedded/result/

What is a quick way to force CRLF in C# / .NET?

This is a quick way to do that, I mean.

It does not use an expensive regex function. It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.

So the search is done directly in one for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops. In some cases, a larger page size might be more efficient.

public static string NormalizeNewLine(this string val)
{
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
    {
        char ch = val[i];

        if (ch == '\r')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else if (ch == '\n')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) // Ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else
        {
            res[j++] = ch;
        }
    }

    return new string(res, 0, j);
}

I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?

If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.

Where is adb.exe in windows 10 located?

I know the question was in the context of "android studio 1.5", but I found this answer and have Xamarin installed.

In this case, the location is C:\Program Files (x86)\Android\android-sdk\platform-tools

Find file in directory from command line

When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:

# finds all .java files starting in current directory
find . -print | grep '\.java'

#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'

Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")

What is time_t ultimately a typedef to?

It's a 32-bit signed integer type on most legacy platforms. However, that causes your code to suffer from the year 2038 bug. So modern C libraries should be defining it to be a signed 64-bit int instead, which is safe for a few billion years.

Resolving IP Address from hostname with PowerShell

$computername = $env:computername    
[System.Net.Dns]::GetHostAddresses($computername)  | where {$_.AddressFamily -notlike "InterNetworkV6"} | foreach {echo $_.IPAddressToString }

password for postgres

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

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

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

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

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

img src SVG changing the styles with CSS

To expand on @gringo answer, the Javascript method described in other answers works, but requires the user to download unnecessary image files, and IMO, it bloats your code.

I think a better approach would be to to migrate all 1-color vector graphics to a webfont file. I've used Fort Awesome in the past, and it works great to combine your custom icons/images in SVG format, along with any 3rd party icons you may be using (Font Awesome, Bootstrap icons, etc.) into a single webfont file the user has to download. You can also customize it, so you only include the 3rd party icons you're using. This reduces the number of requests the page has to make, and you're overall page weight, especially if you're already including any 3rd party icons libraries.

If you prefer a more dev oriented option, you could Google "npm svg webfont", and use one of the node modules that's most appropriate for your environment.

Once, you've done either of those two options, then you could easily change the color via CSS, and most likely, you've sped up your site in the process.

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

Simply u can add this to jquery.validationEngine-en.js file

    "onlyLetterNumberSp": {
                "regex": ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,
                "alertText": "* No special characters allowed"
          },

and call it in text field as

<input type="text" class="form-control validate[required,custom[onlyLetterNumberSp]]"  id="title" name="title" placeholder="Title"/>

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

Initializing ArrayList with some predefined values

Personnaly I like to do all the initialisations in the constructor

public Test()
{
  symbolsPresent = new ArrayList<String>();
  symbolsPresent.add("ONE");
  symbolsPresent.add("TWO");
  symbolsPresent.add("THREE");
  symbolsPresent.add("FOUR");
}

Edit : It is a choice of course and others prefer to initialize in the declaration. Both are valid, I have choosen the constructor because all type of initialitions are possible there (if you need a loop or parameters, ...). However I initialize the constants in the declaration on the top on the source.
The most important is to follow a rule that you like and be consistent in our classes.

Date ticks and rotation in matplotlib

An easy solution which avoids looping over the ticklabes is to just use

fig.autofmt_xdate()

This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call

fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')

The additional bottom argument is equivalent to setting plt.subplots_adjust(bottom=bottom), which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.

So basically here you have all the settings you need to have a nice date axis in a single command.

A good example can be found on the matplotlib page.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had the same problem and I solved by installing Service pack 22 and it fixed it.

Alternative to itoa() for converting integer to string C++?

?++11 finally resolves this providing std::to_string. Also boost::lexical_cast is handy tool for older compilers.

How to parse a string into a nullable int

Old topic, but how about:

public static int? ParseToNullableInt(this string value)
{
     return String.IsNullOrEmpty(value) ? null : (int.Parse(value) as int?);
}

I like this better as the requriement where to parse null, the TryParse version would not throw an error on e.g. ToNullableInt32(XXX). That may introduce unwanted silent errors.

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

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

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they


# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = [email protected]

Or

msg = "From: [email protected]" +
      "To: [email protected]" +
      "BCC: [email protected]" +
      "Subject: You've got mail!" +
      "This is the message body"

The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you'll need to import a class from email.message instead of merely passing strings into sendmail.

selecting unique values from a column

Use something like this in case you also want to output products details per date as JSON and the MySQL version does not support JSON functions.

SELECT `date`,
CONCAT('{',GROUP_CONCAT('{\"id\": \"',`product_id`,'\",\"name\": \"',`product_name`,'\"}'),'}') as `productsJSON`
FROM `buy` group by `date` 
order by `date` DESC

 product_id product_name     date  
|    1     |     azd    | 2011-12-12 |
|    2     |     xyz    | 2011-12-12 |
|    3     |     ase    | 2011-12-11 |
|    4     |     azwed  | 2011-12-11 |
|    5     |     wed    | 2011-12-10 |
|    6     |     cvg    | 2011-12-10 |
|    7     |     cvig   | 2011-12-09 |

RESULT
       date                                productsJSON
2011-12-12T00:00:00Z    {{"id": "1","name": "azd"},{"id": "2","name": "xyz"}}
2011-12-11T00:00:00Z    {{"id": "3","name": "ase"},{"id": "4","name": "azwed"}}
2011-12-10T00:00:00Z    {{"id": "5","name": "wed"},{"id": "6","name": "cvg"}}
2011-12-09T00:00:00Z    {{"id": "7","name": "cvig"}}

Try it out in SQL Fiddle

If you are using a MySQL version that supports JSON functions then the above query could be re-written:

SELECT `date`,JSON_OBJECTAGG(CONCAT('product-',`product_id`),JSON_OBJECT('id', `product_id`, 'name', `product_name`)) as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC;

Try both in DB Fiddle

Choose folders to be ignored during search in VS Code

The short answer is to comma-separate the folders you want to ignore in "files to exclude".

  1. Start workspace wide search: CTRL+SHIFT+f
  2. Expand the global search with the three-dot button
  3. Enter your search term
  4. As an example, in the files to exclude-input field write babel,concat to exclude the folder "babel" and the folder "concat" in the search (make sure the exclude button is enabled).
  5. Press enter to get the results.

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

In my case:

sudo -E add-apt-repository ppa:linuxuprising/java

sudo apt-get update

sudo apt install  oracle-java12-installer

that works fine

How do you kill all current connections to a SQL Server 2005 database?

ALTER DATABASE [Test]
SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER DATABASE [Test]
SET ONLINE

When should I use a struct rather than a class in C#?

Nah - I don't entirely agree with the rules. They are good guidelines to consider with performance and standardization, but not in light of the possibilities.

As you can see in the responses, there are a lot of creative ways to use them. So, these guidelines need to just be that, always for the sake of performance and efficiency.

In this case, I use classes to represent real world objects in their larger form, I use structs to represent smaller objects that have more exact uses. The way you said it, "a more cohesive whole." The keyword being cohesive. The classes will be more object oriented elements, while structs can have some of those characteristics, though on a smaller scale. IMO.

I use them a lot in Treeview and Listview tags where common static attributes can be accessed very quickly. I have always struggled to get this info another way. For example, in my database applications, I use a Treeview where I have Tables, SPs, Functions, or any other objects. I create and populate my struct, put it in the tag, pull it out, get the data of the selection and so forth. I wouldn't do this with a class!

I do try and keep them small, use them in single instance situations, and keep them from changing. It's prudent to be aware of memory, allocation, and performance. And testing is so necessary.

How can I retrieve Id of inserted entity using Entity framework?

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you:

using (var context = new MyContext())
{
  context.MyEntities.Add(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

Set min-width in HTML table's <td>

None of these solutions worked for me. The only workaround I could find was, adding all the min-width sizes together and applying that to the entire table. This obviously only works if you know all the column sizes in advanced, which I do. My tables look something like this:

var columns = [
  {label: 'Column 1', width: 80 /* plus other column config */},
  {label: 'Column 2', minWidth: 110 /* plus other column config */},
  {label: 'Column 3' /* plus other column config */},
];

const minimumTableWidth = columns.reduce((sum, column) => {
  return sum + (column.width || column.minWidth || 0);
}, 0);

tableElement.style.minWidth = minimumTableWidth + 'px';

This is an example and not recommended code. Fit the idea to your requirements. For example, the above is javascript and won't work if the user has JS disabled, etc.

Why can't I change my input value in React even with the onChange listener

In React, the component will re-render (or update) only if the state or the prop changes.

In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.

onTodoChange(event) {
        // update the state
    this.setState({name: event.target.value});
}

jQuery Scroll To bottom of the page

something like this:

var $target = $('html,body'); 
$target.animate({scrollTop: $target.height()}, 1000);

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

What do \t and \b do?

The C standard (actually C99, I'm not up to date) says:

Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows:

\b (backspace) Moves the active position to the previous position on the current line. [...]

\t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. [...]

Both just move the active position, neither are supposed to write any character on or over another character. To overwrite with a space you could try: puts("foo\b \tbar"); but note that on some display devices - say a daisy wheel printer - the o will show the transparent space.

Delete empty lines using sed

I am missing the awk solution:

awk 'NF' file

Which would return:

xxxxxx
yyyyyy
zzzzzz

How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.

Can I pass a JavaScript variable to another browser window?

Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:

var x = 10;
window.open('mypage.php?x='+x);

How to send parameters with jquery $.get()

This is what worked for me:

$.get({
    method: 'GET',
    url: 'api.php',
    headers: {
        'Content-Type': 'application/json',
    },
    // query parameters go under "data" as an Object
    data: {
        client: 'mikescafe'
    }
});

will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe

Good Luck.

How can I debug my JavaScript code?

Start with Firebug and IE Debugger.

Be careful with debuggers in JavaScript though. Every once in a while they will affect the environment just enough to cause some of the errors you are trying to debug.

Examples:

For Internet Explorer, it's generally a gradual slowdown and is some kind of memory leak type deal. After a half hour or so I need to restart. It seems to be fairly regular.

For Firebug, it's probably been more than a year so it may have been an older version. As a result, I don't remember the specifics, but basically the code was not running correctly and after trying to debug it for a while I disabled Firebug and the code worked fine.

TypeError: got multiple values for argument

Simply put you can't do the following:

class C(object):
    def x(self, y, **kwargs):
        # Which y to use, kwargs or declaration? 
        pass

c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS

Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

Go to Matching Brace in Visual Studio?

On a Spanish keyboard it is CTRL + ¿ (or CTRL + ¡).

How to iterate over a JavaScript object?

If you wanted to iterate the whole object at once you could use for in loop:

for (var i in obj) {
  ...
}

But if you want to divide the object into parts in fact you cannot. There's no guarantee that properties in the object are in any specified order. Therefore, I can think of two solutions.

First of them is to "remove" already read properties:

var i = 0;
for (var key in obj) {
    console.log(obj[key]);
    delete obj[key];
    if ( ++i > 300) break;
}

Another solution I can think of is to use Array of Arrays instead of the object:

var obj = [['key1', 'value1'], ['key2', 'value2']];

Then, standard for loop will work.

No notification sound when sending notification from firebase in android

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.

How do I remove the old history from a git repository?

According to the Git repo of the BFG tool, it "removes large or troublesome blobs as git-filter-branch does, but faster - and is written in Scala".

https://github.com/rtyley/bfg-repo-cleaner

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

How can I hash a password in Java?

Among all the standard hash schemes, LDAP ssha is the most secure one to use,

http://www.openldap.org/faq/data/cache/347.html

I would just follow the algorithms specified there and use MessageDigest to do the hash.

You need to store the salt in your database as you suggested.

The model backing the 'ApplicationDbContext' context has changed since the database was created

this comes because you add some property to one of your model and you did not update-Database . to solve this you have to remove it from model or you have to add-migration anyProperName with that properties and Update-database.

How to check Elasticsearch cluster health?

If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:

Kibana => DevTools => Console:

GET /_cluster/health 

enter image description here enter image description here

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

What is the difference between Session.Abandon() and Session.Clear()

this code works and dont throw any exception:

Session.Abandon();  
Session["tempKey1"] = "tempValue1";

One thing to note here that Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request. That simply means that suppose you tried to access value in code just after the session.abandon command was executed, it will be still there. So do not get confused if your code is just not working even after issuing session.abandon command and immediately doing some logic with the session.

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

Running two projects at once in Visual Studio

Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.

Solution properties dialog

How to position absolute inside a div?

One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

_x000D_
_x000D_
 #box {_x000D_
        background-color: #000;_x000D_
        position: relative;     _x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }_x000D_
    _x000D_
    .a {_x000D_
        width: 210px;_x000D_
        background-color: #fff;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    .b {_x000D_
        width: 100px; /* So you can see the other one */_x000D_
        position: absolute;_x000D_
        top: 10px; left: 10px;_x000D_
        background-color: red;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    #after {_x000D_
        background-color: yellow;_x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }
_x000D_
    <div id="box">_x000D_
        <div class="a">Lorem</div>_x000D_
        <div class="b">Lorem</div>_x000D_
    </div>_x000D_
    <div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_

(Note that I've made the widths different, so you can see one behind the other.)

Edit after Justine's comment: Then your only option is to specify the height of #box. This:

#box {
    /* ... */
    height: 30px;
}

works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

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

before that works properly.

Return list using select new in LINQ

try this solution for me its working

     public List<ProjectInfo> GetProjectForCombo()
      {
    using (MyDataContext db = new MyDataContext 
    (DBHelper.GetConnectionString()))
         {
        return  (from pro in db.Projects
                    select new { query  }.query).ToList();
        }
      }

Passing parameters on button action:@selector

You can set tag of the button and access it from sender in action

[btnHome addTarget:self action:@selector(btnMenuClicked:)     forControlEvents:UIControlEventTouchUpInside];
                    btnHome.userInteractionEnabled = YES;
                    btnHome.tag = 123;

In the called function

-(void)btnMenuClicked:(id)sender
{
[sender tag];

    if ([sender tag] == 123) {
        // Do Anything
    }
}

How can I perform static code analysis in PHP?

There a new tool called nWire for PHP. It is a code exploration plugin for Eclipse PDT and Zend Studio 7.x. It enables real-time code analysis for PHP and provides the following tools:

  • Code visualization - interactive graphical representation of components and associations.
  • Code navigation - unique navigation view shows all the associations and works with you while you write or read code.
  • Quick search - search as you type for methods, fields, file, etc.

How do you make websites with Java?

You are asking a few different questions...

  • How can I create websites with Java?

The simplest way to start making websites with Java is to use JSP. JSP stands for Java Server Pages, and it allows you to embed HTML in Java code files for dynamic page creation. In order to compile and serve JSPs, you will need a Servlet Container, which is basically a web server that runs Java classes. The most popular basic Servlet Container is called Tomcat, and it's provided free by The Apache Software Foundation. Follow the tutorial that cletus provided here.

Once you have Tomcat up and running, and have a basic understanding of how to deploy JSPs, you'll probably want to start creating your own JSPs. I always like IBM developerWorks tutorials. They have a JSP tutorial here that looks alright (though a bit dated).

You'll find out that there is a lot more to Java web development than JSPs, but these tutorials will get you headed in the right direction.

  • PHP vs. Java

This is a pretty subjective question. PHP and Java are just tools, and in the hands of a bad programmer, any tool is useless. PHP and Java both have their strengths and weaknesses, and the discussion of them is probably outside of the scope of this post. I'd say that if you already know Java, stick with Java.

  • File I/O vs. MySQL

MySQL is better suited for web applications, as it is designed to handle many concurrent users. You should know though that Java can use MySQL just as easily as PHP can, through JDBC, Java's database connectivity framework.

How to call a View Controller programmatically?

        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone_iOS7" bundle:nil];
            AccountViewController * controller = [storyboard instantiateViewControllerWithIdentifier:@"accountView"];
            //            [self presentViewController:controller animated:YES completion:nil];

        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }

        [topRootViewController presentViewController:controller animated:YES completion:nil];

TypeLoadException says 'no implementation', but it is implemented

I faced almost same issue. I was scratching my head what is causing this error. I cross checked, all the methods were implemented.

On Googling I got this link among other. Based on @Paul McLink comment, This two steps resolved the issue.

  1. Restart Visual Studio
  2. Clean, Build (Rebuild)

and the error gone.

Restart VS Plugin

Thanks Paul :)

Hope this helps someone who come across this error :)

Android ListView selected item stay highlighted

*please be sure there is no Ripple at your root layout of list view container

add this line to your list view

android:listSelector="@drawable/background_listview"

here is the "background_listview.xml" file

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white_background" android:state_pressed="true" />
<item android:drawable="@color/primary_color" android:state_focused="false" /></selector>

the colors that used in the background_listview.xml file :

<color name="primary_color">#cc7e00</color>
<color name="white_background">#ffffffff</color>

after these

(clicked item contain orange color until you click another item)

UNIX export command

export is used to set environment variables. For example:

export EDITOR=pico

Will set your default text editor to be the pico command.

SVN- How to commit multiple files in a single shot

You can use --targets ARG option where ARG is the name of textfile containing the targets for commit.

svn ci --targets myfiles.txt -m "another commit"

How to get the name of the current Windows user in JavaScript

I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information

Is there a built-in function to print all the current properties and values of an object?

A metaprogramming example Dump object with magic:

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

Without arguments:

$ python dump.py
<__main__.Data instance at 0x00A052D8>

With Gnosis Utils:

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

It is a bit outdated but still working.

How do I style a <select> dropdown with only CSS?

Here's a solution based on my favorite ideas from this discussion. This allows styling a <select> element directly without any additional markup.

It works Internet Explorer 10 (and later) with a safe fallback for Internet Explorer 8/9. One caveat for these browsers is that the background image must be positioned and be small enough to hide behind the native expand control.

HTML

<select name='options'>
  <option value='option-1'>Option 1</option>
  <option value='option-2'>Option 2</option>
  <option value='option-3'>Option 3</option>
</select>

SCSS

body {
  padding: 4em 40%;
  text-align: center;
}

select {
  $bg-color: lightcyan;
  $text-color: black;
  appearance: none; // Using -prefix-free http://leaverou.github.io/prefixfree/
  background: {
    color: $bg-color;
    image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/1255/caret--down-15.png");
    position: right;
    repeat: no-repeat;
  }
  border: {
    color: mix($bg-color, black, 80%);
    radius: .2em;
    style: solid;
    width: 1px;
    right-color: mix($bg-color, black, 60%);
    bottom-color: mix($bg-color, black, 60%);
  }
  color: $text-color;
  padding: .33em .5em;
  width: 100%;
}

// Removes default arrow for Internet Explorer 10 (and later)
// Internet Explorer 8/9 gets the default arrow which covers the caret
// image as long as the caret image is smaller than and positioned
// behind the default arrow
select::-ms-expand {
    display: none;
}

CodePen

http://codepen.io/ralgh/pen/gpgbGx

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

How to downgrade Node version

Steps to downgrade to node8

brew install node@8
brew link node@8 --force

if warning remove the folder and files as indicated in the warning then again the command :

brew link node@8 --force

How does Go update third-party packages?

To specify versions, or commits:

go get -u [email protected]

go get -u otherpackage@git-sha

See https://github.com/golang/go/wiki/Modules#daily-workflow

Convert string to datetime in vb.net

Pass the decode pattern to ParseExact

Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)

ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string

Get loop counter/index using for…of syntax in JavaScript

As others have said, you shouldn't be using for..in to iterate over an array.

for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }

If you want cleaner syntax, you could use forEach:

myArray.forEach( function ( val, i ) { ... } );

If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.

How to get the next auto-increment id in mysql

You have to connect to MySQL and select a database before you can do this

$table_name = "myTable"; 
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'"); 
$row = mysql_fetch_array($query); 
$next_inc_value = $row["AUTO_INCREMENT"];  

clearing a char array c

Use:

memset(my_custom_data, 0, sizeof(my_custom_data));

Or:

memset(my_custom_data, 0, strlen(my_custom_data));

Comparing boxed Long values 127 and 128

num1 and num2 are Long objects. You should be using equals() to compare them. == comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.

if (num1.equals(num1))
{
 //code
}

how to read value from string.xml in android?

Solution 1

Context context;
String mess = context.getString(R.string.mess_1)

Solution 2

String mess = getString(R.string.mess_1)

How can I flush GPU memory using CUDA (physical reset is unavailable)

One can also use nvtop, which gives an interface very similar to htop, but showing your GPU(s) usage instead, with a nice graph. You can also kill processes directly from here.

Here is a link to its Github : https://github.com/Syllo/nvtop

NVTOP interface

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

When to use a linked list over an array/array list?

Hmm, Arraylist can be used in cases like follows I guess:

  1. you are not sure how many elements will be present
  2. but you need to access all the elements randomly through indexing

For eg, you need to import and access all elements in a contact list (the size of which is unknown to you)

Auto start node.js server on boot

This can easily be done manually with the Windows Task Scheduler.

  • First, install forever.
  • Then, create a batch file that contains the following:

    cd C:\path\to\project\root
    call C:\Users\Username\AppData\Roaming\npm\forever.cmd start server.js
    exit 0
    
  • Lastly, create a scheduled task that runs when you log on. This task should call the batch file.

Case insensitive std::string.find()

#include <iostream>
using namespace std;

template <typename charT>
struct ichar {
    operator charT() const { return toupper(x); }
    charT x;
};
template <typename charT>
static basic_string<ichar<charT> > *istring(basic_string<charT> &s) { return (basic_string<ichar<charT> > *)&s; }
template <typename charT>
static ichar<charT> *istring(const charT *s) { return (ichar<charT> *)s; }

int main()
{
    string s = "The STRING";
    wstring ws = L"The WSTRING";
    cout << istring(s)->find(istring("str")) << " " << istring(ws)->find(istring(L"wstr"))  << endl;
}

A little bit dirty, but short & fast.

What are the options for storing hierarchical data in a relational database?

This design was not mentioned yet:

Multiple lineage columns

Though it has limitations, if you can bear them, it's very simple and very efficient. Features:

  • Columns: one for each lineage level, refers to all the parents up to the root, levels below the current items' level are set to 0 (or NULL)
  • There is a fixed limit to how deep the hierarchy can be
  • Cheap ancestors, descendants, level
  • Cheap insert, delete, move of the leaves
  • Expensive insert, delete, move of the internal nodes

Here follows an example - taxonomic tree of birds so the hierarchy is Class/Order/Family/Genus/Species - species is the lowest level, 1 row = 1 taxon (which corresponds to species in the case of the leaf nodes):

CREATE TABLE `taxons` (
  `TaxonId` smallint(6) NOT NULL default '0',
  `ClassId` smallint(6) default NULL,
  `OrderId` smallint(6) default NULL,
  `FamilyId` smallint(6) default NULL,
  `GenusId` smallint(6) default NULL,
  `Name` varchar(150) NOT NULL default ''
);

and the example of the data:

+---------+---------+---------+----------+---------+-------------------------------+
| TaxonId | ClassId | OrderId | FamilyId | GenusId | Name                          |
+---------+---------+---------+----------+---------+-------------------------------+
|     254 |       0 |       0 |        0 |       0 | Aves                          |
|     255 |     254 |       0 |        0 |       0 | Gaviiformes                   |
|     256 |     254 |     255 |        0 |       0 | Gaviidae                      |
|     257 |     254 |     255 |      256 |       0 | Gavia                         |
|     258 |     254 |     255 |      256 |     257 | Gavia stellata                |
|     259 |     254 |     255 |      256 |     257 | Gavia arctica                 |
|     260 |     254 |     255 |      256 |     257 | Gavia immer                   |
|     261 |     254 |     255 |      256 |     257 | Gavia adamsii                 |
|     262 |     254 |       0 |        0 |       0 | Podicipediformes              |
|     263 |     254 |     262 |        0 |       0 | Podicipedidae                 |
|     264 |     254 |     262 |      263 |       0 | Tachybaptus                   |

This is great because this way you accomplish all the needed operations in a very easy way, as long as the internal categories don't change their level in the tree.

In Powershell what is the idiomatic way of converting a string to an int?

A quick true/false test of whether it will cast to [int]

[bool]($var -as [int] -is [int])

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

How can I get the ID of an element using jQuery?

$('#test').attr('id') In your example:

<div id="test"></div>

$(document).ready(function() {
    alert($('#test').attr('id'));
}); 

array filter in python?

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))

Shrink a YouTube video to responsive width

See full gist here and live example here.

#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }

<div id="hero">
    <div class="container">
        <div class="row-fluid">
            <script src="https://www.youtube.com/iframe_api"></script>
            <center>
            <div class="videoWrapper">
                 <div id="player"></div>
            </div>
            </center>
            <script>
            function onYouTubeIframeAPIReady() { 
                player = new YT.Player('player', {
                   videoId:'xxxxxxxxxxx',playerVars: {  controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
                } );
                resizeHeroVideo();
             }
             </script>
        </div>
    </div>
</div>

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.

finding first day of the month in python

My solution to find the first and last day of the current month:

def find_current_month_last_day(today: datetime) -> datetime:
    if today.month == 2:
        return today.replace(day=28)

    if today.month in [4, 6, 9, 11]:
        return today.replace(day=30)

    return today.replace(day=31)


def current_month_first_and_last_days() -> tuple:
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    first_date = today.replace(day=1)
    last_date = find_current_month_last_day(today)
    return first_date, last_date

Unable instantiate android.gms.maps.MapFragment

Apart from many of the things mentioned before, to me it was important to mark the .jar also in Order and Export. As far as I can tell, is not usually mentioned and to me it was crucial.

Mark the lib in Order and Export

CSS rotation cross browser with jquery.animate()

To do this cross browser including IE7+, you will need to expand the plugin with a transformation matrix. Since vendor prefix is done in jQuery from jquery-1.8+ I will leave that out for the transform property.

$.fn.animateRotate = function(endAngle, options, startAngle)
{
    return this.each(function()
    {
        var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
            anims = {}, animsEnd = {};
        if(typeof options !== 'object')
        {
            options = {};
        }
        else if(typeof options.extra === 'object')
        {
            anims = options.extra;
            animsEnd = options.extra;
        }
        anims.deg = startAngle;
        animsEnd.deg = endAngle;
        options.step = function(now, fx)
        {
            if(fx.prop === 'deg')
            {
                if(noTransform)
                {
                    rad = now * (Math.PI * 2 / 360);
                    costheta = Math.cos(rad);
                    sintheta = Math.sin(rad);
                    matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
                    $('body').append('Test ' + matrixValues + '<br />');
                    elem.css({
                        'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
                    });
                }
                else
                {
                    elem.css({
                        //webkitTransform: 'rotate('+now+'deg)',
                        //mozTransform: 'rotate('+now+'deg)',
                        //msTransform: 'rotate('+now+'deg)',
                        //oTransform: 'rotate('+now+'deg)',
                        transform: 'rotate('+now+'deg)'
                    });
                }
            }
        };
        if(startAngle)
        {
            $(anims).animate(animsEnd, options);
        }
        else
        {
            elem.animate(animsEnd, options);
        }
    });
};

Note: The parameters options and startAngle are optional, if you only need to set startAngle use {} or null for options.

Example usage:

var obj = $(document.createElement('div'));
obj.on("click", function(){
    obj.stop().animateRotate(180, {
        duration: 250,
        complete: function()
        {
            obj.animateRotate(0, {
                duration: 250
            });
        }
    });
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);

See also this jsfiddle for a demo.

Update: You can now also pass extra: {} in the options. This will make you able to execute other animations simultaneously. For example:

obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});

This will rotate the element 90 degrees, and move it to the right with 100px and make it semi-transparent all at the same time during the animation.

How can I get npm start at a different directory?

Below Command where project is a folder which contains package.json file

npm run --prefix project ${COMMAND}

is working as well. Useful in Docker based applications.

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

Using Pipes within ngModel on INPUT Elements in Angular

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)] actually encompasses. [] is one-way binding syntax and () is event binding syntax. When used together - [()] Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.

The reason you cannot use [()] with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.

See Angular Template Syntax for more info.

printing out a 2-D array in Matrix format

Here's my efficient approach for displaying 2-D integer array using a StringBuilder array.

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}

enter image description here

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

How to start automatic download of a file in Internet Explorer?

Nice jquery solution:

jQuery('a.auto-start').get(0).click();

You can even set different file name for download inside <a> tag:

Your download should start shortly. If not - you can use
<a href="/attachments-31-3d4c8970.zip" download="attachments-31.zip" class="download auto-start">direct link</a>.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

How do I remove a substring from the end of a string in Python?

If you know it's an extension, then

url = 'abcdc.com'
...
url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split

This works equally well with abcdc.com or www.abcdc.com or abcdc.[anything] and is more extensible.

How to update ruby on linux (ubuntu)?

sudo apt-get install ruby1.9

should do the trick.

You can find what libraries are available to install by

apt-cache search <your search term>

So I just did apt-cache search ruby | grep 9 to find it.

You'll probably need to invoke the new Ruby as ruby1.9, because Ubuntu will probably default to 1.8 if you just type ruby.

How to make image hover in css?

It will not work like this, put both images as background images:

.bg-img {
    background:url(images/yourImg.jpg) no-repeat 0 0;
}

.bg-img:hover {
    background:url(images/yourImg-1.jpg) no-repeat 0 0;
}

How to remove all white space from the beginning or end of a string?

Trim() Removes all leading and trailing white-space characters from the current string. Trim(Char) Removes all leading and trailing instances of a character from the current string. Trim(Char[]) Removes all leading and trailing occurrences of a set of characters specified in an array from the current string.

Look at the following example that I quoted from Microsoft's documentation page.

char[] charsToTrim = { '*', ' ', '\''};
string banner = "*** Much Ado About Nothing ***";
string result = banner.Trim(charsToTrim);
Console.WriteLine("Trimmmed\n   {0}\nto\n   '{1}'", banner, result);

// The example displays the following output:
//       Trimmmed
//          *** Much Ado About Nothing ***
//       to
//          'Much Ado About Nothing'

Regex date format validation on Java

For fine control, consider an InputVerifier using the SimpleDateFormat("YYYY-MM-dd") suggested by Steve B.

Get clicked item and its position in RecyclerView

In onViewHolder set onClickListiner to any view and in side click use this code :

Toast.makeText(Drawer_bar.this, "position" + position, Toast.LENGTH_SHORT).show();

Replace Drawer_Bar with your Activity name.

How to get current SIM card number in Android?

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

=================================================================================

Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

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

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for whatsapp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.

right click context menu for datagridview

For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.

It's quite tested and works well. I Hope you find it useful.

    /// <summary>
    /// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
    /// </summary>
    /// <param name="dgv">DataGridView that produces the event</param>
    /// <param name="e">Event arguments produced</param>
    /// <returns>The Location of the click, relative to the DataGridView</returns>
    public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        if (dgv.RowHeadersVisible)
            x += dgv.RowHeadersWidth;
        if (dgv.ColumnHeadersVisible)
            y += dgv.ColumnHeadersHeight;
        for (int j = 0; j < e.ColumnIndex; j++)
            if (dgv.Columns[j].Visible)
                x += dgv.Columns[j].Width;
        for (int i = 0; i < e.RowIndex; i++)
            if (dgv.Rows[i].Visible)
                y += dgv.Rows[i].Height;
        return new Point(x, y);
    }

Number input type that takes only integers?

The easy way using JavaScript:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

make sure your package name in "google-services.json" file is same with your apps's package name.

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")